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