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