]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
Bugfix: last.fm segfaults under Windows This is due to %ju unsupported in printf...
[vlc] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright © 2006-2008 the VideoLAN team
5  * $Id$
6  *
7  * Author: Rafaël Carré <funman at videolanorg>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /* audioscrobbler protocol version: 1.2
25  * http://www.audioscrobbler.net/development/protocol/
26  *
27  * TODO:    "Now Playing" feature (not mandatory)
28  */
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32
33 #if defined( WIN32 ) 
34 #include <time.h> 
35 #endif 
36
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_interface.h>
44 #include <vlc_meta.h>
45 #include <vlc_md5.h>
46 #include <vlc_block.h>
47 #include <vlc_stream.h>
48 #include <vlc_url.h>
49 #include <vlc_network.h>
50 #include <vlc_interface.h>
51 #include <vlc_playlist.h>
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56
57 #define QUEUE_MAX 50
58
59 /* Keeps track of metadata to be submitted */
60 typedef struct audioscrobbler_song_t
61 {
62     char        *psz_a;             /**< track artist     */
63     char        *psz_t;             /**< track title      */
64     char        *psz_b;             /**< track album      */
65     char        *psz_n;             /**< track number     */
66     int         i_l;                /**< track length     */
67     char        *psz_m;             /**< musicbrainz id   */
68     time_t      date;               /**< date since epoch */
69     mtime_t     i_start;            /**< playing start    */
70 } audioscrobbler_song_t;
71
72 struct intf_sys_t
73 {
74     audioscrobbler_song_t   p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
75     int                     i_songs;            /**< number of songs        */
76
77     vlc_mutex_t             lock;               /**< p_sys mutex            */
78
79     /* data about audioscrobbler session */
80     mtime_t                 next_exchange;      /**< when can we send data  */
81     unsigned int            i_interval;         /**< waiting interval (secs)*/
82
83     /* submission of played songs */
84     char                    *psz_submit_host;   /**< where to submit data   */
85     int                     i_submit_port;      /**< port to which submit   */
86     char                    *psz_submit_file;   /**< file to which submit   */
87
88     /* submission of playing song */
89 #if 0 //NOT USED
90     char                    *psz_nowp_host;     /**< where to submit data   */
91     int                     i_nowp_port;        /**< port to which submit   */
92     char                    *psz_nowp_file;     /**< file to which submit   */
93 #endif
94     bool              b_handshaked;       /**< are we authenticated ? */
95     char                    psz_auth_token[33]; /**< Authentication token */
96
97     /* data about song currently playing */
98     audioscrobbler_song_t   p_current_song;     /**< song being played      */
99
100     mtime_t                 time_pause;         /**< time when vlc paused   */
101     mtime_t                 time_total_pauses;  /**< total time in pause    */
102
103     bool              b_submit;           /**< do we have to submit ? */
104
105     bool              b_state_cb;         /**< if we registered the
106                                                  * "state" callback         */
107
108     bool              b_meta_read;        /**< if we read the song's
109                                                  * metadata already         */
110 };
111
112 static int  Open            ( vlc_object_t * );
113 static void Close           ( vlc_object_t * );
114 static void Run             ( intf_thread_t * );
115
116 static int ItemChange       ( vlc_object_t *, const char *, vlc_value_t,
117                                 vlc_value_t, void * );
118 static int PlayingChange    ( vlc_object_t *, const char *, vlc_value_t,
119                                 vlc_value_t, void * );
120
121 static void AddToQueue      ( intf_thread_t * );
122 static int Handshake        ( intf_thread_t * );
123 static int ReadMetaData     ( intf_thread_t * );
124 static void DeleteSong      ( audioscrobbler_song_t* );
125 static int ParseURL         ( char *, char **, char **, int * );
126 static void HandleInterval  ( mtime_t *, unsigned int * );
127
128 /*****************************************************************************
129  * Module descriptor
130  ****************************************************************************/
131
132 #define USERNAME_TEXT       N_("Username")
133 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
134 #define PASSWORD_TEXT       N_("Password")
135 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
136
137 /* This error value is used when last.fm plugin has to be unloaded. */
138 #define VLC_AUDIOSCROBBLER_EFATAL -69
139
140 /* last.fm client identifier */
141 #define CLIENT_NAME     PACKAGE
142 #define CLIENT_VERSION  VERSION
143
144 /* HTTP POST request : to submit data */
145 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
146                         "Accept-Encoding: identity\n"                       \
147                         "Content-length: %u\n"                              \
148                         "Connection: close\n"                               \
149                         "Content-type: application/x-www-form-urlencoded\n" \
150                         "Host: %s\n"                                        \
151                         "User-agent: VLC Media Player/%s\r\n"               \
152                         "\r\n"                                              \
153                         "%s\r\n"                                            \
154                         "\r\n"
155
156 vlc_module_begin();
157     set_category( CAT_INTERFACE );
158     set_subcategory( SUBCAT_INTERFACE_CONTROL );
159     set_shortname( N_( "Audioscrobbler" ) );
160     set_description( N_("Submission of played songs to last.fm") );
161     add_string( "lastfm-username", "", NULL,
162                 USERNAME_TEXT, USERNAME_LONGTEXT, false );
163     add_password( "lastfm-password", "", NULL,
164                 PASSWORD_TEXT, PASSWORD_LONGTEXT, false );
165     set_capability( "interface", 0 );
166     set_callbacks( Open, Close );
167 vlc_module_end();
168
169 /*****************************************************************************
170  * Open: initialize and create stuff
171  *****************************************************************************/
172 static int Open( vlc_object_t *p_this )
173 {
174     playlist_t      *p_playlist;
175     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
176     intf_sys_t      *p_sys      = calloc( 1, sizeof( intf_sys_t ) );
177
178     if( !p_sys )
179         return VLC_ENOMEM;
180
181     p_intf->p_sys = p_sys;
182
183     vlc_mutex_init( &p_sys->lock );
184
185     p_playlist = pl_Yield( p_intf );
186     PL_LOCK;
187     var_AddCallback( p_playlist, "playlist-current", ItemChange, p_intf );
188     PL_UNLOCK;
189     pl_Release( p_intf );
190
191     p_intf->pf_run = Run;
192
193     return VLC_SUCCESS;
194 }
195
196 /*****************************************************************************
197  * Close: destroy interface stuff
198  *****************************************************************************/
199 static void Close( vlc_object_t *p_this )
200 {
201     playlist_t                  *p_playlist;
202     input_thread_t              *p_input;
203     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
204     intf_sys_t                  *p_sys  = p_intf->p_sys;
205
206     p_playlist = pl_Yield( p_intf );
207     if( p_playlist )
208     {
209         PL_LOCK;
210
211         var_DelCallback( p_playlist, "playlist-current", ItemChange, p_intf );
212
213         p_input = p_playlist->p_input;
214         if ( p_input )
215         {
216             vlc_object_yield( p_input );
217
218             if( p_sys->b_state_cb )
219                 var_DelCallback( p_input, "state", PlayingChange, p_intf );
220
221             vlc_object_release( p_input );
222         }
223
224         PL_UNLOCK;
225         pl_Release( p_intf );
226     }
227
228     p_intf->b_dead = true;
229     /* we lock the mutex in case p_sys is being accessed from a callback */
230     vlc_mutex_lock ( &p_sys->lock );
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_mutex_unlock ( &p_sys->lock );
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
258     intf_sys_t *p_sys = p_intf->p_sys;
259
260     /* main loop */
261     for( ;; )
262     {
263         bool b_wait = false;
264
265         vlc_object_lock( p_intf );
266         if( !vlc_object_alive( p_intf ) )
267         {
268             vlc_object_unlock( p_intf );
269             msg_Dbg( p_intf, "audioscrobbler is dying");
270             return;
271         }
272         if( mdate() < p_sys->next_exchange )
273             /* wait until we can resubmit, i.e.  */
274             b_wait = vlc_object_timedwait( p_intf, 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_object_wait( p_intf );
279         vlc_object_unlock( p_intf );
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                     intf_UserFatal( p_intf, false,
297                         _("Last.fm username not set"),
298                         _("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_file,
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 }
460
461 /*****************************************************************************
462  * PlayingChange: Playing status change callback
463  *****************************************************************************/
464 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
465                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
466 {
467     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
468     intf_sys_t      *p_sys  = p_intf->p_sys;
469
470     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
471
472     if( p_intf->b_dead )
473         return VLC_SUCCESS;
474
475     if( p_sys->b_meta_read == false && newval.i_int >= PLAYING_S )
476     {
477         ReadMetaData( p_intf );
478         return VLC_SUCCESS;
479     }
480
481     if( newval.i_int >= END_S )
482         AddToQueue( p_intf );
483     else if( oldval.i_int == PLAYING_S && newval.i_int == PAUSE_S )
484         p_sys->time_pause = mdate();
485     else if( oldval.i_int == PAUSE_S && newval.i_int == PLAYING_S )
486         p_sys->time_total_pauses += ( mdate() - p_sys->time_pause );
487
488     return VLC_SUCCESS;
489 }
490
491 /*****************************************************************************
492  * ItemChange: Playlist item change callback
493  *****************************************************************************/
494 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
495                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
496 {
497     playlist_t          *p_playlist;
498     input_thread_t      *p_input;
499     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
500     intf_sys_t          *p_sys      = p_intf->p_sys;
501     input_item_t        *p_item;
502     vlc_value_t         video_val;
503
504     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
505     VLC_UNUSED( oldval ); VLC_UNUSED( newval );
506
507     if( p_intf->b_dead )
508         return VLC_SUCCESS;
509
510     p_sys->b_state_cb       = false;
511     p_sys->b_meta_read      = false;
512     p_sys->b_submit         = false;
513
514     p_playlist = pl_Yield( p_intf );
515     PL_LOCK;
516     p_input = p_playlist->p_input;
517
518     if( !p_input || p_input->b_dead )
519     {
520         PL_UNLOCK;
521         pl_Release( p_intf );
522         return VLC_SUCCESS;
523     }
524
525     vlc_object_yield( p_input );
526     PL_UNLOCK;
527     pl_Release( p_intf );
528
529     p_item = input_GetItem( p_input );
530     if( !p_item )
531     {
532         vlc_object_release( p_input );
533         return VLC_SUCCESS;
534     }
535
536     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
537     if( ( video_val.i_int > 0 ) || p_item->i_type == ITEM_TYPE_NET )
538     {
539         msg_Dbg( p_this, "Not an audio local file, not submitting");
540         vlc_object_release( p_input );
541         return VLC_SUCCESS;
542     }
543
544     p_sys->time_total_pauses = 0;
545     time( &p_sys->p_current_song.date );        /* to be sent to last.fm */
546     p_sys->p_current_song.i_start = mdate();    /* only used locally */
547
548     var_AddCallback( p_input, "state", PlayingChange, p_intf );
549     p_sys->b_state_cb = true;
550
551     if( input_item_IsPreparsed( p_item ) )
552         ReadMetaData( p_intf );
553     /* if the input item was not preparsed, we'll do it in PlayingChange()
554      * callback, when "state" == PLAYING_S */
555
556     vlc_object_release( p_input );
557     return VLC_SUCCESS;
558 }
559
560 /*****************************************************************************
561  * AddToQueue: Add the played song to the queue to be submitted
562  *****************************************************************************/
563 static void AddToQueue ( intf_thread_t *p_this )
564 {
565     mtime_t                     played_time;
566     intf_sys_t                  *p_sys = p_this->p_sys;
567
568     vlc_mutex_lock( &p_sys->lock );
569     if( !p_sys->b_submit )
570         goto end;
571
572     /* wait for the user to listen enough before submitting */
573     played_time = mdate() - p_sys->p_current_song.i_start -
574                             p_sys->time_total_pauses;
575     played_time /= 1000000; /* µs → s */
576
577     if( ( played_time < 60 ) &&
578         ( played_time < ( p_sys->p_current_song.i_l / 2 ) ) )
579     {
580         msg_Dbg( p_this, "Song not listened long enough, not submitting" );
581         goto end;
582     }
583
584     if( p_sys->p_current_song.i_l < 30 )
585     {
586         if( played_time < 30 )
587         {
588             msg_Dbg( p_this, "Song too short (< 30s), not submitting" );
589             goto end;
590         }
591         else
592             /* This is a HACK to avoid length = 0 (seems to be rejected by audioscrobbler) */
593             p_sys->p_current_song.i_l = played_time;
594     }
595
596     if( !p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
597         !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t )
598     {
599         msg_Dbg( p_this, "Missing artist or title, not submitting" );
600 /*XXX*/        msg_Dbg( p_this, "%s %s", p_sys->p_current_song.psz_a, p_sys->p_current_song.psz_t );
601         goto end;
602     }
603
604     if( p_sys->i_songs >= QUEUE_MAX )
605     {
606         msg_Warn( p_this, "Submission queue is full, not submitting" );
607         goto end;
608     }
609
610     msg_Dbg( p_this, "Song will be submitted." );
611
612 #define QUEUE_COPY( a ) \
613     p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
614
615 #define QUEUE_COPY_NULL( a ) \
616     QUEUE_COPY( a ); \
617     p_sys->p_current_song.a = NULL
618
619     QUEUE_COPY( i_l );
620     QUEUE_COPY_NULL( psz_n );
621     QUEUE_COPY_NULL( psz_a );
622     QUEUE_COPY_NULL( psz_t );
623     QUEUE_COPY_NULL( psz_b );
624     QUEUE_COPY_NULL( psz_m );
625     QUEUE_COPY( date );
626 #undef QUEUE_COPY_NULL
627 #undef QUEUE_COPY
628
629     p_sys->i_songs++;
630
631     /* signal the main loop we have something to submit */
632     vlc_object_signal( VLC_OBJECT( p_this ) );
633
634 end:
635     DeleteSong( &p_sys->p_current_song );
636     p_sys->b_submit = false;
637     vlc_mutex_unlock( &p_sys->lock );
638 }
639
640 /*****************************************************************************
641  * ParseURL : Split an http:// URL into host, file, and port
642  *
643  * Example: "62.216.251.205:80/protocol_1.2"
644  *      will be split into "62.216.251.205", 80, "protocol_1.2"
645  *
646  * psz_url will be freed before returning
647  * *psz_file & *psz_host will be freed before use
648  *
649  * Return value:
650  *  VLC_ENOMEM      Out Of Memory
651  *  VLC_EGENERIC    Invalid url provided
652  *  VLC_SUCCESS     Success
653  *****************************************************************************/
654 static int ParseURL( char *psz_url, char **psz_host, char **psz_file,
655                         int *i_port )
656 {
657     int i_pos;
658     int i_len = strlen( psz_url );
659     FREENULL( *psz_host );
660     FREENULL( *psz_file );
661
662     i_pos = strcspn( psz_url, ":" );
663     if( i_pos == i_len )
664         return VLC_EGENERIC;
665
666     *psz_host = strndup( psz_url, i_pos );
667     if( !*psz_host )
668         return VLC_ENOMEM;
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     if( i_pos == i_len )
681         return VLC_EGENERIC;
682
683     i_pos++; /* skip the '/' */
684     *psz_file = strdup( psz_url + i_pos );
685     if( !*psz_file )
686     {
687         FREENULL( *psz_host );
688         return VLC_ENOMEM;
689     }
690
691     free( psz_url );
692     return VLC_SUCCESS;
693 }
694
695 /*****************************************************************************
696  * Handshake : Init audioscrobbler connection
697  *****************************************************************************/
698 static int Handshake( intf_thread_t *p_this )
699 {
700     char                *psz_username, *psz_password;
701     time_t              timestamp;
702     char                psz_timestamp[21];
703
704     struct md5_s        p_struct_md5;
705
706     stream_t            *p_stream;
707     char                *psz_handshake_url;
708     uint8_t             p_buffer[1024];
709     char                *p_buffer_pos;
710
711     int                 i_ret;
712     char                *psz_url;
713
714     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
715     intf_sys_t          *p_sys                  = p_this->p_sys;
716
717     psz_username = config_GetPsz( p_this, "lastfm-username" );
718     if( !psz_username )
719         return VLC_ENOMEM;
720
721     psz_password = config_GetPsz( p_this, "lastfm-password" );
722     if( !psz_password )
723     {
724         free( psz_username );
725         return VLC_ENOMEM;
726     }
727
728     /* username or password have not been setup */
729     if ( !*psz_username || !*psz_password )
730     {
731         free( psz_username );
732         free( psz_password );
733         return VLC_ENOVAR;
734     }
735
736     time( &timestamp );
737
738     /* generates a md5 hash of the password */
739     InitMD5( &p_struct_md5 );
740     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
741     EndMD5( &p_struct_md5 );
742
743     free( psz_password );
744
745     char *psz_password_md5 = psz_md5_hash( &p_struct_md5 );
746     if( !psz_password_md5 )
747     {
748         free( psz_username );
749         return VLC_ENOMEM;
750     }
751
752     snprintf( psz_timestamp, sizeof( psz_timestamp ), "%"PRIu64,
753               (uint64_t)timestamp );
754
755     /* generates a md5 hash of :
756      * - md5 hash of the password, plus
757      * - timestamp in clear text
758      */
759     InitMD5( &p_struct_md5 );
760     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
761     AddMD5( &p_struct_md5, ( uint8_t* ) psz_timestamp, strlen( psz_timestamp ));
762     EndMD5( &p_struct_md5 );
763     free( psz_password_md5 );
764
765     char *psz_auth_token = psz_md5_hash( &p_struct_md5 );
766     if( !psz_auth_token )
767     {
768         free( psz_username );
769         return VLC_ENOMEM;
770     }
771     strncpy( p_sys->psz_auth_token, psz_auth_token, 33 );
772     free( psz_auth_token );
773
774     if( !asprintf( &psz_handshake_url,
775     "http://post.audioscrobbler.com/?hs=true&p=1.2&c=%s&v=%s&u=%s&t=%s&a=%s",
776         CLIENT_NAME, CLIENT_VERSION, psz_username, psz_timestamp,
777         p_sys->psz_auth_token ) )
778     {
779         free( psz_username );
780         return VLC_ENOMEM;
781     }
782     free( psz_username );
783
784     /* send the http handshake request */
785     p_stream = stream_UrlNew( p_intf, psz_handshake_url );
786     free( psz_handshake_url );
787
788     if( !p_stream )
789         return VLC_EGENERIC;
790
791     /* read answer */
792     i_ret = stream_Read( p_stream, p_buffer, 1023 );
793     if( i_ret == 0 )
794     {
795         stream_Delete( p_stream );
796         return VLC_EGENERIC;
797     }
798     p_buffer[i_ret] = '\0';
799     stream_Delete( p_stream );
800
801     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED " );
802     if ( p_buffer_pos )
803     {
804         /* handshake request failed, sorry */
805         msg_Err( p_this, "last.fm handshake failed: %s", p_buffer_pos + 7 );
806         return VLC_EGENERIC;
807     }
808
809     p_buffer_pos = strstr( ( char* ) p_buffer, "BADAUTH" );
810     if ( p_buffer_pos )
811     {
812         /* authentication failed, bad username/password combination */
813         intf_UserFatal( p_this, false,
814             _("last.fm: Authentication failed"),
815             _("last.fm username or password is incorrect. "
816               "Please verify your settings and relaunch VLC." ) );
817         return VLC_AUDIOSCROBBLER_EFATAL;
818     }
819
820     p_buffer_pos = strstr( ( char* ) p_buffer, "BANNED" );
821     if ( p_buffer_pos )
822     {
823         /* oops, our version of vlc has been banned by last.fm servers */
824         msg_Err( p_intf, "This version of VLC has been banned by last.fm. "
825                          "You should upgrade VLC, or disable the last.fm plugin." );
826         return VLC_AUDIOSCROBBLER_EFATAL;
827     }
828
829     p_buffer_pos = strstr( ( char* ) p_buffer, "BADTIME" );
830     if ( p_buffer_pos )
831     {
832         /* The system clock isn't good */
833         msg_Err( p_intf, "last.fm handshake failed because your clock is too "
834                          "much shifted. Please correct it, and relaunch VLC." );
835         return VLC_AUDIOSCROBBLER_EFATAL;
836     }
837
838     p_buffer_pos = strstr( ( char* ) p_buffer, "OK" );
839     if ( !p_buffer_pos )
840         goto proto;
841
842     p_buffer_pos = strstr( p_buffer_pos, "\n" );
843     if( !p_buffer_pos || strlen( p_buffer_pos ) < 34 )
844         goto proto;
845     p_buffer_pos++; /* we skip the '\n' */
846
847     /* save the session ID */
848     snprintf( p_sys->psz_auth_token, 33, "%s", p_buffer_pos );
849
850     p_buffer_pos = strstr( p_buffer_pos, "http://" );
851     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
852         goto proto;
853
854     /* We need to read the nowplaying url */
855     p_buffer_pos += 7; /* we skip "http://" */
856 #if 0 //NOT USED
857     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
858     if( !psz_url )
859         goto oom;
860
861     switch( ParseURL( psz_url, &p_sys->psz_nowp_host,
862                 &p_sys->psz_nowp_file, &p_sys->i_nowp_port ) )
863     {
864         case VLC_ENOMEM:
865             goto oom;
866         case VLC_EGENERIC:
867             goto proto;
868         case VLC_SUCCESS:
869         default:
870             break;
871     }
872 #endif
873     p_buffer_pos = strstr( p_buffer_pos, "http://" );
874     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
875         goto proto;
876
877     /* We need to read the submission url */
878     p_buffer_pos += 7; /* we skip "http://" */
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_submit_host,
884                 &p_sys->psz_submit_file, &p_sys->i_submit_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
895     return VLC_SUCCESS;
896
897 oom:
898     return VLC_ENOMEM;
899
900 proto:
901     msg_Err( p_intf, "Handshake: can't recognize server protocol" );
902     return VLC_EGENERIC;
903 }
904
905 /*****************************************************************************
906  * DeleteSong : Delete the char pointers in a song
907  *****************************************************************************/
908 static void DeleteSong( audioscrobbler_song_t* p_song )
909 {
910     FREENULL( p_song->psz_a );
911     FREENULL( p_song->psz_b );
912     FREENULL( p_song->psz_t );
913     FREENULL( p_song->psz_m );
914     FREENULL( p_song->psz_n );
915 }
916
917 /*****************************************************************************
918  * ReadMetaData : Read meta data when parsed by vlc
919  *****************************************************************************/
920 static int ReadMetaData( intf_thread_t *p_this )
921 {
922     playlist_t          *p_playlist;
923     input_thread_t      *p_input;
924     input_item_t        *p_item;
925
926     intf_sys_t          *p_sys = p_this->p_sys;
927
928     p_playlist = pl_Yield( p_this );
929     PL_LOCK;
930     p_input = p_playlist->p_input;
931     if( !p_input )
932     {
933         PL_UNLOCK;
934         pl_Release( p_this );
935         return( VLC_SUCCESS );
936     }
937
938     vlc_object_yield( p_input );
939     PL_UNLOCK;
940     pl_Release( p_this );
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             free( psz_meta ); \
955             return VLC_ENOMEM; \
956         } \
957     }
958
959     vlc_mutex_lock( &p_sys->lock );
960
961     p_sys->b_meta_read = true;
962
963     ALLOC_ITEM_META( p_sys->p_current_song.psz_a, Artist )
964     else
965     {
966         vlc_mutex_unlock( &p_sys->lock );
967         msg_Dbg( p_this, "No artist.." );
968         vlc_object_release( p_input );
969         free( psz_meta );
970         return VLC_EGENERIC;
971     }
972     free( psz_meta );
973
974     ALLOC_ITEM_META( p_sys->p_current_song.psz_t, Title )
975     else
976     {
977         vlc_mutex_unlock( &p_sys->lock );
978         msg_Dbg( p_this, "No track name.." );
979         vlc_object_release( p_input );
980         free( p_sys->p_current_song.psz_a );
981         free( psz_meta );
982         return VLC_EGENERIC;
983     }
984     free( psz_meta );
985
986     /* Now we have read the mandatory meta data, so we can submit that info */
987     p_sys->b_submit = true;
988
989     ALLOC_ITEM_META( p_sys->p_current_song.psz_b, Album )
990     else
991         p_sys->p_current_song.psz_b = calloc( 1, 1 );
992     free( psz_meta );
993
994     ALLOC_ITEM_META( p_sys->p_current_song.psz_m, TrackID )
995     else
996         p_sys->p_current_song.psz_m = calloc( 1, 1 );
997     free( psz_meta );
998
999     p_sys->p_current_song.i_l = input_item_GetDuration( p_item ) / 1000000;
1000
1001     ALLOC_ITEM_META( p_sys->p_current_song.psz_n, TrackNum )
1002     else
1003         p_sys->p_current_song.psz_n = calloc( 1, 1 );
1004     free( psz_meta );
1005 #undef ALLOC_ITEM_META
1006
1007     msg_Dbg( p_this, "Meta data registered" );
1008
1009     vlc_mutex_unlock( &p_sys->lock );
1010     vlc_object_release( p_input );
1011     return VLC_SUCCESS;
1012
1013 }
1014
1015 static void HandleInterval( mtime_t *next, unsigned int *i_interval )
1016 {
1017     if( *i_interval == 0 )
1018     {
1019         /* first interval is 1 minute */
1020         *i_interval = 1;
1021     }
1022     else
1023     {
1024         /* else we double the previous interval, up to 120 minutes */
1025         *i_interval <<= 1;
1026         if( *i_interval > 120 )
1027             *i_interval = 120;
1028     }
1029     *next = mdate() + ( *i_interval * 1000000 * 60 );
1030 }
1031