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