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