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