]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
freetype: don't create/show fontcache dialog if config is upto date
[vlc] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright © 2006-2009 the VideoLAN team
5  * $Id$
6  *
7  * Author: Rafaël Carré <funman at videolanorg>
8  *         Ilkka Ollakka <ileoo at videolan org>
9  *
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.
14  *
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.
19  *
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  *****************************************************************************/
24
25 /* audioscrobbler protocol version: 1.2
26  * http://www.audioscrobbler.net/development/protocol/
27  *
28  * TODO:    "Now Playing" feature (not mandatory)
29  *          Update to new API? http://www.lastfm.fr/api
30  */
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #if defined( WIN32 ) 
36 #include <time.h> 
37 #endif 
38
39 #ifdef HAVE_CONFIG_H
40 # include "config.h"
41 #endif
42
43 #include <vlc_common.h>
44 #include <vlc_plugin.h>
45 #include <vlc_interface.h>
46 #include <vlc_dialog.h>
47 #include <vlc_meta.h>
48 #include <vlc_md5.h>
49 #include <vlc_stream.h>
50 #include <vlc_url.h>
51 #include <vlc_network.h>
52 #include <vlc_playlist.h>
53
54 /*****************************************************************************
55  * Local prototypes
56  *****************************************************************************/
57
58 #define QUEUE_MAX 50
59
60 /* Keeps track of metadata to be submitted */
61 typedef struct audioscrobbler_song_t
62 {
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;
72
73 struct intf_sys_t
74 {
75     audioscrobbler_song_t   p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
76     int                     i_songs;            /**< number of songs        */
77
78     vlc_mutex_t             lock;               /**< p_sys mutex            */
79     vlc_cond_t              wait;               /**< song to submit event   */
80
81     /* data about audioscrobbler session */
82     mtime_t                 next_exchange;      /**< when can we send data  */
83     unsigned int            i_interval;         /**< waiting interval (secs)*/
84
85     /* submission of played songs */
86     char                    *psz_submit_host;   /**< where to submit data   */
87     int                     i_submit_port;      /**< port to which submit   */
88     char                    *psz_submit_file;   /**< file to which submit   */
89
90     /* submission of playing song */
91 #if 0 //NOT USED
92     char                    *psz_nowp_host;     /**< where to submit data   */
93     int                     i_nowp_port;        /**< port to which submit   */
94     char                    *psz_nowp_file;     /**< file to which submit   */
95 #endif
96     bool                    b_handshaked;       /**< are we authenticated ? */
97     char                    psz_auth_token[33]; /**< Authentication token */
98
99     /* data about song currently playing */
100     audioscrobbler_song_t   p_current_song;     /**< song being played      */
101
102     mtime_t                 time_pause;         /**< time when vlc paused   */
103     mtime_t                 time_total_pauses;  /**< total time in pause    */
104
105     bool                    b_submit;           /**< do we have to submit ? */
106
107     bool                    b_state_cb;         /**< if we registered the
108                                                  * "state" callback         */
109
110     bool                    b_meta_read;        /**< if we read the song's
111                                                  * metadata already         */
112 };
113
114 static int  Open            ( vlc_object_t * );
115 static void Close           ( vlc_object_t * );
116 static void Run             ( intf_thread_t * );
117
118 static int ItemChange       ( vlc_object_t *, const char *, vlc_value_t,
119                                 vlc_value_t, void * );
120 static int PlayingChange    ( vlc_object_t *, const char *, vlc_value_t,
121                                 vlc_value_t, void * );
122
123 static void AddToQueue      ( intf_thread_t * );
124 static int Handshake        ( intf_thread_t * );
125 static int ReadMetaData     ( intf_thread_t * );
126 static void DeleteSong      ( audioscrobbler_song_t* );
127 static int ParseURL         ( char *, char **, char **, int * );
128 static void HandleInterval  ( mtime_t *, unsigned int * );
129
130 /*****************************************************************************
131  * Module descriptor
132  ****************************************************************************/
133
134 #define USERNAME_TEXT       N_("Username")
135 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
136 #define PASSWORD_TEXT       N_("Password")
137 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
138 #define URL_TEXT            N_("Scrobbler URL")
139 #define URL_LONGTEXT        N_("The URL set for an alternative scrobbler engine")
140
141 /* This error value is used when last.fm plugin has to be unloaded. */
142 #define VLC_AUDIOSCROBBLER_EFATAL -69
143
144 /* last.fm client identifier */
145 #define CLIENT_NAME     PACKAGE
146 #define CLIENT_VERSION  VERSION
147
148 /* HTTP POST request : to submit data */
149 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
150                         "Accept-Encoding: identity\n"                       \
151                         "Content-length: %u\n"                              \
152                         "Connection: close\n"                               \
153                         "Content-type: application/x-www-form-urlencoded\n" \
154                         "Host: %s\n"                                        \
155                         "User-agent: VLC media player/%s\r\n"               \
156                         "\r\n"                                              \
157                         "%s\r\n"                                            \
158                         "\r\n"
159
160 vlc_module_begin ()
161     set_category( CAT_INTERFACE )
162     set_subcategory( SUBCAT_INTERFACE_CONTROL )
163     set_shortname( N_( "Audioscrobbler" ) )
164     set_description( N_("Submission of played songs to last.fm") )
165     add_string( "lastfm-username", "", NULL,
166                 USERNAME_TEXT, USERNAME_LONGTEXT, false )
167     add_password( "lastfm-password", "", NULL,
168                 PASSWORD_TEXT, PASSWORD_LONGTEXT, false )
169     add_string( "scrobbler-url", "post.audioscrobbler.com", NULL,
170                 URL_TEXT, URL_LONGTEXT, false )
171     set_capability( "interface", 0 )
172     set_callbacks( Open, Close )
173 vlc_module_end ()
174
175 /*****************************************************************************
176  * Open: initialize and create stuff
177  *****************************************************************************/
178 static int Open( vlc_object_t *p_this )
179 {
180     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
181     intf_sys_t      *p_sys      = calloc( 1, sizeof( intf_sys_t ) );
182
183     if( !p_sys )
184         return VLC_ENOMEM;
185
186     p_intf->p_sys = p_sys;
187
188     vlc_mutex_init( &p_sys->lock );
189     vlc_cond_init( &p_sys->wait );
190
191     var_AddCallback( pl_Get( p_intf ), "item-current", ItemChange, p_intf );
192
193     p_intf->pf_run = Run;
194
195     return VLC_SUCCESS;
196 }
197
198 /*****************************************************************************
199  * Close: destroy interface stuff
200  *****************************************************************************/
201 static void Close( vlc_object_t *p_this )
202 {
203     playlist_t                  *p_playlist = pl_Get( p_this );
204     input_thread_t              *p_input;
205     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
206     intf_sys_t                  *p_sys  = p_intf->p_sys;
207
208     var_DelCallback( p_playlist, "item-current", ItemChange, p_intf );
209
210     p_input = playlist_CurrentInput( p_playlist );
211     if ( p_input )
212     {
213         if( p_sys->b_state_cb )
214             var_DelCallback( p_input, "intf-event", PlayingChange, p_intf );
215         vlc_object_release( p_input );
216     }
217
218     int i;
219     for( i = 0; i < p_sys->i_songs; i++ )
220         DeleteSong( &p_sys->p_queue[i] );
221     free( p_sys->psz_submit_host );
222     free( p_sys->psz_submit_file );
223 #if 0 //NOT USED
224     free( p_sys->psz_nowp_host );
225     free( p_sys->psz_nowp_file );
226 #endif
227     vlc_cond_destroy( &p_sys->wait );
228     vlc_mutex_destroy( &p_sys->lock );
229     free( p_sys );
230 }
231
232
233 /*****************************************************************************
234  * Run : call Handshake() then submit songs
235  *****************************************************************************/
236 static void Run( intf_thread_t *p_intf )
237 {
238     char                    *psz_submit, *psz_submit_song, *psz_submit_tmp;
239     int                     i_net_ret;
240     int                     i_song;
241     uint8_t                 p_buffer[1024];
242     char                    *p_buffer_pos;
243     int                     i_post_socket;
244     int                     canc = vlc_savecancel();
245
246     intf_sys_t *p_sys = p_intf->p_sys;
247
248     /* main loop */
249     for( ;; )
250     {
251         bool b_wait = false;
252
253
254         vlc_restorecancel( canc );
255         vlc_mutex_lock( &p_sys->lock );
256         mutex_cleanup_push( &p_sys->lock );
257
258         if( mdate() < p_sys->next_exchange )
259             /* wait until we can resubmit, i.e.  */
260             b_wait = vlc_cond_timedwait( &p_sys->wait, &p_sys->lock,
261                                           p_sys->next_exchange ) == 0;
262         else
263             /* wait for data to submit */
264             /* we are signaled each time there is a song to submit */
265             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
266         vlc_cleanup_run();
267         canc = vlc_savecancel();
268
269         if( b_wait )
270             continue; /* holding on until next_exchange */
271
272         /* handshake if needed */
273         if( p_sys->b_handshaked == false )
274         {
275             msg_Dbg( p_intf, "Handshaking with last.fm ..." );
276
277             switch( Handshake( p_intf ) )
278             {
279                 case VLC_ENOMEM:
280                     return;
281
282                 case VLC_ENOVAR:
283                     /* username not set */
284                     dialog_Fatal( p_intf,
285                         _("Last.fm username not set"),
286                         "%s", _("Please set a username or disable the "
287                         "audioscrobbler plugin, and restart VLC.\n"
288                         "Visit http://www.last.fm/join/ to get an account.")
289                     );
290                     return;
291
292                 case VLC_SUCCESS:
293                     msg_Dbg( p_intf, "Handshake successfull :)" );
294                     p_sys->b_handshaked = true;
295                     p_sys->i_interval = 0;
296                     p_sys->next_exchange = mdate();
297                     break;
298
299                 case VLC_AUDIOSCROBBLER_EFATAL:
300                     msg_Warn( p_intf, "Exiting..." );
301                     return;
302
303                 case VLC_EGENERIC:
304                 default:
305                     /* protocol error : we'll try later */
306                     HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
307                     break;
308             }
309             /* if handshake failed let's restart the loop */
310             if( p_sys->b_handshaked == false )
311                 continue;
312         }
313
314         msg_Dbg( p_intf, "Going to submit some data..." );
315
316         /* The session may be invalid if there is a trailing \n */
317         char *psz_ln = strrchr( p_sys->psz_auth_token, '\n' );
318         if( psz_ln )
319             *psz_ln = '\0';
320
321         if( !asprintf( &psz_submit, "s=%s", p_sys->psz_auth_token ) )
322         {   /* Out of memory */
323             return;
324         }
325
326         /* forge the HTTP POST request */
327         vlc_mutex_lock( &p_sys->lock );
328         audioscrobbler_song_t *p_song;
329         for( i_song = 0 ; i_song < p_sys->i_songs ; i_song++ )
330         {
331             p_song = &p_sys->p_queue[i_song];
332             if( !asprintf( &psz_submit_song,
333                     "&a%%5B%d%%5D=%s"
334                     "&t%%5B%d%%5D=%s"
335                     "&i%%5B%d%%5D=%u"
336                     "&o%%5B%d%%5D=P"
337                     "&r%%5B%d%%5D="
338                     "&l%%5B%d%%5D=%d"
339                     "&b%%5B%d%%5D=%s"
340                     "&n%%5B%d%%5D=%s"
341                     "&m%%5B%d%%5D=%s",
342                     i_song, p_song->psz_a,
343                     i_song, p_song->psz_t,
344                     i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
345                     i_song,
346                     i_song,
347                     i_song, p_song->i_l,
348                     i_song, p_song->psz_b,
349                     i_song, p_song->psz_n,
350                     i_song, p_song->psz_m
351             ) )
352             {   /* Out of memory */
353                 vlc_mutex_unlock( &p_sys->lock );
354                 return;
355             }
356             psz_submit_tmp = psz_submit;
357             if( !asprintf( &psz_submit, "%s%s",
358                     psz_submit_tmp, psz_submit_song ) )
359             {   /* Out of memory */
360                 free( psz_submit_tmp );
361                 free( psz_submit_song );
362                 vlc_mutex_unlock( &p_sys->lock );
363                 return;
364             }
365             free( psz_submit_song );
366             free( psz_submit_tmp );
367         }
368         vlc_mutex_unlock( &p_sys->lock );
369
370         i_post_socket = net_ConnectTCP( p_intf,
371             p_sys->psz_submit_host, p_sys->i_submit_port );
372
373         if ( i_post_socket == -1 )
374         {
375             /* If connection fails, we assume we must handshake again */
376             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
377             p_sys->b_handshaked = false;
378             free( psz_submit );
379             continue;
380         }
381
382         /* we transmit the data */
383         i_net_ret = net_Printf(
384             p_intf, i_post_socket, NULL,
385             POST_REQUEST, p_sys->psz_submit_file,
386             (unsigned)strlen( psz_submit ), p_sys->psz_submit_host,
387             VERSION, psz_submit
388         );
389
390         free( psz_submit );
391         if ( i_net_ret == -1 )
392         {
393             /* If connection fails, we assume we must handshake again */
394             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
395             p_sys->b_handshaked = false;
396             continue;
397         }
398
399         i_net_ret = net_Read( p_intf, i_post_socket, NULL,
400                     p_buffer, 1023, false );
401         if ( i_net_ret <= 0 )
402         {
403             /* if we get no answer, something went wrong : try again */
404             continue;
405         }
406
407         net_Close( i_post_socket );
408         p_buffer[i_net_ret] = '\0';
409
410         p_buffer_pos = strstr( ( char * ) p_buffer, "FAILED" );
411         if ( p_buffer_pos )
412         {
413             msg_Warn( p_intf, "%s", p_buffer_pos );
414             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
415             continue;
416         }
417
418         p_buffer_pos = strstr( ( char * ) p_buffer, "BADSESSION" );
419         if ( p_buffer_pos )
420         {
421             msg_Err( p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?" );
422             p_sys->b_handshaked = false;
423             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
424             continue;
425         }
426
427         p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
428         if ( p_buffer_pos )
429         {
430             int i;
431             for( i = 0; i < p_sys->i_songs; i++ )
432                 DeleteSong( &p_sys->p_queue[i] );
433             p_sys->i_songs = 0;
434             p_sys->i_interval = 0;
435             p_sys->next_exchange = mdate();
436             msg_Dbg( p_intf, "Submission successful!" );
437         }
438         else
439         {
440             msg_Err( p_intf, "Authentication failed, handshaking again (%s)", 
441                              p_buffer );
442             p_sys->b_handshaked = false;
443             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
444             continue;
445         }
446     }
447     vlc_restorecancel( canc );
448 }
449
450 /*****************************************************************************
451  * PlayingChange: Playing status change callback
452  *****************************************************************************/
453 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
454                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
455 {
456     VLC_UNUSED( oldval );
457
458     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
459     intf_sys_t      *p_sys  = p_intf->p_sys;
460     input_thread_t  *p_input = ( input_thread_t* )p_this;
461     vlc_value_t     state_value;
462
463     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
464
465     if( newval.i_int != INPUT_EVENT_STATE ) return VLC_SUCCESS;
466
467     state_value.i_int = 0;
468
469     var_Get( p_input, "state", &state_value );
470
471
472     if( p_sys->b_meta_read == false && state_value.i_int >= PLAYING_S )
473     {
474         ReadMetaData( p_intf );
475         return VLC_SUCCESS;
476     }
477
478
479     if( state_value.i_int >= END_S )
480         AddToQueue( p_intf );
481     else if( state_value.i_int == PAUSE_S )
482         p_sys->time_pause = mdate();
483     else if( p_sys->time_pause > 0 && state_value.i_int == PLAYING_S )
484     {
485         p_sys->time_total_pauses += ( mdate() - p_sys->time_pause );
486         p_sys->time_pause = 0;
487     }
488
489     return VLC_SUCCESS;
490 }
491
492 /*****************************************************************************
493  * ItemChange: Playlist item change callback
494  *****************************************************************************/
495 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
496                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
497 {
498     input_thread_t      *p_input;
499     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
500     intf_sys_t          *p_sys      = p_intf->p_sys;
501     input_item_t        *p_item;
502     vlc_value_t         video_val;
503
504     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
505     VLC_UNUSED( oldval ); VLC_UNUSED( newval );
506
507     p_sys->b_state_cb       = false;
508     p_sys->b_meta_read      = false;
509     p_sys->b_submit         = false;
510
511     p_input = playlist_CurrentInput( pl_Get( p_intf ) );
512
513     if( !p_input || p_input->b_dead )
514         return VLC_SUCCESS;
515
516     p_item = input_GetItem( p_input );
517     if( !p_item )
518     {
519         vlc_object_release( p_input );
520         return VLC_SUCCESS;
521     }
522
523     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
524     if( video_val.i_int > 0 )
525     {
526         msg_Dbg( p_this, "Not an audio-only input, not submitting");
527         vlc_object_release( p_input );
528         return VLC_SUCCESS;
529     }
530
531     p_sys->time_total_pauses = 0;
532     time( &p_sys->p_current_song.date );        /* to be sent to last.fm */
533     p_sys->p_current_song.i_start = mdate();    /* only used locally */
534
535     var_AddCallback( p_input, "intf-event", PlayingChange, p_intf );
536     p_sys->b_state_cb = true;
537
538     if( input_item_IsPreparsed( p_item ) )
539         ReadMetaData( p_intf );
540     /* if the input item was not preparsed, we'll do it in PlayingChange()
541      * callback, when "state" == PLAYING_S */
542
543     vlc_object_release( p_input );
544     return VLC_SUCCESS;
545 }
546
547 /*****************************************************************************
548  * AddToQueue: Add the played song to the queue to be submitted
549  *****************************************************************************/
550 static void AddToQueue ( intf_thread_t *p_this )
551 {
552     mtime_t                     played_time;
553     intf_sys_t                  *p_sys = p_this->p_sys;
554
555     vlc_mutex_lock( &p_sys->lock );
556     if( !p_sys->b_submit )
557         goto end;
558
559     /* wait for the user to listen enough before submitting */
560     played_time = mdate() - p_sys->p_current_song.i_start -
561                             p_sys->time_total_pauses;
562     played_time /= 1000000; /* µs → s */
563
564     /*HACK: it seam that the preparsing sometime fail,
565             so use the playing time as the song length */
566     if( p_sys->p_current_song.i_l == 0 )
567         p_sys->p_current_song.i_l = played_time;
568
569     /* Don't send song shorter than 30s */
570     if( p_sys->p_current_song.i_l < 30 )
571     {
572         msg_Dbg( p_this, "Song too short (< 30s), not submitting" );
573         goto end;
574     }
575
576     /* Send if the user had listen more than 240s OR half the track length */
577     if( ( played_time < 240 ) &&
578         ( played_time < ( p_sys->p_current_song.i_l / 2 ) ) )
579     {
580         msg_Dbg( p_this, "Song not listened long enough, not submitting" );
581         goto end;
582     }
583
584     /* Check that all meta are present */
585     if( !p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
586         !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t )
587     {
588         msg_Dbg( p_this, "Missing artist or title, not submitting" );
589         goto end;
590     }
591
592     if( p_sys->i_songs >= QUEUE_MAX )
593     {
594         msg_Warn( p_this, "Submission queue is full, not submitting" );
595         goto end;
596     }
597
598     msg_Dbg( p_this, "Song will be submitted." );
599
600 #define QUEUE_COPY( a ) \
601     p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
602
603 #define QUEUE_COPY_NULL( a ) \
604     QUEUE_COPY( a ); \
605     p_sys->p_current_song.a = NULL
606
607     QUEUE_COPY( i_l );
608     QUEUE_COPY_NULL( psz_n );
609     QUEUE_COPY_NULL( psz_a );
610     QUEUE_COPY_NULL( psz_t );
611     QUEUE_COPY_NULL( psz_b );
612     QUEUE_COPY_NULL( psz_m );
613     QUEUE_COPY( date );
614 #undef QUEUE_COPY_NULL
615 #undef QUEUE_COPY
616
617     p_sys->i_songs++;
618
619     /* signal the main loop we have something to submit */
620     vlc_cond_signal( &p_sys->wait );
621
622 end:
623     DeleteSong( &p_sys->p_current_song );
624     p_sys->b_submit = false;
625     vlc_mutex_unlock( &p_sys->lock );
626 }
627
628 /*****************************************************************************
629  * ParseURL : Split an http:// URL into host, file, and port
630  *
631  * Example: "62.216.251.205:80/protocol_1.2"
632  *      will be split into "62.216.251.205", 80, "protocol_1.2"
633  *
634  * psz_url will be freed before returning
635  * *psz_file & *psz_host will be freed before use
636  *
637  * Return value:
638  *  VLC_ENOMEM      Out Of Memory
639  *  VLC_EGENERIC    Invalid url provided
640  *  VLC_SUCCESS     Success
641  *****************************************************************************/
642 static int ParseURL( char *psz_url, char **psz_host, char **psz_file,
643                         int *i_port )
644 {
645     int i_pos;
646     int i_len = strlen( psz_url );
647     bool b_no_port = false;
648     FREENULL( *psz_host );
649     FREENULL( *psz_file );
650
651     i_pos = strcspn( psz_url, ":" );
652     if( i_pos == i_len )
653     {
654         *i_port = 80;
655         i_pos = strcspn( psz_url, "/" );
656         b_no_port = true;
657     }
658
659     *psz_host = strndup( psz_url, i_pos );
660     if( !*psz_host )
661         return VLC_ENOMEM;
662
663     if( !b_no_port )
664     {
665         i_pos++; /* skip the ':' */
666         *i_port = atoi( psz_url + i_pos );
667         if( *i_port <= 0 )
668         {
669             FREENULL( *psz_host );
670             return VLC_EGENERIC;
671         }
672
673         i_pos = strcspn( psz_url, "/" );
674     }
675
676     if( i_pos == i_len )
677         return VLC_EGENERIC;
678
679     i_pos++; /* skip the '/' */
680     *psz_file = strdup( psz_url + i_pos );
681     if( !*psz_file )
682     {
683         FREENULL( *psz_host );
684         return VLC_ENOMEM;
685     }
686
687     free( psz_url );
688     return VLC_SUCCESS;
689 }
690
691 /*****************************************************************************
692  * Handshake : Init audioscrobbler connection
693  *****************************************************************************/
694 static int Handshake( intf_thread_t *p_this )
695 {
696     char                *psz_username, *psz_password;
697     char                *psz_scrobbler_url;
698     time_t              timestamp;
699     char                psz_timestamp[21];
700
701     struct md5_s        p_struct_md5;
702
703     stream_t            *p_stream;
704     char                *psz_handshake_url;
705     uint8_t             p_buffer[1024];
706     char                *p_buffer_pos;
707
708     int                 i_ret;
709     char                *psz_url;
710
711     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
712     intf_sys_t          *p_sys                  = p_this->p_sys;
713
714     psz_username = var_InheritString( p_this, "lastfm-username" );
715     if( !psz_username )
716         return VLC_ENOMEM;
717
718     psz_password = var_InheritString( p_this, "lastfm-password" );
719     if( !psz_password )
720     {
721         free( psz_username );
722         return VLC_ENOMEM;
723     }
724
725     /* username or password have not been setup */
726     if ( !*psz_username || !*psz_password )
727     {
728         free( psz_username );
729         free( psz_password );
730         return VLC_ENOVAR;
731     }
732
733     time( &timestamp );
734
735     /* generates a md5 hash of the password */
736     InitMD5( &p_struct_md5 );
737     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
738     EndMD5( &p_struct_md5 );
739
740     free( psz_password );
741
742     char *psz_password_md5 = psz_md5_hash( &p_struct_md5 );
743     if( !psz_password_md5 )
744     {
745         free( psz_username );
746         return VLC_ENOMEM;
747     }
748
749     snprintf( psz_timestamp, sizeof( psz_timestamp ), "%"PRIu64,
750               (uint64_t)timestamp );
751
752     /* generates a md5 hash of :
753      * - md5 hash of the password, plus
754      * - timestamp in clear text
755      */
756     InitMD5( &p_struct_md5 );
757     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
758     AddMD5( &p_struct_md5, ( uint8_t* ) psz_timestamp, strlen( psz_timestamp ));
759     EndMD5( &p_struct_md5 );
760     free( psz_password_md5 );
761
762     char *psz_auth_token = psz_md5_hash( &p_struct_md5 );
763     if( !psz_auth_token )
764     {
765         free( psz_username );
766         return VLC_ENOMEM;
767     }
768     strncpy( p_sys->psz_auth_token, psz_auth_token, 33 );
769     free( psz_auth_token );
770
771     psz_scrobbler_url = var_InheritString( p_this, "scrobbler-url" );
772     if( !psz_scrobbler_url )
773     {
774         free( psz_username );
775         return VLC_ENOMEM;
776     }
777
778     if( !asprintf( &psz_handshake_url,
779     "http://%s/?hs=true&p=1.2&c=%s&v=%s&u=%s&t=%s&a=%s", psz_scrobbler_url,
780         CLIENT_NAME, CLIENT_VERSION, psz_username, psz_timestamp,
781         p_sys->psz_auth_token ) )
782     {
783         free( psz_scrobbler_url );
784         free( psz_username );
785         return VLC_ENOMEM;
786     }
787     free( psz_scrobbler_url );
788     free( psz_username );
789
790     /* send the http handshake request */
791     p_stream = stream_UrlNew( p_intf, psz_handshake_url );
792     free( psz_handshake_url );
793
794     if( !p_stream )
795         return VLC_EGENERIC;
796
797     /* read answer */
798     i_ret = stream_Read( p_stream, p_buffer, 1023 );
799     if( i_ret == 0 )
800     {
801         stream_Delete( p_stream );
802         return VLC_EGENERIC;
803     }
804     p_buffer[i_ret] = '\0';
805     stream_Delete( p_stream );
806
807     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED " );
808     if ( p_buffer_pos )
809     {
810         /* handshake request failed, sorry */
811         msg_Err( p_this, "last.fm handshake failed: %s", p_buffer_pos + 7 );
812         return VLC_EGENERIC;
813     }
814
815     p_buffer_pos = strstr( ( char* ) p_buffer, "BADAUTH" );
816     if ( p_buffer_pos )
817     {
818         /* authentication failed, bad username/password combination */
819         dialog_Fatal( p_this,
820             _("last.fm: Authentication failed"),
821             "%s", _("last.fm username or password is incorrect. "
822               "Please verify your settings and relaunch VLC." ) );
823         return VLC_AUDIOSCROBBLER_EFATAL;
824     }
825
826     p_buffer_pos = strstr( ( char* ) p_buffer, "BANNED" );
827     if ( p_buffer_pos )
828     {
829         /* oops, our version of vlc has been banned by last.fm servers */
830         msg_Err( p_intf, "This version of VLC has been banned by last.fm. "
831                          "You should upgrade VLC, or disable the last.fm plugin." );
832         return VLC_AUDIOSCROBBLER_EFATAL;
833     }
834
835     p_buffer_pos = strstr( ( char* ) p_buffer, "BADTIME" );
836     if ( p_buffer_pos )
837     {
838         /* The system clock isn't good */
839         msg_Err( p_intf, "last.fm handshake failed because your clock is too "
840                          "much shifted. Please correct it, and relaunch VLC." );
841         return VLC_AUDIOSCROBBLER_EFATAL;
842     }
843
844     p_buffer_pos = strstr( ( char* ) p_buffer, "OK" );
845     if ( !p_buffer_pos )
846         goto proto;
847
848     p_buffer_pos = strstr( p_buffer_pos, "\n" );
849     if( !p_buffer_pos || strlen( p_buffer_pos ) < 34 )
850         goto proto;
851     p_buffer_pos++; /* we skip the '\n' */
852
853     /* save the session ID */
854     snprintf( p_sys->psz_auth_token, 33, "%s", p_buffer_pos );
855
856     p_buffer_pos = strstr( p_buffer_pos, "http://" );
857     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
858         goto proto;
859
860     /* We need to read the nowplaying url */
861     p_buffer_pos += 7; /* we skip "http://" */
862 #if 0 //NOT USED
863     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
864     if( !psz_url )
865         goto oom;
866
867     switch( ParseURL( psz_url, &p_sys->psz_nowp_host,
868                 &p_sys->psz_nowp_file, &p_sys->i_nowp_port ) )
869     {
870         case VLC_ENOMEM:
871             goto oom;
872         case VLC_EGENERIC:
873             goto proto;
874         case VLC_SUCCESS:
875         default:
876             break;
877     }
878 #endif
879     p_buffer_pos = strstr( p_buffer_pos, "http://" );
880     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
881         goto proto;
882
883     /* We need to read the submission url */
884     p_buffer_pos += 7; /* we skip "http://" */
885     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
886     if( !psz_url )
887         goto oom;
888
889     switch( ParseURL( psz_url, &p_sys->psz_submit_host,
890                 &p_sys->psz_submit_file, &p_sys->i_submit_port ) )
891     {
892         case VLC_ENOMEM:
893             goto oom;
894         case VLC_EGENERIC:
895             goto proto;
896         case VLC_SUCCESS:
897         default:
898             break;
899     }
900
901     return VLC_SUCCESS;
902
903 oom:
904     return VLC_ENOMEM;
905
906 proto:
907     msg_Err( p_intf, "Handshake: can't recognize server protocol" );
908     return VLC_EGENERIC;
909 }
910
911 /*****************************************************************************
912  * DeleteSong : Delete the char pointers in a song
913  *****************************************************************************/
914 static void DeleteSong( audioscrobbler_song_t* p_song )
915 {
916     FREENULL( p_song->psz_a );
917     FREENULL( p_song->psz_b );
918     FREENULL( p_song->psz_t );
919     FREENULL( p_song->psz_m );
920     FREENULL( p_song->psz_n );
921 }
922
923 /*****************************************************************************
924  * ReadMetaData : Read meta data when parsed by vlc
925  *****************************************************************************/
926 static int ReadMetaData( intf_thread_t *p_this )
927 {
928     input_thread_t      *p_input;
929     input_item_t        *p_item;
930
931     intf_sys_t          *p_sys = p_this->p_sys;
932
933     p_input = playlist_CurrentInput( pl_Get( p_this ) );
934     if( !p_input )
935         return( VLC_SUCCESS );
936
937     p_item = input_GetItem( p_input );
938     if( !p_item )
939         return VLC_SUCCESS;
940
941     char *psz_meta;
942 #define ALLOC_ITEM_META( a, b ) \
943     psz_meta = input_item_Get##b( p_item ); \
944     if( psz_meta && *psz_meta ) \
945     { \
946         a = encode_URI_component( psz_meta ); \
947         if( !a ) \
948         { \
949             vlc_mutex_unlock( &p_sys->lock ); \
950             vlc_object_release( p_input ); \
951             free( psz_meta ); \
952             return VLC_ENOMEM; \
953         } \
954     }
955
956     vlc_mutex_lock( &p_sys->lock );
957
958     p_sys->b_meta_read = true;
959
960     ALLOC_ITEM_META( p_sys->p_current_song.psz_a, Artist )
961     else
962     {
963         vlc_mutex_unlock( &p_sys->lock );
964         msg_Dbg( p_this, "No artist.." );
965         vlc_object_release( p_input );
966         free( psz_meta );
967         return VLC_EGENERIC;
968     }
969     free( psz_meta );
970
971     ALLOC_ITEM_META( p_sys->p_current_song.psz_t, Title )
972     else
973     {
974         vlc_mutex_unlock( &p_sys->lock );
975         msg_Dbg( p_this, "No track name.." );
976         vlc_object_release( p_input );
977         free( p_sys->p_current_song.psz_a );
978         free( psz_meta );
979         return VLC_EGENERIC;
980     }
981     free( psz_meta );
982
983     /* Now we have read the mandatory meta data, so we can submit that info */
984     p_sys->b_submit = true;
985
986     ALLOC_ITEM_META( p_sys->p_current_song.psz_b, Album )
987     else
988         p_sys->p_current_song.psz_b = calloc( 1, 1 );
989     free( psz_meta );
990
991     ALLOC_ITEM_META( p_sys->p_current_song.psz_m, TrackID )
992     else
993         p_sys->p_current_song.psz_m = calloc( 1, 1 );
994     free( psz_meta );
995
996     p_sys->p_current_song.i_l = input_item_GetDuration( p_item ) / 1000000;
997
998     ALLOC_ITEM_META( p_sys->p_current_song.psz_n, TrackNum )
999     else
1000         p_sys->p_current_song.psz_n = calloc( 1, 1 );
1001     free( psz_meta );
1002 #undef ALLOC_ITEM_META
1003
1004     msg_Dbg( p_this, "Meta data registered" );
1005
1006     vlc_mutex_unlock( &p_sys->lock );
1007     vlc_object_release( p_input );
1008     return VLC_SUCCESS;
1009
1010 }
1011
1012 static void HandleInterval( mtime_t *next, unsigned int *i_interval )
1013 {
1014     if( *i_interval == 0 )
1015     {
1016         /* first interval is 1 minute */
1017         *i_interval = 1;
1018     }
1019     else
1020     {
1021         /* else we double the previous interval, up to 120 minutes */
1022         *i_interval <<= 1;
1023         if( *i_interval > 120 )
1024             *i_interval = 120;
1025     }
1026     *next = mdate() + ( *i_interval * 1000000 * 60 );
1027 }
1028