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_input.h>
45 #include <vlc_dialog.h>
48 #include <vlc_stream.h>
50 #include <vlc_network.h>
51 #include <vlc_playlist.h>
53 /*****************************************************************************
55 *****************************************************************************/
59 /* Keeps track of metadata to be submitted */
60 typedef struct audioscrobbler_song_t
62 char *psz_a; /**< track artist */
63 char *psz_t; /**< track title */
64 char *psz_b; /**< track album */
65 char *psz_n; /**< track number */
66 int i_l; /**< track length */
67 char *psz_m; /**< musicbrainz id */
68 time_t date; /**< date since epoch */
69 mtime_t i_start; /**< playing start */
70 } audioscrobbler_song_t;
74 audioscrobbler_song_t p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
75 int i_songs; /**< number of songs */
77 vlc_mutex_t lock; /**< p_sys mutex */
78 vlc_cond_t wait; /**< song to submit event */
79 vlc_thread_t thread; /**< thread to submit song */
81 /* submission of played songs */
82 vlc_url_t p_submit_url; /**< where to submit data */
84 /* submission of playing song */
86 char *psz_nowp_host; /**< where to submit data */
87 int i_nowp_port; /**< port to which submit */
88 char *psz_nowp_file; /**< file to which submit */
90 char psz_auth_token[33]; /**< Authentication token */
92 /* data about song currently playing */
93 audioscrobbler_song_t p_current_song; /**< song being played */
95 mtime_t time_pause; /**< time when vlc paused */
96 mtime_t time_total_pauses; /**< total time in pause */
98 bool b_submit; /**< do we have to submit ? */
100 bool b_state_cb; /**< if we registered the
101 * "state" callback */
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)
161 intf_sys_t *p_sys = p_this->p_sys;
163 input_thread_t *p_input = pl_CurrentInput(p_this);
167 input_item_t *p_item = input_GetItem(p_input);
170 vlc_object_release(p_input);
174 #define ALLOC_ITEM_META(a, b) do { \
175 char *psz_meta = input_item_Get##b(p_item); \
176 if (psz_meta && *psz_meta) \
177 a = encode_URI_component(psz_meta); \
181 vlc_mutex_lock(&p_sys->lock);
183 p_sys->b_meta_read = true;
185 ALLOC_ITEM_META(p_sys->p_current_song.psz_a, Artist);
186 if (!p_sys->p_current_song.psz_a)
188 msg_Dbg(p_this, "No artist..");
189 DeleteSong(&p_sys->p_current_song);
193 ALLOC_ITEM_META(p_sys->p_current_song.psz_t, Title);
194 if (!p_sys->p_current_song.psz_t)
196 msg_Dbg(p_this, "No track name..");
197 DeleteSong(&p_sys->p_current_song);
201 /* Now we have read the mandatory meta data, so we can submit that info */
202 p_sys->b_submit = true;
204 ALLOC_ITEM_META(p_sys->p_current_song.psz_b, Album);
205 if (!p_sys->p_current_song.psz_b)
206 p_sys->p_current_song.psz_b = calloc(1, 1);
208 ALLOC_ITEM_META(p_sys->p_current_song.psz_m, TrackID);
209 if (!p_sys->p_current_song.psz_m)
210 p_sys->p_current_song.psz_m = calloc(1, 1);
212 p_sys->p_current_song.i_l = input_item_GetDuration(p_item) / 1000000;
214 ALLOC_ITEM_META(p_sys->p_current_song.psz_n, TrackNum);
215 if (!p_sys->p_current_song.psz_n)
216 p_sys->p_current_song.psz_n = calloc(1, 1);
217 #undef ALLOC_ITEM_META
219 msg_Dbg(p_this, "Meta data registered");
222 vlc_mutex_unlock(&p_sys->lock);
223 vlc_object_release(p_input);
226 /*****************************************************************************
227 * AddToQueue: Add the played song to the queue to be submitted
228 *****************************************************************************/
229 static void AddToQueue (intf_thread_t *p_this)
232 intf_sys_t *p_sys = p_this->p_sys;
234 vlc_mutex_lock(&p_sys->lock);
235 if (!p_sys->b_submit)
238 /* wait for the user to listen enough before submitting */
239 played_time = mdate() - p_sys->p_current_song.i_start -
240 p_sys->time_total_pauses;
241 played_time /= 1000000; /* µs → s */
243 /*HACK: it seam that the preparsing sometime fail,
244 so use the playing time as the song length */
245 if (p_sys->p_current_song.i_l == 0)
246 p_sys->p_current_song.i_l = played_time;
248 /* Don't send song shorter than 30s */
249 if (p_sys->p_current_song.i_l < 30)
251 msg_Dbg(p_this, "Song too short (< 30s), not submitting");
255 /* Send if the user had listen more than 240s OR half the track length */
256 if ((played_time < 240) &&
257 (played_time < (p_sys->p_current_song.i_l / 2)))
259 msg_Dbg(p_this, "Song not listened long enough, not submitting");
263 /* Check that all meta are present */
264 if (!p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
265 !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t)
267 msg_Dbg(p_this, "Missing artist or title, not submitting");
271 if (p_sys->i_songs >= QUEUE_MAX)
273 msg_Warn(p_this, "Submission queue is full, not submitting");
277 msg_Dbg(p_this, "Song will be submitted.");
279 #define QUEUE_COPY(a) \
280 p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
282 #define QUEUE_COPY_NULL(a) \
284 p_sys->p_current_song.a = NULL
287 QUEUE_COPY_NULL(psz_n);
288 QUEUE_COPY_NULL(psz_a);
289 QUEUE_COPY_NULL(psz_t);
290 QUEUE_COPY_NULL(psz_b);
291 QUEUE_COPY_NULL(psz_m);
293 #undef QUEUE_COPY_NULL
298 /* signal the main loop we have something to submit */
299 vlc_cond_signal(&p_sys->wait);
302 DeleteSong(&p_sys->p_current_song);
303 p_sys->b_submit = false;
304 vlc_mutex_unlock(&p_sys->lock);
307 /*****************************************************************************
308 * PlayingChange: Playing status change callback
309 *****************************************************************************/
310 static int PlayingChange(vlc_object_t *p_this, const char *psz_var,
311 vlc_value_t oldval, vlc_value_t newval, void *p_data)
315 intf_thread_t *p_intf = (intf_thread_t*) p_data;
316 intf_sys_t *p_sys = p_intf->p_sys;
317 input_thread_t *p_input = (input_thread_t*)p_this;
322 if (newval.i_int != INPUT_EVENT_STATE) return VLC_SUCCESS;
324 if (var_CountChoices(p_input, "video-es"))
326 msg_Dbg(p_this, "Not an audio-only input, not submitting");
330 state = var_GetInteger(p_input, "state");
332 if (!p_sys->b_meta_read && state >= PLAYING_S)
334 ReadMetaData(p_intf);
341 else if (state == PAUSE_S)
342 p_sys->time_pause = mdate();
343 else if (p_sys->time_pause > 0 && state == PLAYING_S)
345 p_sys->time_total_pauses += (mdate() - p_sys->time_pause);
346 p_sys->time_pause = 0;
352 /*****************************************************************************
353 * ItemChange: Playlist item change callback
354 *****************************************************************************/
355 static int ItemChange(vlc_object_t *p_this, const char *psz_var,
356 vlc_value_t oldval, vlc_value_t newval, void *p_data)
358 intf_thread_t *p_intf = (intf_thread_t*) p_data;
359 intf_sys_t *p_sys = p_intf->p_sys;
361 VLC_UNUSED(p_this); VLC_UNUSED(psz_var);
362 VLC_UNUSED(oldval); VLC_UNUSED(newval);
364 p_sys->b_state_cb = false;
365 p_sys->b_meta_read = false;
366 p_sys->b_submit = false;
368 input_thread_t *p_input = pl_CurrentInput(p_intf);
369 if (!p_input || p_input->b_dead)
372 input_item_t *p_item = input_GetItem(p_input);
375 vlc_object_release(p_input);
379 if (var_CountChoices(p_input, "video-es"))
381 msg_Dbg(p_this, "Not an audio-only input, not submitting");
382 vlc_object_release(p_input);
386 p_sys->time_total_pauses = 0;
387 time(&p_sys->p_current_song.date); /* to be sent to last.fm */
388 p_sys->p_current_song.i_start = mdate(); /* only used locally */
390 var_AddCallback(p_input, "intf-event", PlayingChange, p_intf);
391 p_sys->b_state_cb = true;
393 if (input_item_IsPreparsed(p_item))
394 ReadMetaData(p_intf);
395 /* if the input item was not preparsed, we'll do it in PlayingChange()
396 * callback, when "state" == PLAYING_S */
398 vlc_object_release(p_input);
402 /*****************************************************************************
403 * Open: initialize and create stuff
404 *****************************************************************************/
405 static int Open(vlc_object_t *p_this)
407 intf_thread_t *p_intf = (intf_thread_t*) p_this;
408 intf_sys_t *p_sys = calloc(1, sizeof(intf_sys_t));
413 p_intf->p_sys = p_sys;
415 vlc_mutex_init(&p_sys->lock);
416 vlc_cond_init(&p_sys->wait);
418 if (vlc_clone(&p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW))
420 vlc_cond_destroy(&p_sys->wait);
421 vlc_mutex_destroy(&p_sys->lock);
426 var_AddCallback(pl_Get(p_intf), "activity", ItemChange, p_intf);
431 /*****************************************************************************
432 * Close: destroy interface stuff
433 *****************************************************************************/
434 static void Close(vlc_object_t *p_this)
436 intf_thread_t *p_intf = (intf_thread_t*) p_this;
437 intf_sys_t *p_sys = p_intf->p_sys;
439 var_DelCallback(pl_Get(p_intf), "activity", ItemChange, p_intf);
441 vlc_cancel(p_sys->thread);
442 vlc_join(p_sys->thread, NULL);
444 input_thread_t *p_input = pl_CurrentInput(p_intf);
447 if (p_sys->b_state_cb)
448 var_DelCallback(p_input, "intf-event", PlayingChange, p_intf);
449 vlc_object_release(p_input);
453 for (i = 0; i < p_sys->i_songs; i++)
454 DeleteSong(&p_sys->p_queue[i]);
455 vlc_UrlClean(&p_sys->p_submit_url);
457 free(p_sys->psz_nowp_host);
458 free(p_sys->psz_nowp_file);
460 vlc_cond_destroy(&p_sys->wait);
461 vlc_mutex_destroy(&p_sys->lock);
465 /*****************************************************************************
466 * Handshake : Init audioscrobbler connection
467 *****************************************************************************/
468 static int Handshake(intf_thread_t *p_this)
470 char *psz_username, *psz_password;
471 char *psz_scrobbler_url;
473 char psz_timestamp[21];
475 struct md5_s p_struct_md5;
478 char *psz_handshake_url;
479 uint8_t p_buffer[1024];
485 intf_thread_t *p_intf = (intf_thread_t*) p_this;
486 intf_sys_t *p_sys = p_this->p_sys;
488 psz_username = var_InheritString(p_this, "lastfm-username");
489 psz_password = var_InheritString(p_this, "lastfm-password");
491 /* username or password have not been setup */
492 if (EMPTY_STR(psz_username) || EMPTY_STR(psz_password))
501 /* generates a md5 hash of the password */
502 InitMD5(&p_struct_md5);
503 AddMD5(&p_struct_md5, (uint8_t*) psz_password, strlen(psz_password));
504 EndMD5(&p_struct_md5);
508 char *psz_password_md5 = psz_md5_hash(&p_struct_md5);
509 if (!psz_password_md5)
515 snprintf(psz_timestamp, sizeof(psz_timestamp), "%"PRIu64,
516 (uint64_t)timestamp);
518 /* generates a md5 hash of :
519 * - md5 hash of the password, plus
520 * - timestamp in clear text
522 InitMD5(&p_struct_md5);
523 AddMD5(&p_struct_md5, (uint8_t*) psz_password_md5, 32);
524 AddMD5(&p_struct_md5, (uint8_t*) psz_timestamp, strlen(psz_timestamp));
525 EndMD5(&p_struct_md5);
526 free(psz_password_md5);
528 char *psz_auth_token = psz_md5_hash(&p_struct_md5);
535 psz_scrobbler_url = var_InheritString(p_this, "scrobbler-url");
536 if (!psz_scrobbler_url)
538 free(psz_auth_token);
543 i_ret = asprintf(&psz_handshake_url,
544 "http://%s/?hs=true&p=1.2&c="CLIENT_NAME"&v="CLIENT_VERSION"&u=%s&t=%s&a=%s"
545 , psz_scrobbler_url, psz_username, psz_timestamp, psz_auth_token);
547 free(psz_auth_token);
548 free(psz_scrobbler_url);
553 /* send the http handshake request */
554 p_stream = stream_UrlNew(p_intf, psz_handshake_url);
555 free(psz_handshake_url);
561 i_ret = stream_Read(p_stream, p_buffer, sizeof(p_buffer) - 1);
564 stream_Delete(p_stream);
567 p_buffer[i_ret] = '\0';
568 stream_Delete(p_stream);
570 p_buffer_pos = strstr((char*) p_buffer, "FAILED ");
573 /* handshake request failed, sorry */
574 msg_Err(p_this, "last.fm handshake failed: %s", p_buffer_pos + 7);
578 if (strstr((char*) p_buffer, "BADAUTH"))
580 /* authentication failed, bad username/password combination */
582 _("last.fm: Authentication failed"),
583 "%s", _("last.fm username or password is incorrect. "
584 "Please verify your settings and relaunch VLC."));
585 return VLC_AUDIOSCROBBLER_EFATAL;
588 if (strstr((char*) p_buffer, "BANNED"))
590 /* oops, our version of vlc has been banned by last.fm servers */
591 msg_Err(p_intf, "This version of VLC has been banned by last.fm. "
592 "You should upgrade VLC, or disable the last.fm plugin.");
593 return VLC_AUDIOSCROBBLER_EFATAL;
596 if (strstr((char*) p_buffer, "BADTIME"))
598 /* The system clock isn't good */
599 msg_Err(p_intf, "last.fm handshake failed because your clock is too "
600 "much shifted. Please correct it, and relaunch VLC.");
601 return VLC_AUDIOSCROBBLER_EFATAL;
604 p_buffer_pos = strstr((char*) p_buffer, "OK");
608 p_buffer_pos = strstr(p_buffer_pos, "\n");
609 if (!p_buffer_pos || strlen(p_buffer_pos) < 33)
611 p_buffer_pos++; /* we skip the '\n' */
613 /* save the session ID */
614 memcpy(p_sys->psz_auth_token, p_buffer_pos, 32);
615 p_sys->psz_auth_token[32] = '\0';
617 p_buffer_pos = strstr(p_buffer_pos, "http://");
618 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
621 /* We need to read the nowplaying url */
622 p_buffer_pos += 7; /* we skip "http://" */
624 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
628 switch(ParseURL(psz_url, &p_sys->psz_nowp_host,
629 &p_sys->psz_nowp_file, &p_sys->i_nowp_port))
640 p_buffer_pos = strstr(p_buffer_pos, "http://");
641 if (!p_buffer_pos || strlen(p_buffer_pos) == 7)
644 /* We need to read the submission url */
645 p_buffer_pos += 7; /* we skip "http://" */
646 psz_url = strndup(p_buffer_pos, strcspn(p_buffer_pos, "\n"));
650 /* parse the submission url */
651 vlc_UrlParse(&p_sys->p_submit_url, psz_url, 0);
660 msg_Err(p_intf, "Handshake: can't recognize server protocol");
664 static void HandleInterval(mtime_t *next, unsigned int *i_interval)
666 if (*i_interval == 0)
668 /* first interval is 1 minute */
673 /* else we double the previous interval, up to 120 minutes */
675 if (*i_interval > 120)
678 *next = mdate() + (*i_interval * 1000000 * 60);
681 /*****************************************************************************
682 * Run : call Handshake() then submit songs
683 *****************************************************************************/
684 static void *Run(void *data)
686 intf_thread_t *p_intf = data;
687 uint8_t p_buffer[1024];
688 int canc = vlc_savecancel();
689 bool b_handshaked = false;
691 /* data about audioscrobbler session */
692 mtime_t next_exchange = -1; /**< when can we send data */
693 unsigned int i_interval = 0; /**< waiting interval (secs)*/
695 intf_sys_t *p_sys = p_intf->p_sys;
700 vlc_restorecancel(canc);
701 vlc_mutex_lock(&p_sys->lock);
702 mutex_cleanup_push(&p_sys->lock);
705 vlc_cond_wait(&p_sys->wait, &p_sys->lock);
706 while (mdate() < next_exchange);
709 canc = vlc_savecancel();
711 /* handshake if needed */
714 msg_Dbg(p_intf, "Handshaking with last.fm ...");
716 switch(Handshake(p_intf))
722 /* username not set */
724 _("Last.fm username not set"),
725 "%s", _("Please set a username or disable the "
726 "audioscrobbler plugin, and restart VLC.\n"
727 "Visit http://www.last.fm/join/ to get an account."));
731 msg_Dbg(p_intf, "Handshake successful :)");
734 next_exchange = mdate();
737 case VLC_AUDIOSCROBBLER_EFATAL:
738 msg_Warn(p_intf, "Exiting...");
743 /* protocol error : we'll try later */
744 HandleInterval(&next_exchange, &i_interval);
747 /* if handshake failed let's restart the loop */
752 msg_Dbg(p_intf, "Going to submit some data...");
754 if (asprintf(&psz_submit, "s=%s", p_sys->psz_auth_token) == -1)
757 /* forge the HTTP POST request */
758 vlc_mutex_lock(&p_sys->lock);
759 audioscrobbler_song_t *p_song;
760 for (int i_song = 0 ; i_song < p_sys->i_songs ; i_song++)
762 char *psz_submit_song, *psz_submit_tmp;
763 p_song = &p_sys->p_queue[i_song];
764 if (asprintf(&psz_submit_song,
774 i_song, p_song->psz_a,
775 i_song, p_song->psz_t,
776 i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
780 i_song, p_song->psz_b,
781 i_song, p_song->psz_n,
782 i_song, p_song->psz_m
784 { /* Out of memory */
785 vlc_mutex_unlock(&p_sys->lock);
788 psz_submit_tmp = psz_submit;
789 if (asprintf(&psz_submit, "%s%s",
790 psz_submit_tmp, psz_submit_song) == -1)
791 { /* Out of memory */
792 free(psz_submit_tmp);
793 free(psz_submit_song);
794 vlc_mutex_unlock(&p_sys->lock);
797 free(psz_submit_song);
798 free(psz_submit_tmp);
800 vlc_mutex_unlock(&p_sys->lock);
802 int i_post_socket = net_ConnectTCP(p_intf, p_sys->p_submit_url.psz_host,
803 p_sys->p_submit_url.i_port);
805 if (i_post_socket == -1)
807 /* If connection fails, we assume we must handshake again */
808 HandleInterval(&next_exchange, &i_interval);
809 b_handshaked = false;
814 /* we transmit the data */
815 int i_net_ret = net_Printf(p_intf, i_post_socket, NULL,
817 "Accept-Encoding: identity\n"
818 "Content-length: %zu\n"
819 "Connection: close\n"
820 "Content-type: application/x-www-form-urlencoded\n"
822 "User-agent: VLC media player/"VERSION"\r\n"
826 p_sys->p_submit_url.psz_path, strlen(psz_submit),
827 p_sys->p_submit_url.psz_host, psz_submit
833 /* If connection fails, we assume we must handshake again */
834 HandleInterval(&next_exchange, &i_interval);
835 b_handshaked = false;
839 i_net_ret = net_Read(p_intf, i_post_socket, NULL,
840 p_buffer, sizeof(p_buffer) - 1, false);
843 /* if we get no answer, something went wrong : try again */
847 net_Close(i_post_socket);
848 p_buffer[i_net_ret] = '\0';
850 char *failed = strstr((char *) p_buffer, "FAILED");
853 msg_Warn(p_intf, "%s", failed);
854 HandleInterval(&next_exchange, &i_interval);
858 if (strstr((char *) p_buffer, "BADSESSION"))
860 msg_Err(p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?");
861 b_handshaked = false;
862 HandleInterval(&next_exchange, &i_interval);
866 if (strstr((char *) p_buffer, "OK"))
868 for (int i = 0; i < p_sys->i_songs; i++)
869 DeleteSong(&p_sys->p_queue[i]);
872 next_exchange = mdate();
873 msg_Dbg(p_intf, "Submission successful!");
877 msg_Err(p_intf, "Authentication failed, handshaking again (%s)",
879 b_handshaked = false;
880 HandleInterval(&next_exchange, &i_interval);
884 vlc_restorecancel(canc);