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