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