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