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