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 */
79 /* submission of played songs */
80 vlc_url_t p_submit_url; /**< where to submit data */
82 /* submission of playing song */
84 char *psz_nowp_host; /**< where to submit data */
85 int i_nowp_port; /**< port to which submit */
86 char *psz_nowp_file; /**< file to which submit */
88 char psz_auth_token[33]; /**< Authentication token */
90 /* data about song currently playing */
91 audioscrobbler_song_t p_current_song; /**< song being played */
93 mtime_t time_pause; /**< time when vlc paused */
94 mtime_t time_total_pauses; /**< total time in pause */
96 bool b_submit; /**< do we have to submit ? */
98 bool b_state_cb; /**< if we registered the
101 bool b_meta_read; /**< if we read the song's
102 * metadata already */
105 static int Open (vlc_object_t *);
106 static void Close (vlc_object_t *);
107 static void Run (intf_thread_t *);
109 /*****************************************************************************
111 ****************************************************************************/
113 #define USERNAME_TEXT N_("Username")
114 #define USERNAME_LONGTEXT N_("The username of your last.fm account")
115 #define PASSWORD_TEXT N_("Password")
116 #define PASSWORD_LONGTEXT N_("The password of your last.fm account")
117 #define URL_TEXT N_("Scrobbler URL")
118 #define URL_LONGTEXT N_("The URL set for an alternative scrobbler engine")
120 /* This error value is used when last.fm plugin has to be unloaded. */
121 #define VLC_AUDIOSCROBBLER_EFATAL -69
123 /* last.fm client identifier */
124 #define CLIENT_NAME PACKAGE
125 #define CLIENT_VERSION VERSION
128 set_category(CAT_INTERFACE)
129 set_subcategory(SUBCAT_INTERFACE_CONTROL)
130 set_shortname(N_("Audioscrobbler"))
131 set_description(N_("Submission of played songs to last.fm"))
132 add_string("lastfm-username", "",
133 USERNAME_TEXT, USERNAME_LONGTEXT, false)
134 add_password("lastfm-password", "",
135 PASSWORD_TEXT, PASSWORD_LONGTEXT, false)
136 add_string("scrobbler-url", "post.audioscrobbler.com",
137 URL_TEXT, URL_LONGTEXT, false)
138 set_capability("interface", 0)
139 set_callbacks(Open, Close)
142 /*****************************************************************************
143 * DeleteSong : Delete the char pointers in a song
144 *****************************************************************************/
145 static void DeleteSong(audioscrobbler_song_t* p_song)
147 FREENULL(p_song->psz_a);
148 FREENULL(p_song->psz_b);
149 FREENULL(p_song->psz_t);
150 FREENULL(p_song->psz_m);
151 FREENULL(p_song->psz_n);
154 /*****************************************************************************
155 * ReadMetaData : Read meta data when parsed by vlc
156 *****************************************************************************/
157 static void ReadMetaData(intf_thread_t *p_this)
159 input_thread_t *p_input;
160 input_item_t *p_item;
162 intf_sys_t *p_sys = p_this->p_sys;
164 p_input = playlist_CurrentInput(pl_Get(p_this));
168 p_item = input_GetItem(p_input);
171 vlc_object_release(p_input);
175 #define ALLOC_ITEM_META(a, b) do { \
176 char *psz_meta = input_item_Get##b(p_item); \
177 if (psz_meta && *psz_meta) \
178 a = encode_URI_component(psz_meta); \
182 vlc_mutex_lock(&p_sys->lock);
184 p_sys->b_meta_read = true;
186 ALLOC_ITEM_META(p_sys->p_current_song.psz_a, Artist);
187 if (!p_sys->p_current_song.psz_a)
189 msg_Dbg(p_this, "No artist..");
190 DeleteSong(&p_sys->p_current_song);
194 ALLOC_ITEM_META(p_sys->p_current_song.psz_t, Title);
195 if (!p_sys->p_current_song.psz_t)
197 msg_Dbg(p_this, "No track name..");
198 DeleteSong(&p_sys->p_current_song);
202 /* Now we have read the mandatory meta data, so we can submit that info */
203 p_sys->b_submit = true;
205 ALLOC_ITEM_META(p_sys->p_current_song.psz_b, Album);
206 if (!p_sys->p_current_song.psz_b)
207 p_sys->p_current_song.psz_b = calloc(1, 1);
209 ALLOC_ITEM_META(p_sys->p_current_song.psz_m, TrackID);
210 if (!p_sys->p_current_song.psz_m)
211 p_sys->p_current_song.psz_m = calloc(1, 1);
213 p_sys->p_current_song.i_l = input_item_GetDuration(p_item) / 1000000;
215 ALLOC_ITEM_META(p_sys->p_current_song.psz_n, TrackNum);
216 if (!p_sys->p_current_song.psz_n)
217 p_sys->p_current_song.psz_n = calloc(1, 1);
218 #undef ALLOC_ITEM_META
220 msg_Dbg(p_this, "Meta data registered");
223 vlc_mutex_unlock(&p_sys->lock);
224 vlc_object_release(p_input);
227 /*****************************************************************************
228 * AddToQueue: Add the played song to the queue to be submitted
229 *****************************************************************************/
230 static void AddToQueue (intf_thread_t *p_this)
233 intf_sys_t *p_sys = p_this->p_sys;
235 vlc_mutex_lock(&p_sys->lock);
236 if (!p_sys->b_submit)
239 /* wait for the user to listen enough before submitting */
240 played_time = mdate() - p_sys->p_current_song.i_start -
241 p_sys->time_total_pauses;
242 played_time /= 1000000; /* µs → s */
244 /*HACK: it seam that the preparsing sometime fail,
245 so use the playing time as the song length */
246 if (p_sys->p_current_song.i_l == 0)
247 p_sys->p_current_song.i_l = played_time;
249 /* Don't send song shorter than 30s */
250 if (p_sys->p_current_song.i_l < 30)
252 msg_Dbg(p_this, "Song too short (< 30s), not submitting");
256 /* Send if the user had listen more than 240s OR half the track length */
257 if ((played_time < 240) &&
258 (played_time < (p_sys->p_current_song.i_l / 2)))
260 msg_Dbg(p_this, "Song not listened long enough, not submitting");
264 /* Check that all meta are present */
265 if (!p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
266 !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t)
268 msg_Dbg(p_this, "Missing artist or title, not submitting");
272 if (p_sys->i_songs >= QUEUE_MAX)
274 msg_Warn(p_this, "Submission queue is full, not submitting");
278 msg_Dbg(p_this, "Song will be submitted.");
280 #define QUEUE_COPY(a) \
281 p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
283 #define QUEUE_COPY_NULL(a) \
285 p_sys->p_current_song.a = NULL
288 QUEUE_COPY_NULL(psz_n);
289 QUEUE_COPY_NULL(psz_a);
290 QUEUE_COPY_NULL(psz_t);
291 QUEUE_COPY_NULL(psz_b);
292 QUEUE_COPY_NULL(psz_m);
294 #undef QUEUE_COPY_NULL
299 /* signal the main loop we have something to submit */
300 vlc_cond_signal(&p_sys->wait);
303 DeleteSong(&p_sys->p_current_song);
304 p_sys->b_submit = false;
305 vlc_mutex_unlock(&p_sys->lock);
308 /*****************************************************************************
309 * PlayingChange: Playing status change callback
310 *****************************************************************************/
311 static int PlayingChange(vlc_object_t *p_this, const char *psz_var,
312 vlc_value_t oldval, vlc_value_t newval, void *p_data)
316 intf_thread_t *p_intf = (intf_thread_t*) p_data;
317 intf_sys_t *p_sys = p_intf->p_sys;
318 input_thread_t *p_input = (input_thread_t*)p_this;
323 if (newval.i_int != INPUT_EVENT_STATE) return VLC_SUCCESS;
325 if (var_CountChoices(p_input, "video-es"))
327 msg_Dbg(p_this, "Not an audio-only input, not submitting");
331 state = var_GetInteger(p_input, "state");
333 if (!p_sys->b_meta_read && state >= PLAYING_S)
335 ReadMetaData(p_intf);
342 else if (state == PAUSE_S)
343 p_sys->time_pause = mdate();
344 else if (p_sys->time_pause > 0 && state == PLAYING_S)
346 p_sys->time_total_pauses += (mdate() - p_sys->time_pause);
347 p_sys->time_pause = 0;
353 /*****************************************************************************
354 * ItemChange: Playlist item change callback
355 *****************************************************************************/
356 static int ItemChange(vlc_object_t *p_this, const char *psz_var,
357 vlc_value_t oldval, vlc_value_t newval, void *p_data)
359 input_thread_t *p_input;
360 intf_thread_t *p_intf = (intf_thread_t*) p_data;
361 intf_sys_t *p_sys = p_intf->p_sys;
362 input_item_t *p_item;
364 VLC_UNUSED(p_this); VLC_UNUSED(psz_var);
365 VLC_UNUSED(oldval); VLC_UNUSED(newval);
367 p_sys->b_state_cb = false;
368 p_sys->b_meta_read = false;
369 p_sys->b_submit = false;
371 p_input = playlist_CurrentInput(pl_Get(p_intf));
373 if (!p_input || p_input->b_dead)
376 p_item = input_GetItem(p_input);
379 vlc_object_release(p_input);
383 if (var_CountChoices(p_input, "video-es"))
385 msg_Dbg(p_this, "Not an audio-only input, not submitting");
386 vlc_object_release(p_input);
390 p_sys->time_total_pauses = 0;
391 time(&p_sys->p_current_song.date); /* to be sent to last.fm */
392 p_sys->p_current_song.i_start = mdate(); /* only used locally */
394 var_AddCallback(p_input, "intf-event", PlayingChange, p_intf);
395 p_sys->b_state_cb = true;
397 if (input_item_IsPreparsed(p_item))
398 ReadMetaData(p_intf);
399 /* if the input item was not preparsed, we'll do it in PlayingChange()
400 * callback, when "state" == PLAYING_S */
402 vlc_object_release(p_input);
406 /*****************************************************************************
407 * Open: initialize and create stuff
408 *****************************************************************************/
409 static int Open(vlc_object_t *p_this)
411 intf_thread_t *p_intf = (intf_thread_t*) p_this;
412 intf_sys_t *p_sys = calloc(1, sizeof(intf_sys_t));
417 p_intf->p_sys = p_sys;
419 vlc_mutex_init(&p_sys->lock);
420 vlc_cond_init(&p_sys->wait);
422 var_AddCallback(pl_Get(p_intf), "item-current", ItemChange, p_intf);
424 p_intf->pf_run = Run;
429 /*****************************************************************************
430 * Close: destroy interface stuff
431 *****************************************************************************/
432 static void Close(vlc_object_t *p_this)
434 playlist_t *p_playlist = pl_Get(p_this);
435 input_thread_t *p_input;
436 intf_thread_t *p_intf = (intf_thread_t*) p_this;
437 intf_sys_t *p_sys = p_intf->p_sys;
439 var_DelCallback(p_playlist, "item-current", ItemChange, p_intf);
441 p_input = playlist_CurrentInput(p_playlist);
444 if (p_sys->b_state_cb)
445 var_DelCallback(p_input, "intf-event", PlayingChange, p_intf);
446 vlc_object_release(p_input);
450 for (i = 0; i < p_sys->i_songs; i++)
451 DeleteSong(&p_sys->p_queue[i]);
452 vlc_UrlClean(&p_sys->p_submit_url);
454 free(p_sys->psz_nowp_host);
455 free(p_sys->psz_nowp_file);
457 vlc_cond_destroy(&p_sys->wait);
458 vlc_mutex_destroy(&p_sys->lock);
462 /*****************************************************************************
463 * Handshake : Init audioscrobbler connection
464 *****************************************************************************/
465 static int Handshake(intf_thread_t *p_this)
467 char *psz_username, *psz_password;
468 char *psz_scrobbler_url;
470 char psz_timestamp[21];
472 struct md5_s p_struct_md5;
475 char *psz_handshake_url;
476 uint8_t p_buffer[1024];
482 intf_thread_t *p_intf = (intf_thread_t*) p_this;
483 intf_sys_t *p_sys = p_this->p_sys;
485 psz_username = var_InheritString(p_this, "lastfm-username");
489 psz_password = var_InheritString(p_this, "lastfm-password");
496 /* username or password have not been setup */
497 if (!*psz_username || !*psz_password)
506 /* generates a md5 hash of the password */
507 InitMD5(&p_struct_md5);
508 AddMD5(&p_struct_md5, (uint8_t*) psz_password, strlen(psz_password));
509 EndMD5(&p_struct_md5);
513 char *psz_password_md5 = psz_md5_hash(&p_struct_md5);
514 if (!psz_password_md5)
520 snprintf(psz_timestamp, sizeof(psz_timestamp), "%"PRIu64,
521 (uint64_t)timestamp);
523 /* generates a md5 hash of :
524 * - md5 hash of the password, plus
525 * - timestamp in clear text
527 InitMD5(&p_struct_md5);
528 AddMD5(&p_struct_md5, (uint8_t*) psz_password_md5, 32);
529 AddMD5(&p_struct_md5, (uint8_t*) psz_timestamp, strlen(psz_timestamp));
530 EndMD5(&p_struct_md5);
531 free(psz_password_md5);
533 char *psz_auth_token = psz_md5_hash(&p_struct_md5);
540 psz_scrobbler_url = var_InheritString(p_this, "scrobbler-url");
541 if (!psz_scrobbler_url)
547 i_ret = asprintf(&psz_handshake_url,
548 "http://%s/?hs=true&p=1.2&c="CLIENT_NAME"&v="CLIENT_VERSION"&u=%s&t=%s&a=%s"
549 , psz_scrobbler_url, psz_username, psz_timestamp, psz_auth_token);
551 free(psz_scrobbler_url);
556 /* send the http handshake request */
557 p_stream = stream_UrlNew(p_intf, psz_handshake_url);
558 free(psz_handshake_url);
564 i_ret = stream_Read(p_stream, p_buffer, sizeof(p_buffer) - 1);
567 stream_Delete(p_stream);
570 p_buffer[i_ret] = '\0';
571 stream_Delete(p_stream);
573 p_buffer_pos = strstr((char*) p_buffer, "FAILED ");
576 /* handshake request failed, sorry */
577 msg_Err(p_this, "last.fm handshake failed: %s", p_buffer_pos + 7);
581 if (strstr((char*) p_buffer, "BADAUTH"))
583 /* authentication failed, bad username/password combination */
585 _("last.fm: Authentication failed"),
586 "%s", _("last.fm username or password is incorrect. "
587 "Please verify your settings and relaunch VLC."));
588 return VLC_AUDIOSCROBBLER_EFATAL;
591 if (strstr((char*) p_buffer, "BANNED"))
593 /* oops, our version of vlc has been banned by last.fm servers */
594 msg_Err(p_intf, "This version of VLC has been banned by last.fm. "
595 "You should upgrade VLC, or disable the last.fm plugin.");
596 return VLC_AUDIOSCROBBLER_EFATAL;
599 if (strstr((char*) p_buffer, "BADTIME"))
601 /* The system clock isn't good */
602 msg_Err(p_intf, "last.fm handshake failed because your clock is too "
603 "much shifted. Please correct it, and relaunch VLC.");
604 return VLC_AUDIOSCROBBLER_EFATAL;
607 p_buffer_pos = strstr((char*) p_buffer, "OK");
611 p_buffer_pos = strstr(p_buffer_pos, "\n");
612 if (!p_buffer_pos || strlen(p_buffer_pos) < 33)
614 p_buffer_pos++; /* we skip the '\n' */
616 /* save the session ID */
617 memcpy(p_sys->psz_auth_token, p_buffer_pos, 32);
618 p_sys->psz_auth_token[32] = '\0';
620 p_buffer_pos = strstr(p_buffer_pos, "http://");
621 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
624 /* We need to read the nowplaying url */
625 p_buffer_pos += 7; /* we skip "http://" */
627 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
631 switch(ParseURL(psz_url, &p_sys->psz_nowp_host,
632 &p_sys->psz_nowp_file, &p_sys->i_nowp_port))
643 p_buffer_pos = strstr(p_buffer_pos, "http://");
644 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
647 /* We need to read the submission url */
648 p_buffer_pos += 7; /* we skip "http://" */
649 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
653 /* parse the submission url */
654 vlc_UrlParse(&p_sys->p_submit_url, psz_url, 0);
663 msg_Err(p_intf, "Handshake: can't recognize server protocol");
667 static void HandleInterval(mtime_t *next, unsigned int *i_interval)
669 if (*i_interval == 0)
671 /* first interval is 1 minute */
676 /* else we double the previous interval, up to 120 minutes */
678 if (*i_interval > 120)
681 *next = mdate() + (*i_interval * 1000000 * 60);
684 /*****************************************************************************
685 * Run : call Handshake() then submit songs
686 *****************************************************************************/
687 static void Run(intf_thread_t *p_intf)
689 uint8_t p_buffer[1024];
690 int canc = vlc_savecancel();
691 bool b_handshaked = false;
693 /* data about audioscrobbler session */
694 mtime_t next_exchange = -1; /**< when can we send data */
695 unsigned int i_interval; /**< waiting interval (secs)*/
697 intf_sys_t *p_sys = p_intf->p_sys;
702 vlc_restorecancel(canc);
703 vlc_mutex_lock(&p_sys->lock);
704 mutex_cleanup_push(&p_sys->lock);
707 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
708 while (mdate() < next_exchange);
711 canc = vlc_savecancel();
713 /* handshake if needed */
716 msg_Dbg(p_intf, "Handshaking with last.fm ...");
718 switch(Handshake(p_intf))
724 /* username not set */
726 _("Last.fm username not set"),
727 "%s", _("Please set a username or disable the "
728 "audioscrobbler plugin, and restart VLC.\n"
729 "Visit http://www.last.fm/join/ to get an account.")
734 msg_Dbg(p_intf, "Handshake successful :)");
737 next_exchange = mdate();
740 case VLC_AUDIOSCROBBLER_EFATAL:
741 msg_Warn(p_intf, "Exiting...");
746 /* protocol error : we'll try later */
747 HandleInterval(&next_exchange, &i_interval);
750 /* if handshake failed let's restart the loop */
755 msg_Dbg(p_intf, "Going to submit some data...");
757 if (asprintf(&psz_submit, "s=%s", p_sys->psz_auth_token) == -1)
760 /* forge the HTTP POST request */
761 vlc_mutex_lock(&p_sys->lock);
762 audioscrobbler_song_t *p_song;
763 for (int i_song = 0 ; i_song < p_sys->i_songs ; i_song++)
765 char *psz_submit_song, *psz_submit_tmp;
766 p_song = &p_sys->p_queue[i_song];
767 if (asprintf(&psz_submit_song,
777 i_song, p_song->psz_a,
778 i_song, p_song->psz_t,
779 i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
783 i_song, p_song->psz_b,
784 i_song, p_song->psz_n,
785 i_song, p_song->psz_m
787 { /* Out of memory */
788 vlc_mutex_unlock(&p_sys->lock);
791 psz_submit_tmp = psz_submit;
792 if (asprintf(&psz_submit, "%s%s",
793 psz_submit_tmp, psz_submit_song) == -1)
794 { /* Out of memory */
795 free(psz_submit_tmp);
796 free(psz_submit_song);
797 vlc_mutex_unlock(&p_sys->lock);
800 free(psz_submit_song);
801 free(psz_submit_tmp);
803 vlc_mutex_unlock(&p_sys->lock);
805 int i_post_socket = net_ConnectTCP(p_intf, p_sys->p_submit_url.psz_host,
806 p_sys->p_submit_url.i_port);
808 if (i_post_socket == -1)
810 /* If connection fails, we assume we must handshake again */
811 HandleInterval(&next_exchange, &i_interval);
812 b_handshaked = false;
817 /* we transmit the data */
818 int i_net_ret = net_Printf(p_intf, i_post_socket, NULL,
820 "Accept-Encoding: identity\n"
821 "Content-length: %zu\n"
822 "Connection: close\n"
823 "Content-type: application/x-www-form-urlencoded\n"
825 "User-agent: VLC media player/"VERSION"\r\n"
829 p_sys->p_submit_url.psz_path, strlen(psz_submit),
830 p_sys->p_submit_url.psz_host, psz_submit
836 /* If connection fails, we assume we must handshake again */
837 HandleInterval(&next_exchange, &i_interval);
838 b_handshaked = false;
842 i_net_ret = net_Read(p_intf, i_post_socket, NULL,
843 p_buffer, sizeof(p_buffer) - 1, false);
846 /* if we get no answer, something went wrong : try again */
850 net_Close(i_post_socket);
851 p_buffer[i_net_ret] = '\0';
853 char *failed = strstr((char *) p_buffer, "FAILED");
856 msg_Warn(p_intf, "%s", failed);
857 HandleInterval(&next_exchange, &i_interval);
861 if (strstr((char *) p_buffer, "BADSESSION"))
863 msg_Err(p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?");
864 b_handshaked = false;
865 HandleInterval(&next_exchange, &i_interval);
869 if (strstr((char *) p_buffer, "OK"))
871 for (int i = 0; i < p_sys->i_songs; i++)
872 DeleteSong(&p_sys->p_queue[i]);
875 next_exchange = mdate();
876 msg_Dbg(p_intf, "Submission successful!");
880 msg_Err(p_intf, "Authentication failed, handshaking again (%s)",
882 b_handshaked = false;
883 HandleInterval(&next_exchange, &i_interval);
886 vlc_restorecancel(canc);