]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
Audioscrobbler: prepare to submit to libre.fm
[vlc] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright © 2006-2009 the VideoLAN team
5  * $Id$
6  *
7  * Author: Rafaël Carré <funman at videolanorg>
8  *         Ilkka Ollakka <ileoo at videolan org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /* audioscrobbler protocol version: 1.2
26  * http://www.audioscrobbler.net/development/protocol/
27  *
28  * TODO:    "Now Playing" feature (not mandatory)
29  */
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33
34 #if defined( WIN32 ) 
35 #include <time.h> 
36 #endif 
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_interface.h>
45 #include <vlc_dialog.h>
46 #include <vlc_meta.h>
47 #include <vlc_md5.h>
48 #include <vlc_stream.h>
49 #include <vlc_url.h>
50 #include <vlc_network.h>
51 #include <vlc_playlist.h>
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56
57 #define QUEUE_MAX 50
58
59 /* Keeps track of metadata to be submitted */
60 typedef struct audioscrobbler_song_t
61 {
62     char        *psz_a;             /**< track artist     */
63     char        *psz_t;             /**< track title      */
64     char        *psz_b;             /**< track album      */
65     char        *psz_n;             /**< track number     */
66     int         i_l;                /**< track length     */
67     char        *psz_m;             /**< musicbrainz id   */
68     time_t      date;               /**< date since epoch */
69     mtime_t     i_start;            /**< playing start    */
70 } audioscrobbler_song_t;
71
72 struct intf_sys_t
73 {
74     audioscrobbler_song_t   p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
75     int                     i_songs;            /**< number of songs        */
76
77     vlc_mutex_t             lock;               /**< p_sys mutex            */
78     vlc_cond_t              wait;               /**< song to submit event   */
79
80     /* data about audioscrobbler session */
81     mtime_t                 next_exchange;      /**< when can we send data  */
82     unsigned int            i_interval;         /**< waiting interval (secs)*/
83
84     /* submission of played songs */
85     char                    *psz_submit_host;   /**< where to submit data   */
86     int                     i_submit_port;      /**< port to which submit   */
87     char                    *psz_submit_file;   /**< file to which submit   */
88
89     /* submission of playing song */
90 #if 0 //NOT USED
91     char                    *psz_nowp_host;     /**< where to submit data   */
92     int                     i_nowp_port;        /**< port to which submit   */
93     char                    *psz_nowp_file;     /**< file to which submit   */
94 #endif
95     bool                    b_handshaked;       /**< are we authenticated ? */
96     char                    psz_auth_token[33]; /**< Authentication token */
97
98     /* data about song currently playing */
99     audioscrobbler_song_t   p_current_song;     /**< song being played      */
100
101     mtime_t                 time_pause;         /**< time when vlc paused   */
102     mtime_t                 time_total_pauses;  /**< total time in pause    */
103
104     bool                    b_submit;           /**< do we have to submit ? */
105
106     bool                    b_state_cb;         /**< if we registered the
107                                                  * "state" callback         */
108
109     bool                    b_meta_read;        /**< if we read the song's
110                                                  * metadata already         */
111 };
112
113 static int  Open            ( vlc_object_t * );
114 static void Close           ( vlc_object_t * );
115 static void Run             ( intf_thread_t * );
116
117 static int ItemChange       ( vlc_object_t *, const char *, vlc_value_t,
118                                 vlc_value_t, void * );
119 static int PlayingChange    ( vlc_object_t *, const char *, vlc_value_t,
120                                 vlc_value_t, void * );
121
122 static void AddToQueue      ( intf_thread_t * );
123 static int Handshake        ( intf_thread_t * );
124 static int ReadMetaData     ( intf_thread_t * );
125 static void DeleteSong      ( audioscrobbler_song_t* );
126 static int ParseURL         ( char *, char **, char **, int * );
127 static void HandleInterval  ( mtime_t *, unsigned int * );
128
129 /*****************************************************************************
130  * Module descriptor
131  ****************************************************************************/
132
133 #define USERNAME_TEXT       N_("Username")
134 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
135 #define PASSWORD_TEXT       N_("Password")
136 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
137 #if 0
138     #define URL_TEXT       N_("Scrobbler URL")
139     #define URL_LONGTEXT   N_("The URL set for an alternative scrobbler engine")
140 #endif
141
142 /* This error value is used when last.fm plugin has to be unloaded. */
143 #define VLC_AUDIOSCROBBLER_EFATAL -69
144
145 /* last.fm client identifier */
146 #define CLIENT_NAME     PACKAGE
147 #define CLIENT_VERSION  VERSION
148
149 /* HTTP POST request : to submit data */
150 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
151                         "Accept-Encoding: identity\n"                       \
152                         "Content-length: %u\n"                              \
153                         "Connection: close\n"                               \
154                         "Content-type: application/x-www-form-urlencoded\n" \
155                         "Host: %s\n"                                        \
156                         "User-agent: VLC media player/%s\r\n"               \
157                         "\r\n"                                              \
158                         "%s\r\n"                                            \
159                         "\r\n"
160
161 vlc_module_begin ()
162     set_category( CAT_INTERFACE )
163     set_subcategory( SUBCAT_INTERFACE_CONTROL )
164     set_shortname( N_( "Audioscrobbler" ) )
165     set_description( N_("Submission of played songs to last.fm") )
166     add_string( "lastfm-username", "", NULL,
167                 USERNAME_TEXT, USERNAME_LONGTEXT, false )
168     add_password( "lastfm-password", "", NULL,
169                 PASSWORD_TEXT, PASSWORD_LONGTEXT, false )
170 #if 0
171     add_string( "scrobbler-url", "post.audioscrobbler.com", NULL,
172                 URL_TEXT, URL_LONGTEXT, false )*/
173 #endif
174     set_capability( "interface", 0 )
175     set_callbacks( Open, Close )
176 vlc_module_end ()
177
178 /*****************************************************************************
179  * Open: initialize and create stuff
180  *****************************************************************************/
181 static int Open( vlc_object_t *p_this )
182 {
183     playlist_t      *p_playlist;
184     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
185     intf_sys_t      *p_sys      = calloc( 1, sizeof( intf_sys_t ) );
186
187     if( !p_sys )
188         return VLC_ENOMEM;
189
190     p_intf->p_sys = p_sys;
191
192     vlc_mutex_init( &p_sys->lock );
193     vlc_cond_init( &p_sys->wait );
194
195     p_playlist = pl_Hold( p_intf );
196     PL_LOCK;
197     var_AddCallback( p_playlist, "item-current", ItemChange, p_intf );
198     PL_UNLOCK;
199     pl_Release( p_intf );
200
201     p_intf->pf_run = Run;
202
203     return VLC_SUCCESS;
204 }
205
206 /*****************************************************************************
207  * Close: destroy interface stuff
208  *****************************************************************************/
209 static void Close( vlc_object_t *p_this )
210 {
211     playlist_t                  *p_playlist;
212     input_thread_t              *p_input;
213     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
214     intf_sys_t                  *p_sys  = p_intf->p_sys;
215
216     p_playlist = pl_Hold( p_intf );
217     if( p_playlist )
218     {
219
220         var_DelCallback( p_playlist, "item-current", ItemChange, p_intf );
221
222         p_input = playlist_CurrentInput( p_playlist );
223         if ( p_input )
224         {
225             if( p_sys->b_state_cb )
226                 var_DelCallback( p_input, "intf-event", PlayingChange, p_intf );
227
228             vlc_object_release( p_input );
229         }
230
231         pl_Release( p_intf );
232     }
233
234     int i;
235     for( i = 0; i < p_sys->i_songs; i++ )
236         DeleteSong( &p_sys->p_queue[i] );
237     free( p_sys->psz_submit_host );
238     free( p_sys->psz_submit_file );
239 #if 0 //NOT USED
240     free( p_sys->psz_nowp_host );
241     free( p_sys->psz_nowp_file );
242 #endif
243     vlc_cond_destroy( &p_sys->wait );
244     vlc_mutex_destroy( &p_sys->lock );
245     free( p_sys );
246 }
247
248
249 /*****************************************************************************
250  * Run : call Handshake() then submit songs
251  *****************************************************************************/
252 static void Run( intf_thread_t *p_intf )
253 {
254     char                    *psz_submit, *psz_submit_song, *psz_submit_tmp;
255     int                     i_net_ret;
256     int                     i_song;
257     uint8_t                 p_buffer[1024];
258     char                    *p_buffer_pos;
259     int                     i_post_socket;
260     int                     canc = vlc_savecancel();
261
262     intf_sys_t *p_sys = p_intf->p_sys;
263
264     /* main loop */
265     for( ;; )
266     {
267         bool b_wait = false;
268
269
270         vlc_restorecancel( canc );
271         vlc_mutex_lock( &p_sys->lock );
272         mutex_cleanup_push( &p_sys->lock );
273
274         if( mdate() < p_sys->next_exchange )
275             /* wait until we can resubmit, i.e.  */
276             b_wait = vlc_cond_timedwait( &p_sys->wait, &p_sys->lock,
277                                           p_sys->next_exchange ) == 0;
278         else
279             /* wait for data to submit */
280             /* we are signaled each time there is a song to submit */
281             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
282         vlc_cleanup_run();
283         canc = vlc_savecancel();
284
285         if( b_wait )
286             continue; /* holding on until next_exchange */
287
288         /* handshake if needed */
289         if( p_sys->b_handshaked == false )
290         {
291             msg_Dbg( p_intf, "Handshaking with last.fm ..." );
292
293             switch( Handshake( p_intf ) )
294             {
295                 case VLC_ENOMEM:
296                     return;
297
298                 case VLC_ENOVAR:
299                     /* username not set */
300                     dialog_Fatal( p_intf,
301                         _("Last.fm username not set"),
302                         _("Please set a username or disable the "
303                         "audioscrobbler plugin, and restart VLC.\n"
304                         "Visit http://www.last.fm/join/ to get an account.")
305                     );
306                     return;
307
308                 case VLC_SUCCESS:
309                     msg_Dbg( p_intf, "Handshake successfull :)" );
310                     p_sys->b_handshaked = true;
311                     p_sys->i_interval = 0;
312                     p_sys->next_exchange = mdate();
313                     break;
314
315                 case VLC_AUDIOSCROBBLER_EFATAL:
316                     msg_Warn( p_intf, "Exiting..." );
317                     return;
318
319                 case VLC_EGENERIC:
320                 default:
321                     /* protocol error : we'll try later */
322                     HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
323                     break;
324             }
325             /* if handshake failed let's restart the loop */
326             if( p_sys->b_handshaked == false )
327                 continue;
328         }
329
330         msg_Dbg( p_intf, "Going to submit some data..." );
331
332         /* The session may be invalid if there is a trailing \n */
333         char *psz_ln = strrchr( p_sys->psz_auth_token, '\n' );
334         if( psz_ln )
335             *psz_ln = '\0';
336
337         if( !asprintf( &psz_submit, "s=%s", p_sys->psz_auth_token ) )
338         {   /* Out of memory */
339             return;
340         }
341
342         /* forge the HTTP POST request */
343         vlc_mutex_lock( &p_sys->lock );
344         audioscrobbler_song_t *p_song;
345         for( i_song = 0 ; i_song < p_sys->i_songs ; i_song++ )
346         {
347             p_song = &p_sys->p_queue[i_song];
348             if( !asprintf( &psz_submit_song,
349                     "&a%%5B%d%%5D=%s"
350                     "&t%%5B%d%%5D=%s"
351                     "&i%%5B%d%%5D=%u"
352                     "&o%%5B%d%%5D=P"
353                     "&r%%5B%d%%5D="
354                     "&l%%5B%d%%5D=%d"
355                     "&b%%5B%d%%5D=%s"
356                     "&n%%5B%d%%5D=%s"
357                     "&m%%5B%d%%5D=%s",
358                     i_song, p_song->psz_a,
359                     i_song, p_song->psz_t,
360                     i_song, (unsigned)p_song->date, /* HACK: %ju (uintmax_t) unsupported on Windows */
361                     i_song,
362                     i_song,
363                     i_song, p_song->i_l,
364                     i_song, p_song->psz_b,
365                     i_song, p_song->psz_n,
366                     i_song, p_song->psz_m
367             ) )
368             {   /* Out of memory */
369                 vlc_mutex_unlock( &p_sys->lock );
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                 return;
380             }
381             free( psz_submit_song );
382             free( psz_submit_tmp );
383         }
384         vlc_mutex_unlock( &p_sys->lock );
385
386         i_post_socket = net_ConnectTCP( p_intf,
387             p_sys->psz_submit_host, p_sys->i_submit_port );
388
389         if ( i_post_socket == -1 )
390         {
391             /* If connection fails, we assume we must handshake again */
392             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
393             p_sys->b_handshaked = false;
394             free( psz_submit );
395             continue;
396         }
397
398         /* we transmit the data */
399         i_net_ret = net_Printf(
400             VLC_OBJECT( p_intf ), i_post_socket, NULL,
401             POST_REQUEST, p_sys->psz_submit_file,
402             (unsigned)strlen( psz_submit ), p_sys->psz_submit_host,
403             VERSION, psz_submit
404         );
405
406         free( psz_submit );
407         if ( i_net_ret == -1 )
408         {
409             /* If connection fails, we assume we must handshake again */
410             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
411             p_sys->b_handshaked = false;
412             continue;
413         }
414
415         i_net_ret = net_Read( p_intf, i_post_socket, NULL,
416                     p_buffer, 1023, false );
417         if ( i_net_ret <= 0 )
418         {
419             /* if we get no answer, something went wrong : try again */
420             continue;
421         }
422
423         net_Close( i_post_socket );
424         p_buffer[i_net_ret] = '\0';
425
426         p_buffer_pos = strstr( ( char * ) p_buffer, "FAILED" );
427         if ( p_buffer_pos )
428         {
429             msg_Warn( p_intf, "%s", p_buffer_pos );
430             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
431             continue;
432         }
433
434         p_buffer_pos = strstr( ( char * ) p_buffer, "BADSESSION" );
435         if ( p_buffer_pos )
436         {
437             msg_Err( p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?" );
438             p_sys->b_handshaked = false;
439             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
440             continue;
441         }
442
443         p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
444         if ( p_buffer_pos )
445         {
446             int i;
447             for( i = 0; i < p_sys->i_songs; i++ )
448                 DeleteSong( &p_sys->p_queue[i] );
449             p_sys->i_songs = 0;
450             p_sys->i_interval = 0;
451             p_sys->next_exchange = mdate();
452             msg_Dbg( p_intf, "Submission successful!" );
453         }
454         else
455         {
456             msg_Err( p_intf, "Authentication failed, handshaking again (%s)", 
457                              p_buffer );
458             p_sys->b_handshaked = false;
459             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
460             continue;
461         }
462     }
463     vlc_restorecancel( canc );
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     input_thread_t  *p_input = ( input_thread_t* )p_this;
475     vlc_value_t     state_value;
476
477     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
478
479     if( newval.i_int != INPUT_EVENT_STATE ) return VLC_SUCCESS;
480
481     state_value.i_int = 0;
482
483     var_Get( p_input, "state", &state_value );
484
485
486     if( p_sys->b_meta_read == false && state_value.i_int >= PLAYING_S )
487     {
488         ReadMetaData( p_intf );
489         return VLC_SUCCESS;
490     }
491
492
493     if( state_value.i_int >= END_S )
494         AddToQueue( p_intf );
495     else if( state_value.i_int == PAUSE_S )
496         p_sys->time_pause = mdate();
497     else if( p_sys->time_pause > 0 && state_value.i_int == PLAYING_S )
498         p_sys->time_total_pauses += ( mdate() - p_sys->time_pause );
499
500     return VLC_SUCCESS;
501 }
502
503 /*****************************************************************************
504  * ItemChange: Playlist item change callback
505  *****************************************************************************/
506 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
507                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
508 {
509     playlist_t          *p_playlist;
510     input_thread_t      *p_input;
511     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
512     intf_sys_t          *p_sys      = p_intf->p_sys;
513     input_item_t        *p_item;
514     vlc_value_t         video_val;
515
516     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
517     VLC_UNUSED( oldval ); VLC_UNUSED( newval );
518
519     p_sys->b_state_cb       = false;
520     p_sys->b_meta_read      = false;
521     p_sys->b_submit         = false;
522
523     p_playlist = pl_Hold( p_intf );
524     p_input = playlist_CurrentInput( p_playlist );
525
526     if( !p_input || p_input->b_dead )
527     {
528         pl_Release( p_intf );
529         return VLC_SUCCESS;
530     }
531
532     pl_Release( p_intf );
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, "intf-event", 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     /*HACK: it seam that the preparsing sometime fail,
583             so use the playing time as the song length */
584     if( p_sys->p_current_song.i_l == 0 )
585         p_sys->p_current_song.i_l = played_time;
586
587     /* Don't send song shorter than 30s */
588     if( p_sys->p_current_song.i_l < 30 )
589     {
590         msg_Dbg( p_this, "Song too short (< 30s), not submitting" );
591         goto end;
592     }
593
594     /* Send if the user had listen more than 240s OR half the track length */
595     if( ( played_time < 240 ) &&
596         ( played_time < ( p_sys->p_current_song.i_l / 2 ) ) )
597     {
598         msg_Dbg( p_this, "Song not listened long enough, not submitting" );
599         goto end;
600     }
601
602     /* Check that all meta are present */
603     if( !p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
604         !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t )
605     {
606         msg_Dbg( p_this, "Missing artist or title, not submitting" );
607         goto end;
608     }
609
610     if( p_sys->i_songs >= QUEUE_MAX )
611     {
612         msg_Warn( p_this, "Submission queue is full, not submitting" );
613         goto end;
614     }
615
616     msg_Dbg( p_this, "Song will be submitted." );
617
618 #define QUEUE_COPY( a ) \
619     p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
620
621 #define QUEUE_COPY_NULL( a ) \
622     QUEUE_COPY( a ); \
623     p_sys->p_current_song.a = NULL
624
625     QUEUE_COPY( i_l );
626     QUEUE_COPY_NULL( psz_n );
627     QUEUE_COPY_NULL( psz_a );
628     QUEUE_COPY_NULL( psz_t );
629     QUEUE_COPY_NULL( psz_b );
630     QUEUE_COPY_NULL( psz_m );
631     QUEUE_COPY( date );
632 #undef QUEUE_COPY_NULL
633 #undef QUEUE_COPY
634
635     p_sys->i_songs++;
636
637     /* signal the main loop we have something to submit */
638     vlc_cond_signal( &p_sys->wait );
639
640 end:
641     DeleteSong( &p_sys->p_current_song );
642     p_sys->b_submit = false;
643     vlc_mutex_unlock( &p_sys->lock );
644 }
645
646 /*****************************************************************************
647  * ParseURL : Split an http:// URL into host, file, and port
648  *
649  * Example: "62.216.251.205:80/protocol_1.2"
650  *      will be split into "62.216.251.205", 80, "protocol_1.2"
651  *
652  * psz_url will be freed before returning
653  * *psz_file & *psz_host will be freed before use
654  *
655  * Return value:
656  *  VLC_ENOMEM      Out Of Memory
657  *  VLC_EGENERIC    Invalid url provided
658  *  VLC_SUCCESS     Success
659  *****************************************************************************/
660 static int ParseURL( char *psz_url, char **psz_host, char **psz_file,
661                         int *i_port )
662 {
663     int i_pos;
664     int i_len = strlen( psz_url );
665     bool b_no_port = false;
666     FREENULL( *psz_host );
667     FREENULL( *psz_file );
668
669     i_pos = strcspn( psz_url, ":" );
670     if( i_pos == i_len )
671     {
672         *i_port = 80;
673         i_pos = strcspn( psz_url, "/" );
674         b_no_port = true;
675     }
676
677     *psz_host = strndup( psz_url, i_pos );
678     if( !*psz_host )
679         return VLC_ENOMEM;
680
681     if( !b_no_port )
682     {
683         i_pos++; /* skip the ':' */
684         *i_port = atoi( psz_url + i_pos );
685         if( *i_port <= 0 )
686         {
687             FREENULL( *psz_host );
688             return VLC_EGENERIC;
689         }
690
691         i_pos = strcspn( psz_url, "/" );
692     }
693
694     if( i_pos == i_len )
695         return VLC_EGENERIC;
696
697     i_pos++; /* skip the '/' */
698     *psz_file = strdup( psz_url + i_pos );
699     if( !*psz_file )
700     {
701         FREENULL( *psz_host );
702         return VLC_ENOMEM;
703     }
704
705     free( psz_url );
706     return VLC_SUCCESS;
707 }
708
709 /*****************************************************************************
710  * Handshake : Init audioscrobbler connection
711  *****************************************************************************/
712 static int Handshake( intf_thread_t *p_this )
713 {
714     char                *psz_username, *psz_password;
715     char                *psz_scrobbler_url;
716     time_t              timestamp;
717     char                psz_timestamp[21];
718
719     struct md5_s        p_struct_md5;
720
721     stream_t            *p_stream;
722     char                *psz_handshake_url;
723     uint8_t             p_buffer[1024];
724     char                *p_buffer_pos;
725
726     int                 i_ret;
727     char                *psz_url;
728
729     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
730     intf_sys_t          *p_sys                  = p_this->p_sys;
731
732     psz_username = config_GetPsz( p_this, "lastfm-username" );
733     if( !psz_username )
734         return VLC_ENOMEM;
735
736     psz_password = config_GetPsz( p_this, "lastfm-password" );
737     if( !psz_password )
738     {
739         free( psz_username );
740         return VLC_ENOMEM;
741     }
742
743     /* username or password have not been setup */
744     if ( !*psz_username || !*psz_password )
745     {
746         free( psz_username );
747         free( psz_password );
748         return VLC_ENOVAR;
749     }
750
751     time( &timestamp );
752
753     /* generates a md5 hash of the password */
754     InitMD5( &p_struct_md5 );
755     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
756     EndMD5( &p_struct_md5 );
757
758     free( psz_password );
759
760     char *psz_password_md5 = psz_md5_hash( &p_struct_md5 );
761     if( !psz_password_md5 )
762     {
763         free( psz_username );
764         return VLC_ENOMEM;
765     }
766
767     snprintf( psz_timestamp, sizeof( psz_timestamp ), "%"PRIu64,
768               (uint64_t)timestamp );
769
770     /* generates a md5 hash of :
771      * - md5 hash of the password, plus
772      * - timestamp in clear text
773      */
774     InitMD5( &p_struct_md5 );
775     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
776     AddMD5( &p_struct_md5, ( uint8_t* ) psz_timestamp, strlen( psz_timestamp ));
777     EndMD5( &p_struct_md5 );
778     free( psz_password_md5 );
779
780     char *psz_auth_token = psz_md5_hash( &p_struct_md5 );
781     if( !psz_auth_token )
782     {
783         free( psz_username );
784         return VLC_ENOMEM;
785     }
786     strncpy( p_sys->psz_auth_token, psz_auth_token, 33 );
787     free( psz_auth_token );
788
789 #if 0
790     psz_scrobbler_url = config_GetPsz( p_this, "scrobbler-url" );
791 #else
792     psz_scrobbler_url = strdup( "post.audioscrobbler.com" );
793 #endif
794     if( !psz_scrobbler_url )
795         return VLC_ENOMEM;
796
797     if( !asprintf( &psz_handshake_url,
798     "http://%s/?hs=true&p=1.2&c=%s&v=%s&u=%s&t=%s&a=%s", psz_scrobbler_url,
799         CLIENT_NAME, CLIENT_VERSION, psz_username, psz_timestamp,
800         p_sys->psz_auth_token ) )
801     {
802         free( psz_username );
803         return VLC_ENOMEM;
804     }
805     free( psz_username );
806
807     /* send the http handshake request */
808     p_stream = stream_UrlNew( p_intf, psz_handshake_url );
809     free( psz_handshake_url );
810
811     if( !p_stream )
812         return VLC_EGENERIC;
813
814     /* read answer */
815     i_ret = stream_Read( p_stream, p_buffer, 1023 );
816     if( i_ret == 0 )
817     {
818         stream_Delete( p_stream );
819         return VLC_EGENERIC;
820     }
821     p_buffer[i_ret] = '\0';
822     stream_Delete( p_stream );
823
824     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED " );
825     if ( p_buffer_pos )
826     {
827         /* handshake request failed, sorry */
828         msg_Err( p_this, "last.fm handshake failed: %s", p_buffer_pos + 7 );
829         return VLC_EGENERIC;
830     }
831
832     p_buffer_pos = strstr( ( char* ) p_buffer, "BADAUTH" );
833     if ( p_buffer_pos )
834     {
835         /* authentication failed, bad username/password combination */
836         dialog_Fatal( p_this,
837             _("last.fm: Authentication failed"),
838             _("last.fm username or password is incorrect. "
839               "Please verify your settings and relaunch VLC." ) );
840         return VLC_AUDIOSCROBBLER_EFATAL;
841     }
842
843     p_buffer_pos = strstr( ( char* ) p_buffer, "BANNED" );
844     if ( p_buffer_pos )
845     {
846         /* oops, our version of vlc has been banned by last.fm servers */
847         msg_Err( p_intf, "This version of VLC has been banned by last.fm. "
848                          "You should upgrade VLC, or disable the last.fm plugin." );
849         return VLC_AUDIOSCROBBLER_EFATAL;
850     }
851
852     p_buffer_pos = strstr( ( char* ) p_buffer, "BADTIME" );
853     if ( p_buffer_pos )
854     {
855         /* The system clock isn't good */
856         msg_Err( p_intf, "last.fm handshake failed because your clock is too "
857                          "much shifted. Please correct it, and relaunch VLC." );
858         return VLC_AUDIOSCROBBLER_EFATAL;
859     }
860
861     p_buffer_pos = strstr( ( char* ) p_buffer, "OK" );
862     if ( !p_buffer_pos )
863         goto proto;
864
865     p_buffer_pos = strstr( p_buffer_pos, "\n" );
866     if( !p_buffer_pos || strlen( p_buffer_pos ) < 34 )
867         goto proto;
868     p_buffer_pos++; /* we skip the '\n' */
869
870     /* save the session ID */
871     snprintf( p_sys->psz_auth_token, 33, "%s", p_buffer_pos );
872
873     p_buffer_pos = strstr( p_buffer_pos, "http://" );
874     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
875         goto proto;
876
877     /* We need to read the nowplaying url */
878     p_buffer_pos += 7; /* we skip "http://" */
879 #if 0 //NOT USED
880     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
881     if( !psz_url )
882         goto oom;
883
884     switch( ParseURL( psz_url, &p_sys->psz_nowp_host,
885                 &p_sys->psz_nowp_file, &p_sys->i_nowp_port ) )
886     {
887         case VLC_ENOMEM:
888             goto oom;
889         case VLC_EGENERIC:
890             goto proto;
891         case VLC_SUCCESS:
892         default:
893             break;
894     }
895 #endif
896     p_buffer_pos = strstr( p_buffer_pos, "http://" );
897     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
898         goto proto;
899
900     /* We need to read the submission url */
901     p_buffer_pos += 7; /* we skip "http://" */
902     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
903     if( !psz_url )
904         goto oom;
905
906     switch( ParseURL( psz_url, &p_sys->psz_submit_host,
907                 &p_sys->psz_submit_file, &p_sys->i_submit_port ) )
908     {
909         case VLC_ENOMEM:
910             goto oom;
911         case VLC_EGENERIC:
912             goto proto;
913         case VLC_SUCCESS:
914         default:
915             break;
916     }
917
918     return VLC_SUCCESS;
919
920 oom:
921     return VLC_ENOMEM;
922
923 proto:
924     msg_Err( p_intf, "Handshake: can't recognize server protocol" );
925     return VLC_EGENERIC;
926 }
927
928 /*****************************************************************************
929  * DeleteSong : Delete the char pointers in a song
930  *****************************************************************************/
931 static void DeleteSong( audioscrobbler_song_t* p_song )
932 {
933     FREENULL( p_song->psz_a );
934     FREENULL( p_song->psz_b );
935     FREENULL( p_song->psz_t );
936     FREENULL( p_song->psz_m );
937     FREENULL( p_song->psz_n );
938 }
939
940 /*****************************************************************************
941  * ReadMetaData : Read meta data when parsed by vlc
942  *****************************************************************************/
943 static int ReadMetaData( intf_thread_t *p_this )
944 {
945     playlist_t          *p_playlist;
946     input_thread_t      *p_input;
947     input_item_t        *p_item;
948
949     intf_sys_t          *p_sys = p_this->p_sys;
950
951     p_playlist = pl_Hold( p_this );
952     p_input = playlist_CurrentInput( p_playlist );
953     if( !p_input )
954     {
955         pl_Release( p_this );
956         return( VLC_SUCCESS );
957     }
958
959     pl_Release( p_this );
960
961     p_item = input_GetItem( p_input );
962     if( !p_item )
963         return VLC_SUCCESS;
964
965     char *psz_meta;
966 #define ALLOC_ITEM_META( a, b ) \
967     psz_meta = input_item_Get##b( p_item ); \
968     if( psz_meta && *psz_meta ) \
969     { \
970         a = encode_URI_component( psz_meta ); \
971         if( !a ) \
972         { \
973             vlc_mutex_unlock( &p_sys->lock ); \
974             vlc_object_release( p_input ); \
975             free( psz_meta ); \
976             return VLC_ENOMEM; \
977         } \
978     }
979
980     vlc_mutex_lock( &p_sys->lock );
981
982     p_sys->b_meta_read = true;
983
984     ALLOC_ITEM_META( p_sys->p_current_song.psz_a, Artist )
985     else
986     {
987         vlc_mutex_unlock( &p_sys->lock );
988         msg_Dbg( p_this, "No artist.." );
989         vlc_object_release( p_input );
990         free( psz_meta );
991         return VLC_EGENERIC;
992     }
993     free( psz_meta );
994
995     ALLOC_ITEM_META( p_sys->p_current_song.psz_t, Title )
996     else
997     {
998         vlc_mutex_unlock( &p_sys->lock );
999         msg_Dbg( p_this, "No track name.." );
1000         vlc_object_release( p_input );
1001         free( p_sys->p_current_song.psz_a );
1002         free( psz_meta );
1003         return VLC_EGENERIC;
1004     }
1005     free( psz_meta );
1006
1007     /* Now we have read the mandatory meta data, so we can submit that info */
1008     p_sys->b_submit = true;
1009
1010     ALLOC_ITEM_META( p_sys->p_current_song.psz_b, Album )
1011     else
1012         p_sys->p_current_song.psz_b = calloc( 1, 1 );
1013     free( psz_meta );
1014
1015     ALLOC_ITEM_META( p_sys->p_current_song.psz_m, TrackID )
1016     else
1017         p_sys->p_current_song.psz_m = calloc( 1, 1 );
1018     free( psz_meta );
1019
1020     p_sys->p_current_song.i_l = input_item_GetDuration( p_item ) / 1000000;
1021
1022     ALLOC_ITEM_META( p_sys->p_current_song.psz_n, TrackNum )
1023     else
1024         p_sys->p_current_song.psz_n = calloc( 1, 1 );
1025     free( psz_meta );
1026 #undef ALLOC_ITEM_META
1027
1028     msg_Dbg( p_this, "Meta data registered" );
1029
1030     vlc_mutex_unlock( &p_sys->lock );
1031     vlc_object_release( p_input );
1032     return VLC_SUCCESS;
1033
1034 }
1035
1036 static void HandleInterval( mtime_t *next, unsigned int *i_interval )
1037 {
1038     if( *i_interval == 0 )
1039     {
1040         /* first interval is 1 minute */
1041         *i_interval = 1;
1042     }
1043     else
1044     {
1045         /* else we double the previous interval, up to 120 minutes */
1046         *i_interval <<= 1;
1047         if( *i_interval > 120 )
1048             *i_interval = 120;
1049     }
1050     *next = mdate() + ( *i_interval * 1000000 * 60 );
1051 }
1052