]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
Cleanup condition handling, should fix #1448
[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 #include <vlc/vlc.h>
38 #include <vlc_interface.h>
39 #include <vlc_meta.h>
40 #include <vlc_md5.h>
41 #include <vlc_block.h>
42 #include <vlc_stream.h>
43 #include <vlc_url.h>
44 #include <vlc_network.h>
45 #include <vlc_interface.h>
46 #include <vlc_playlist.h>
47
48 /*****************************************************************************
49  * Local prototypes
50  *****************************************************************************/
51
52 #define QUEUE_MAX 50
53
54 /* Keeps track of metadata to be submitted */
55 typedef struct audioscrobbler_song_t
56 {
57     char        *psz_a;             /**< track artist     */
58     char        *psz_t;             /**< track title      */
59     char        *psz_b;             /**< track album      */
60     char        *psz_n;             /**< track number     */
61     int         i_l;                /**< track length     */
62     char        *psz_m;             /**< musicbrainz id   */
63     time_t      date;               /**< date since epoch */
64 } audioscrobbler_song_t;
65
66 struct intf_sys_t
67 {
68     audioscrobbler_song_t   p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
69     int                     i_songs;            /**< number of songs        */
70
71     vlc_mutex_t             lock;               /**< p_sys mutex            */
72
73     /* data about audioscrobbler session */
74     mtime_t                 next_exchange;      /**< when can we send data  */
75     unsigned int            i_interval;         /**< waiting interval (secs)*/
76
77     /* submission of played songs */
78     char                    *psz_submit_host;   /**< where to submit data   */
79     int                     i_submit_port;      /**< port to which submit   */
80     char                    *psz_submit_file;   /**< file to which submit   */
81
82     /* submission of playing song */
83 #if 0 //NOT USED
84     char                    *psz_nowp_host;     /**< where to submit data   */
85     int                     i_nowp_port;        /**< port to which submit   */
86     char                    *psz_nowp_file;     /**< file to which submit   */
87 #endif
88     vlc_bool_t              b_handshaked;       /**< are we authenticated ? */
89     char                    psz_auth_token[33]; /**< Authentication token */
90
91     /* data about song currently playing */
92     audioscrobbler_song_t   p_current_song;     /**< song being played      */
93
94     mtime_t                 time_pause;         /**< time when vlc paused   */
95     mtime_t                 time_total_pauses;  /**< total time in pause    */
96
97     vlc_bool_t              b_submit;           /**< do we have to submit ? */
98
99     vlc_bool_t              b_state_cb;         /**< if we registered the
100                                                  * "state" callback         */
101
102     vlc_bool_t              b_meta_read;        /**< if we read the song's
103                                                  * metadata already         */
104 };
105
106 static int  Open            ( vlc_object_t * );
107 static void Close           ( vlc_object_t * );
108 static void Unload          ( intf_thread_t * );
109 static void Run             ( intf_thread_t * );
110
111 static int ItemChange       ( vlc_object_t *, const char *, vlc_value_t,
112                                 vlc_value_t, void * );
113 static int PlayingChange    ( vlc_object_t *, const char *, vlc_value_t,
114                                 vlc_value_t, void * );
115
116 static void AddToQueue      ( intf_thread_t * );
117 static int Handshake        ( intf_thread_t * );
118 static int ReadMetaData     ( intf_thread_t * );
119 static void DeleteSong      ( audioscrobbler_song_t* );
120 static int ParseURL         ( char *, char **, char **, int * );
121 static void HandleInterval  ( mtime_t *, unsigned int * );
122
123 /*****************************************************************************
124  * Module descriptor
125  ****************************************************************************/
126
127 #define USERNAME_TEXT       N_("Username")
128 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
129 #define PASSWORD_TEXT       N_("Password")
130 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
131
132 /* This error value is used when last.fm plugin has to be unloaded. */
133 #define VLC_AUDIOSCROBBLER_EFATAL -69
134
135 /* last.fm client identifier */
136 #define CLIENT_NAME     PACKAGE
137 #define CLIENT_VERSION  VERSION
138
139 /* HTTP POST request : to submit data */
140 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
141                         "Accept-Encoding: identity\n"                       \
142                         "Content-length: %u\n"                              \
143                         "Connection: close\n"                               \
144                         "Content-type: application/x-www-form-urlencoded\n" \
145                         "Host: %s\n"                                        \
146                         "User-agent: VLC Media Player/%s\r\n"               \
147                         "\r\n"                                              \
148                         "%s\r\n"                                            \
149                         "\r\n"
150
151 vlc_module_begin();
152     set_category( CAT_INTERFACE );
153     set_subcategory( SUBCAT_INTERFACE_CONTROL );
154     set_shortname( N_( "Audioscrobbler" ) );
155     set_description( N_("Submission of played songs to last.fm") );
156     add_string( "lastfm-username", "", NULL,
157                 USERNAME_TEXT, USERNAME_LONGTEXT, VLC_FALSE );
158     add_password( "lastfm-password", "", NULL,
159                 PASSWORD_TEXT, PASSWORD_LONGTEXT, VLC_FALSE );
160     set_capability( "interface", 0 );
161     set_callbacks( Open, Close );
162 vlc_module_end();
163
164 /*****************************************************************************
165  * Open: initialize and create stuff
166  *****************************************************************************/
167 static int Open( vlc_object_t *p_this )
168 {
169     playlist_t      *p_playlist;
170     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
171     intf_sys_t      *p_sys      = calloc( 1, sizeof( intf_sys_t ) );
172
173     if( !p_sys )
174         return VLC_ENOMEM;
175
176     p_intf->p_sys = p_sys;
177
178     vlc_mutex_init( p_this, &p_sys->lock );
179
180     p_playlist = pl_Yield( p_intf );
181     PL_LOCK;
182     var_AddCallback( p_playlist, "playlist-current", ItemChange, p_intf );
183     PL_UNLOCK;
184     pl_Release( p_playlist );
185
186     p_intf->pf_run = Run;
187
188     return VLC_SUCCESS;
189 }
190
191 /*****************************************************************************
192  * Close: destroy interface stuff
193  *****************************************************************************/
194 static void Close( vlc_object_t *p_this )
195 {
196     playlist_t                  *p_playlist;
197     input_thread_t              *p_input;
198     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
199     intf_sys_t                  *p_sys  = p_intf->p_sys;
200
201     p_playlist = pl_Yield( p_intf );
202     PL_LOCK;
203
204     var_DelCallback( p_playlist, "playlist-current", ItemChange, p_intf );
205
206     p_input = p_playlist->p_input;
207     if ( p_input )
208     {
209         vlc_object_yield( p_input );
210
211         if( p_sys->b_state_cb )
212             var_DelCallback( p_input, "state", PlayingChange, p_intf );
213
214         vlc_object_release( p_input );
215     }
216
217     PL_UNLOCK;
218     pl_Release( p_playlist );
219
220     p_intf->b_dead = VLC_TRUE;
221     /* we lock the mutex in case p_sys is being accessed from a callback */
222     vlc_mutex_lock ( &p_sys->lock );
223     int i;
224     for( i = 0; i < p_sys->i_songs; i++ )
225         DeleteSong( &p_sys->p_queue[i] );
226     free( p_sys->psz_submit_host );
227     free( p_sys->psz_submit_file );
228 #if 0 //NOT USED
229     free( p_sys->psz_nowp_host );
230     free( p_sys->psz_nowp_file );
231 #endif
232     vlc_mutex_unlock ( &p_sys->lock );
233     vlc_mutex_destroy( &p_sys->lock );
234     free( p_sys );
235 }
236
237
238 /*****************************************************************************
239  * Unload: Unloads the audioscrobbler when encountering fatal errors
240  *****************************************************************************/
241 static void Unload( intf_thread_t *p_this )
242 {
243     vlc_object_kill( p_this );
244     vlc_object_detach( p_this );
245     if( p_this->p_module )
246         module_Unneed( p_this, p_this->p_module );
247     vlc_mutex_destroy( &p_this->change_lock );
248     vlc_object_destroy( p_this );
249 }
250
251 /*****************************************************************************
252  * Run : call Handshake() then submit songs
253  *****************************************************************************/
254 static void Run( intf_thread_t *p_intf )
255 {
256     char                    *psz_submit, *psz_submit_song, *psz_submit_tmp;
257     int                     i_net_ret;
258     int                     i_song;
259     uint8_t                 p_buffer[1024];
260     char                    *p_buffer_pos;
261     int                     i_post_socket;
262
263     intf_sys_t *p_sys = p_intf->p_sys;
264
265     /* main loop */
266     for( ;; )
267     {
268         vlc_bool_t b_die = VLC_FALSE, b_wait = VLC_FALSE;
269
270         vlc_object_lock( p_intf );
271         if( vlc_object_alive( p_intf ) )
272         {
273            if( mdate() < p_sys->next_exchange )
274                 /* wait until we can resubmit, i.e.  */
275                 b_wait = !vlc_object_timedwait( p_intf,
276                                                 p_sys->next_exchange );
277             else
278                 /* wait for data to submit */
279                 /* we are signaled each time there is a song to submit */
280                vlc_object_wait( p_intf );
281         }
282         b_die = !vlc_object_alive( p_intf );
283         vlc_object_unlock( p_intf );
284
285         if( b_die )
286         {
287             msg_Dbg( p_intf, "audioscrobbler is dying");
288             return;
289         }
290         if( b_wait )
291             continue; /* holding on until next_exchange */
292
293         /* handshake if needed */
294         if( p_sys->b_handshaked == VLC_FALSE )
295         {
296             msg_Dbg( p_intf, "Handshaking with last.fm ..." );
297
298             switch( Handshake( p_intf ) )
299             {
300                 case VLC_ENOMEM:
301                     Unload( p_intf );
302                     return;
303
304                 case VLC_ENOVAR:
305                     /* username not set */
306                     intf_UserFatal( p_intf, VLC_FALSE,
307                         _("Last.fm username not set"),
308                         _("Please set a username or disable the "
309                         "audioscrobbler plugin, and restart VLC.\n"
310                         "Visit http://www.last.fm/join/ to get an account.")
311                     );
312                     Unload( p_intf );
313                     return;
314
315                 case VLC_SUCCESS:
316                     msg_Dbg( p_intf, "Handshake successfull :)" );
317                     p_sys->b_handshaked = VLC_TRUE;
318                     p_sys->i_interval = 0;
319                     p_sys->next_exchange = mdate();
320                     break;
321
322                 case VLC_AUDIOSCROBBLER_EFATAL:
323                     msg_Warn( p_intf, "Unloading..." );
324                     Unload( p_intf );
325                     return;
326
327                 case VLC_EGENERIC:
328                 default:
329                     /* protocol error : we'll try later */
330                     HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
331                     break;
332             }
333             /* if handshake failed let's restart the loop */
334             if( p_sys->b_handshaked == VLC_FALSE )
335                 continue;
336         }
337
338         msg_Dbg( p_intf, "Going to submit some data..." );
339
340         if( !asprintf( &psz_submit, "s=%s", p_sys->psz_auth_token ) )
341         {   /* Out of memory */
342             Unload( p_intf );
343             return;
344         }
345
346         /* forge the HTTP POST request */
347         vlc_mutex_lock( &p_sys->lock );
348         audioscrobbler_song_t *p_song;
349         for( i_song = 0 ; i_song < p_sys->i_songs ; i_song++ )
350         {
351             p_song = &p_sys->p_queue[i_song];
352             if( !asprintf( &psz_submit_song,
353                     "&a%%5B%d%%5D=%s&t%%5B%d%%5D=%s"
354                     "&i%%5B%d%%5D=%llu&o%%5B%d%%5D=P&r%%5B%d%%5D="
355                     "&l%%5B%d%%5D=%d&b%%5B%d%%5D=%s"
356                     "&n%%5B%d%%5D=%s&m%%5B%d%%5D=%s",
357                     i_song, p_song->psz_a,           i_song, p_song->psz_t,
358                     i_song, (uintmax_t)p_song->date, i_song, i_song,
359                     i_song, p_song->i_l,             i_song, p_song->psz_b,
360                     i_song, p_song->psz_n,           i_song, p_song->psz_m
361             ) )
362             {   /* Out of memory */
363                 vlc_mutex_unlock( &p_sys->lock );
364                 Unload( p_intf );
365                 return;
366             }
367             psz_submit_tmp = psz_submit;
368             if( !asprintf( &psz_submit, "%s%s",
369                     psz_submit_tmp, psz_submit_song ) )
370             {   /* Out of memory */
371                 free( psz_submit_tmp );
372                 free( psz_submit_song );
373                 vlc_mutex_unlock( &p_sys->lock );
374                 Unload( p_intf );
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 = VLC_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 = VLC_FALSE;
408             continue;
409         }
410
411         i_net_ret = net_Read( p_intf, i_post_socket, NULL,
412                     p_buffer, 1023, VLC_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 = VLC_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 = VLC_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 == VLC_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       = VLC_FALSE;
511     p_sys->b_meta_read      = VLC_FALSE;
512     p_sys->b_submit         = VLC_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_playlist );
522         return VLC_SUCCESS;
523     }
524
525     vlc_object_yield( p_input );
526     PL_UNLOCK;
527     pl_Release( p_playlist );
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 );
546
547     var_AddCallback( p_input, "state", PlayingChange, p_intf );
548     p_sys->b_state_cb = VLC_TRUE;
549
550     if( input_item_IsPreparsed( p_item ) )
551         ReadMetaData( p_intf );
552     /* if the input item was not preparsed, we'll do it in PlayingChange()
553      * callback, when "state" == PLAYING_S */
554
555     vlc_object_release( p_input );
556     return VLC_SUCCESS;
557 }
558
559 /*****************************************************************************
560  * AddToQueue: Add the played song to the queue to be submitted
561  *****************************************************************************/
562 static void AddToQueue ( intf_thread_t *p_this )
563 {
564     mtime_t                     played_time;
565     intf_sys_t                  *p_sys = p_this->p_sys;
566
567     vlc_mutex_lock( &p_sys->lock );
568     if( !p_sys->b_submit )
569         goto end;
570
571     /* wait for the user to listen enough before submitting */
572     played_time = mdate();
573     played_time -= p_sys->p_current_song.date;
574     played_time -= p_sys->time_total_pauses;
575     played_time /= 1000000; /* µs → s */
576
577     if( ( played_time < 240 ) &&
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         msg_Dbg( p_this, "Song too short (< 30s), not submitting" );
587         goto end;
588     }
589
590     if( !p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
591         !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t )
592     {
593         msg_Dbg( p_this, "Missing artist or title, not submitting" );
594 /*XXX*/        msg_Dbg( p_this, "%s %s", p_sys->p_current_song.psz_a, p_sys->p_current_song.psz_t );
595         goto end;
596     }
597
598     if( p_sys->i_songs >= QUEUE_MAX )
599     {
600         msg_Warn( p_this, "Submission queue is full, not submitting" );
601         goto end;
602     }
603
604     msg_Dbg( p_this, "Song will be submitted." );
605
606 #define QUEUE_COPY( a ) \
607     p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
608
609 #define QUEUE_COPY_NULL( a ) \
610     QUEUE_COPY( a ); \
611     p_sys->p_current_song.a = NULL
612
613     QUEUE_COPY( i_l );
614     QUEUE_COPY_NULL( psz_n );
615     QUEUE_COPY_NULL( psz_a );
616     QUEUE_COPY_NULL( psz_t );
617     QUEUE_COPY_NULL( psz_b );
618     QUEUE_COPY_NULL( psz_m );
619     QUEUE_COPY( date );
620 #undef QUEUE_COPY_NULL
621 #undef QUEUE_COPY
622
623     p_sys->i_songs++;
624
625     /* signal the main loop we have something to submit */
626     vlc_object_signal( VLC_OBJECT( p_this ) );
627
628 end:
629     DeleteSong( &p_sys->p_current_song );
630     p_sys->b_submit = VLC_FALSE;
631     vlc_mutex_unlock( &p_sys->lock );
632 }
633
634 /*****************************************************************************
635  * ParseURL : Split an http:// URL into host, file, and port
636  *
637  * Example: "62.216.251.205:80/protocol_1.2"
638  *      will be split into "62.216.251.205", 80, "protocol_1.2"
639  *
640  * psz_url will be freed before returning
641  * *psz_file & *psz_host will be freed before use
642  *
643  * Return value:
644  *  VLC_ENOMEM      Out Of Memory
645  *  VLC_EGENERIC    Invalid url provided
646  *  VLC_SUCCESS     Success
647  *****************************************************************************/
648 static int ParseURL( char *psz_url, char **psz_host, char **psz_file,
649                         int *i_port )
650 {
651     int i_pos;
652     int i_len = strlen( psz_url );
653     FREENULL( *psz_host );
654     FREENULL( *psz_file );
655
656     i_pos = strcspn( psz_url, ":" );
657     if( i_pos == i_len )
658         return VLC_EGENERIC;
659
660     *psz_host = strndup( psz_url, i_pos );
661     if( !*psz_host )
662         return VLC_ENOMEM;
663
664     i_pos++; /* skip the ':' */
665     *i_port = atoi( psz_url + i_pos );
666     if( *i_port <= 0 )
667     {
668         FREENULL( *psz_host );
669         return VLC_EGENERIC;
670     }
671
672     i_pos = strcspn( psz_url, "/" );
673
674     if( i_pos == i_len )
675         return VLC_EGENERIC;
676
677     i_pos++; /* skip the '/' */
678     *psz_file = strdup( psz_url + i_pos );
679     if( !*psz_file )
680     {
681         FREENULL( *psz_host );
682         return VLC_ENOMEM;
683     }
684
685     free( psz_url );
686     return VLC_SUCCESS;
687 }
688
689 /*****************************************************************************
690  * Handshake : Init audioscrobbler connection
691  *****************************************************************************/
692 static int Handshake( intf_thread_t *p_this )
693 {
694     char                *psz_username, *psz_password;
695     time_t              timestamp;
696     char                psz_timestamp[33];
697
698     struct md5_s        p_struct_md5;
699
700     stream_t            *p_stream;
701     char                *psz_handshake_url;
702     uint8_t             p_buffer[1024];
703     char                *p_buffer_pos;
704
705     int                 i_ret;
706     char                *psz_url;
707
708     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
709     intf_sys_t          *p_sys                  = p_this->p_sys;
710
711     psz_username = config_GetPsz( p_this, "lastfm-username" );
712     if( !psz_username )
713         return VLC_ENOMEM;
714
715     psz_password = config_GetPsz( p_this, "lastfm-password" );
716     if( !psz_password )
717     {
718         free( psz_username );
719         return VLC_ENOMEM;
720     }
721
722     /* username or password have not been setup */
723     if ( !*psz_username || !*psz_password )
724     {
725         free( psz_username );
726         free( psz_password );
727         return VLC_ENOVAR;
728     }
729
730     time( &timestamp );
731
732     /* generates a md5 hash of the password */
733     InitMD5( &p_struct_md5 );
734     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
735     EndMD5( &p_struct_md5 );
736
737     free( psz_password );
738
739     char *psz_password_md5 = psz_md5_hash( &p_struct_md5 );
740     if( !psz_password_md5 )
741     {
742         free( psz_username );
743         return VLC_ENOMEM;
744     }
745
746     snprintf( psz_timestamp, 33, "%llu", (uintmax_t)timestamp );
747
748     /* generates a md5 hash of :
749      * - md5 hash of the password, plus
750      * - timestamp in clear text
751      */
752     InitMD5( &p_struct_md5 );
753     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
754     AddMD5( &p_struct_md5, ( uint8_t* ) psz_timestamp, strlen( psz_timestamp ));
755     EndMD5( &p_struct_md5 );
756     free( psz_password_md5 );
757
758     char *psz_auth_token = psz_md5_hash( &p_struct_md5 );
759     if( !psz_auth_token )
760     {
761         free( psz_username );
762         return VLC_ENOMEM;
763     }
764     strncpy( p_sys->psz_auth_token, psz_auth_token, 33 );
765     free( psz_auth_token );
766
767     if( !asprintf( &psz_handshake_url,
768     "http://post.audioscrobbler.com/?hs=true&p=1.2&c=%s&v=%s&u=%s&t=%s&a=%s",
769         CLIENT_NAME, CLIENT_VERSION, psz_username, psz_timestamp,
770         p_sys->psz_auth_token ) )
771     {
772         free( psz_username );
773         return VLC_ENOMEM;
774     }
775     free( psz_username );
776
777     /* send the http handshake request */
778     p_stream = stream_UrlNew( p_intf, psz_handshake_url );
779     free( psz_handshake_url );
780
781     if( !p_stream )
782         return VLC_EGENERIC;
783
784     /* read answer */
785     i_ret = stream_Read( p_stream, p_buffer, 1023 );
786     if( i_ret == 0 )
787     {
788         stream_Delete( p_stream );
789         return VLC_EGENERIC;
790     }
791     p_buffer[i_ret] = '\0';
792     stream_Delete( p_stream );
793
794     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED " );
795     if ( p_buffer_pos )
796     {
797         /* handshake request failed, sorry */
798         msg_Err( p_this, "last.fm handshake failed: %s", p_buffer_pos + 7 );
799         return VLC_EGENERIC;
800     }
801
802     p_buffer_pos = strstr( ( char* ) p_buffer, "BADAUTH" );
803     if ( p_buffer_pos )
804     {
805         /* authentication failed, bad username/password combination */
806         intf_UserFatal( p_this, VLC_FALSE,
807             _("last.fm: Authentication failed"),
808             _("last.fm username or password is incorrect. "
809               "Please verify your settings and relaunch VLC." ) );
810         return VLC_AUDIOSCROBBLER_EFATAL;
811     }
812
813     p_buffer_pos = strstr( ( char* ) p_buffer, "BANNED" );
814     if ( p_buffer_pos )
815     {
816         /* oops, our version of vlc has been banned by last.fm servers */
817         msg_Err( p_intf, "This version of VLC has been banned by last.fm. "
818                          "You should upgrade VLC, or disable the last.fm plugin." );
819         return VLC_AUDIOSCROBBLER_EFATAL;
820     }
821
822     p_buffer_pos = strstr( ( char* ) p_buffer, "BADTIME" );
823     if ( p_buffer_pos )
824     {
825         /* The system clock isn't good */
826         msg_Err( p_intf, "last.fm handshake failed because your clock is too "
827                          "much shifted. Please correct it, and relaunch VLC." );
828         return VLC_AUDIOSCROBBLER_EFATAL;
829     }
830
831     p_buffer_pos = strstr( ( char* ) p_buffer, "OK" );
832     if ( !p_buffer_pos )
833         goto proto;
834
835     p_buffer_pos = strstr( p_buffer_pos, "\n" );
836     if( !p_buffer_pos || strlen( p_buffer_pos ) < 34 )
837         goto proto;
838     p_buffer_pos++; /* we skip the '\n' */
839
840     /* save the session ID */
841     snprintf( p_sys->psz_auth_token, 33, "%s", p_buffer_pos );
842
843     p_buffer_pos = strstr( p_buffer_pos, "http://" );
844     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
845         goto proto;
846
847     /* We need to read the nowplaying url */
848     p_buffer_pos += 7; /* we skip "http://" */
849 #if 0 //NOT USED
850     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
851     if( !psz_url )
852         goto oom;
853
854     switch( ParseURL( psz_url, &p_sys->psz_nowp_host,
855                 &p_sys->psz_nowp_file, &p_sys->i_nowp_port ) )
856     {
857         case VLC_ENOMEM:
858             goto oom;
859         case VLC_EGENERIC:
860             goto proto;
861         case VLC_SUCCESS:
862         default:
863             break;
864     }
865 #endif
866     p_buffer_pos = strstr( p_buffer_pos, "http://" );
867     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
868         goto proto;
869
870     /* We need to read the submission url */
871     p_buffer_pos += 7; /* we skip "http://" */
872     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
873     if( !psz_url )
874         goto oom;
875
876     switch( ParseURL( psz_url, &p_sys->psz_submit_host,
877                 &p_sys->psz_submit_file, &p_sys->i_submit_port ) )
878     {
879         case VLC_ENOMEM:
880             goto oom;
881         case VLC_EGENERIC:
882             goto proto;
883         case VLC_SUCCESS:
884         default:
885             break;
886     }
887
888     return VLC_SUCCESS;
889
890 oom:
891     return VLC_ENOMEM;
892
893 proto:
894     msg_Err( p_intf, "Handshake: can't recognize server protocol" );
895     return VLC_EGENERIC;
896 }
897
898 /*****************************************************************************
899  * DeleteSong : Delete the char pointers in a song
900  *****************************************************************************/
901 static void DeleteSong( audioscrobbler_song_t* p_song )
902 {
903     FREENULL( p_song->psz_a );
904     FREENULL( p_song->psz_b );
905     FREENULL( p_song->psz_t );
906     FREENULL( p_song->psz_m );
907     FREENULL( p_song->psz_n );
908 }
909
910 /*****************************************************************************
911  * ReadMetaData : Read meta data when parsed by vlc
912  *****************************************************************************/
913 static int ReadMetaData( intf_thread_t *p_this )
914 {
915     playlist_t          *p_playlist;
916     input_thread_t      *p_input;
917     input_item_t        *p_item;
918
919     intf_sys_t          *p_sys = p_this->p_sys;
920
921     p_playlist = pl_Yield( p_this );
922     PL_LOCK;
923     p_input = p_playlist->p_input;
924     if( !p_input )
925     {
926         PL_UNLOCK;
927         pl_Release( p_playlist );
928         return( VLC_SUCCESS );
929     }
930
931     vlc_object_yield( p_input );
932     PL_UNLOCK;
933     pl_Release( p_playlist );
934
935     p_item = input_GetItem( p_input );
936     if( !p_item )
937         return VLC_SUCCESS;
938
939     char *psz_meta;
940 #define ALLOC_ITEM_META( a, b ) \
941     psz_meta = input_item_Get##b( p_item ); \
942     if( psz_meta && *psz_meta ) \
943     { \
944         a = encode_URI_component( psz_meta ); \
945         if( !a ) \
946         { \
947             free( psz_meta ); \
948             return VLC_ENOMEM; \
949         } \
950         free( psz_meta ); \
951     }
952
953     vlc_mutex_lock( &p_sys->lock );
954
955     p_sys->b_meta_read = VLC_TRUE;
956
957     ALLOC_ITEM_META( p_sys->p_current_song.psz_a, Artist )
958     else
959     {
960         vlc_mutex_unlock( &p_sys->lock );
961         msg_Dbg( p_this, "No artist.." );
962         vlc_object_release( p_input );
963         free( psz_meta );
964         return VLC_EGENERIC;
965     }
966
967     ALLOC_ITEM_META( p_sys->p_current_song.psz_t, Title )
968     else
969     {
970         vlc_mutex_unlock( &p_sys->lock );
971         msg_Dbg( p_this, "No track name.." );
972         vlc_object_release( p_input );
973         free( p_sys->p_current_song.psz_a );
974         free( psz_meta );
975         return VLC_EGENERIC;
976     }
977
978     /* Now we have read the mandatory meta data, so we can submit that info */
979     p_sys->b_submit = VLC_TRUE;
980
981     ALLOC_ITEM_META( p_sys->p_current_song.psz_b, Album )
982     else
983         p_sys->p_current_song.psz_b = calloc( 1, 1 );
984
985     ALLOC_ITEM_META( p_sys->p_current_song.psz_m, TrackID )
986     else
987         p_sys->p_current_song.psz_m = calloc( 1, 1 );
988
989     p_sys->p_current_song.i_l = input_item_GetDuration( p_item ) / 1000000;
990
991     ALLOC_ITEM_META( p_sys->p_current_song.psz_n, TrackNum )
992     else
993         p_sys->p_current_song.psz_n = calloc( 1, 1 );
994 #undef ALLOC_ITEM_META
995
996     msg_Dbg( p_this, "Meta data registered" );
997
998     vlc_mutex_unlock( &p_sys->lock );
999     vlc_object_release( p_input );
1000     return VLC_SUCCESS;
1001
1002 }
1003
1004 static void HandleInterval( mtime_t *next, unsigned int *i_interval )
1005 {
1006     if( *i_interval == 0 )
1007     {
1008         /* first interval is 1 minute */
1009         *i_interval = 1;
1010     }
1011     else
1012     {
1013         /* else we double the previous interval, up to 120 minutes */
1014         *i_interval <<= 1;
1015         if( *i_interval > 120 )
1016             *i_interval = 120;
1017     }
1018     *next = mdate() + ( *i_interval * 1000000 * 60 );
1019 }
1020