Do not try to connect to last.fm every second if the request fails, and server allows...
[vlc.git] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright (C) 2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Rafaël Carré <funman at videolan org>
8  *          Kenneth Ostby <kenneo -at- idi -dot- ntnu -dot- no>
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.1
26  * http://audioscrobbler.net/wiki/Protocol1.1
27  * */
28
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32
33
34 #if defined( WIN32 )
35 #include <time.h>
36 #endif
37
38 #include <vlc/vlc.h>
39 #include <vlc_interface.h>
40 #include <vlc_meta.h>
41 #include <vlc_md5.h>
42 #include <vlc_block.h>
43 #include <vlc_stream.h>
44 #include <vlc_url.h>
45 #include <vlc_network.h>
46 #include <vlc_interface.h>
47 #include <vlc_playlist.h>
48
49 /*****************************************************************************
50  * Local prototypes
51  *****************************************************************************/
52
53 /* Keeps track of metadata to be submitted */
54 typedef struct audioscrobbler_song_t
55 {
56     char        *psz_a;                /* track artist     */
57     char        *psz_t;                /* track title      */
58     char        *psz_b;                /* track album      */
59     int         i_l;                   /* track length     */
60     char        *psz_m;                /* musicbrainz id   */
61     char        *psz_i;                /* date             */
62     time_t      time_playing;          /* date (epoch)     */
63 } audioscrobbler_song_t;
64
65
66 /* Queue to be submitted to server, 10 songs max */
67 typedef struct audioscrobbler_queue_t
68 {
69     audioscrobbler_song_t   **p_queue;      /* contains up to 10 songs        */
70     int                     i_songs_nb;     /* number of songs                */
71     void                    *p_next_queue;  /* if queue full, pointer to next */
72 } audioscrobbler_queue_t;
73
74 struct intf_sys_t
75 {
76     audioscrobbler_queue_t  *p_first_queue;     /* 1st queue              */
77     vlc_mutex_t             lock;               /* p_sys mutex            */
78
79     /* data about audioscrobbler session */
80     time_t                  time_next_exchange; /* when can we send data? */
81     char                    *psz_submit_host;   /* where to submit data ? */
82     int                     i_submit_port;      /* at which port ?        */
83     char                    *psz_submit_file;   /* in which file ?        */
84     char                    *psz_username;      /* last.fm username       */
85     vlc_bool_t              b_handshaked;       /* did we handshake ?     */
86     char                    *psz_response_md5;  /* md5 response to use    */
87
88     /* data about song currently playing */
89     audioscrobbler_song_t   *p_current_song;    /* song being played      */
90     time_t                  time_pause;         /* time when vlc paused   */
91     time_t                  time_total_pauses;  /* sum of time in pause   */
92     vlc_bool_t              b_queued;           /* has it been queud ?    */
93     vlc_bool_t              b_metadata_read;    /* did we read metadata ? */
94     vlc_bool_t              b_paused;           /* is vlc paused ?        */
95     vlc_bool_t              b_waiting_meta;     /* we need fetched data?  */
96 };
97
98 intf_sys_t *p_sys_global;     /* to retrieve p_sys in Run() thread */
99
100 static int  Open        ( vlc_object_t * );
101 static void Close       ( vlc_object_t * );
102 static void Run         ( intf_thread_t * );
103 static void Main        ( intf_thread_t * );
104 static int ItemChange   ( vlc_object_t *, const char *, vlc_value_t,
105                                 vlc_value_t, void * );
106 static int PlayingChange( vlc_object_t *, const char *, vlc_value_t,
107                                 vlc_value_t, void * );
108 static int AddToQueue   ( intf_thread_t *p_this );
109 static int Handshake    ( intf_thread_t *p_sd );
110 static int ReadMetaData ( intf_thread_t *p_this );
111 void DeleteQueue        ( audioscrobbler_queue_t *p_queue );
112
113 /*****************************************************************************
114  * Module descriptor
115  ****************************************************************************/
116
117 #define USERNAME_TEXT       N_("Username")
118 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
119 #define PASSWORD_TEXT       N_("Password")
120 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
121
122 /* if something goes wrong, we wait at least one minute before trying again */
123 #define DEFAULT_INTERVAL 60
124
125 /* last.fm client identifier */
126 #define CLIENT_NAME     PACKAGE
127 #define CLIENT_VERSION  VERSION
128
129 /* HTTP POST request : to submit data */
130 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
131                         "Accept-Encoding: identity\n"                       \
132                         "Content-length: %u\n"                              \
133                         "Connection: close\n"                               \
134                         "Content-type: application/x-www-form-urlencoded\n" \
135                         "Host: %s\n"                                        \
136                         "User-agent: VLC Media Player/%s\r\n"               \
137                         "\r\n"                                              \
138                         "%s\r\n"                                            \
139                         "\r\n"
140
141 /* data to submit */
142 #define POST_DATA       "&a%%5B%d%%5D=%s&t%%5B%d%%5D=%s&b%%5B%d%%5D=%s" \
143                         "&m%%5B%d%%5D=%s&l%%5B%d%%5D=%d&i%%5B%d%%5D=%s"
144 #define HTTPPOST_MAXLEN 2048
145
146 vlc_module_begin();
147     set_category( CAT_INTERFACE );
148     set_subcategory( SUBCAT_INTERFACE_CONTROL );
149     set_shortname( N_( "Audioscrobbler" ) );
150     set_description( N_("Audioscrobbler submission Plugin") );
151     add_string( "lastfm-username", "", NULL,
152                 USERNAME_TEXT, USERNAME_LONGTEXT, VLC_FALSE );
153     add_password( "lastfm-password", "", NULL,
154                 PASSWORD_TEXT, PASSWORD_LONGTEXT, VLC_FALSE );
155     set_capability( "interface", 0 );
156     set_callbacks( Open, Close );
157 vlc_module_end();
158
159 /*****************************************************************************
160  * Open: initialize and create stuff
161  *****************************************************************************/
162
163 static int Open( vlc_object_t *p_this )
164 {
165     playlist_t      *p_playlist;
166     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
167     intf_sys_t      *p_sys      = malloc( sizeof( intf_sys_t ) );
168
169 #define MEM_ERROR \
170     free( p_sys->p_current_song ); \
171     free( p_sys->p_first_queue ); \
172     free( p_sys->psz_response_md5 ); \
173     free( p_sys ); \
174     return VLC_ENOMEM;
175
176     if( !p_sys )
177     {
178         MEM_ERROR
179     }
180
181     p_intf->p_sys = p_sys;
182
183     vlc_mutex_init( p_this, &p_sys->lock );
184
185     p_sys_global = p_sys;
186     p_sys->psz_submit_host = NULL;
187     p_sys->psz_submit_file = NULL;
188     p_sys->b_handshaked = VLC_FALSE;
189     p_sys->time_next_exchange = time( NULL );
190     p_sys->psz_username = NULL;
191     p_sys->b_paused = VLC_FALSE;
192
193 #define MALLOC_CHECK( a ) \
194     if( !a ) { \
195         vlc_mutex_destroy( &p_sys->lock ); \
196         MEM_ERROR \
197     }
198
199     /* md5 response is 32 chars, + final \0 */
200     p_sys->psz_response_md5 = malloc( 33 );
201     MALLOC_CHECK( p_sys->psz_response_md5 )
202
203     p_sys->p_first_queue = malloc( sizeof( audioscrobbler_queue_t ) );
204     MALLOC_CHECK( p_sys->p_first_queue )
205
206     p_sys->p_current_song = malloc( sizeof( audioscrobbler_song_t ) );
207     MALLOC_CHECK( p_sys->p_current_song )
208     time( &p_sys->p_current_song->time_playing );
209
210     /* queues can't contain more than 10 songs */
211     p_sys->p_first_queue->p_queue =
212         malloc( 10 * sizeof( audioscrobbler_song_t ) );
213     MALLOC_CHECK( p_sys->p_current_song )
214
215     p_sys->p_first_queue->i_songs_nb = 0;
216     p_sys->p_first_queue->p_next_queue = NULL;
217
218     p_playlist = pl_Yield( p_intf );
219     PL_LOCK;
220     var_AddCallback( p_playlist, "playlist-current", ItemChange, p_intf );
221     PL_UNLOCK;
222     pl_Release( p_playlist );
223
224     p_intf->pf_run = Run;
225
226     return VLC_SUCCESS;
227 #undef MEM_ERROR
228 #undef MALLOC_CHECK
229 }
230
231 /*****************************************************************************
232  * Close: destroy interface stuff
233  *****************************************************************************/
234 static void Close( vlc_object_t *p_this )
235 {
236     audioscrobbler_queue_t      *p_current_queue, *p_next_queue;
237     playlist_t                  *p_playlist;
238     input_thread_t              *p_input;
239     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
240     intf_sys_t                  *p_sys  = p_intf->p_sys;
241
242     p_playlist = pl_Yield( p_intf );
243     PL_LOCK;
244     var_DelCallback( p_playlist, "playlist-current", ItemChange, p_intf );
245
246     p_input = p_playlist->p_input;
247     if ( p_input )
248     {
249         vlc_object_yield( p_input );
250         var_DelCallback( p_input, "state", PlayingChange, p_intf );
251         vlc_object_release( p_input );
252     }
253
254     PL_UNLOCK;
255     pl_Release( p_playlist );
256
257     vlc_mutex_lock ( &p_sys->lock );
258     p_current_queue = p_sys->p_first_queue;
259     vlc_mutex_unlock ( &p_sys->lock );
260
261     while( ( p_current_queue->i_songs_nb == 10 ) &&
262         ( p_current_queue->p_next_queue != NULL ) )
263     {
264         p_next_queue = p_current_queue->p_next_queue;
265         DeleteQueue( p_current_queue );
266         free( p_current_queue );
267         p_current_queue = p_next_queue;
268     }
269
270     DeleteQueue( p_current_queue );
271     free( p_current_queue );
272
273     vlc_mutex_lock ( &p_sys->lock );
274     free( p_sys->psz_username );
275     free( p_sys->p_current_song );
276     free( p_sys->psz_submit_host );
277     free( p_sys->psz_submit_file );
278     free( p_sys->psz_response_md5 );
279     vlc_mutex_unlock ( &p_sys->lock );
280     vlc_mutex_destroy( &p_sys->lock );
281     free( p_sys );
282 }
283
284 /****************************************************************************
285  * Run : create Main() thread
286  * **************************************************************************/
287 static void Run( intf_thread_t *p_intf )
288 {
289     if( vlc_thread_create( p_intf, "Audioscrobbler", Main, 0, VLC_TRUE ) )
290         msg_Err( p_intf, "failed to create Audioscrobbler thread" );
291 }
292
293 /*****************************************************************************
294  * Main : call Handshake() then submit songs
295  *****************************************************************************/
296 static void Main( intf_thread_t *p_this )
297 {
298     char                    *psz_submit         = NULL;
299     char                    *psz_submit_song    = NULL;
300     int                     i_net_ret;
301     int                     i_song;
302     playlist_t              *p_playlist;
303     uint8_t                 *p_buffer           = NULL;
304     char                    *p_buffer_pos       = NULL;
305     audioscrobbler_queue_t  *p_first_queue;
306     int                     i_post_socket;
307     time_t                  played_time;
308
309     vlc_thread_ready( p_this );
310
311     p_this->p_sys = p_sys_global;
312     intf_sys_t *p_sys = p_this->p_sys;
313
314     #define MEM_ERROR \
315         free( psz_submit ); \
316         free( psz_submit_song ); \
317         free( p_buffer ); \
318         msg_Err( p_this, "Out of memory" ); \
319         return;
320
321     psz_submit = malloc( HTTPPOST_MAXLEN );
322     psz_submit_song = malloc( HTTPPOST_MAXLEN );
323     p_buffer = ( uint8_t* ) malloc( 1024 );
324
325     if( !psz_submit || !psz_submit_song || !p_buffer )
326     {
327         MEM_ERROR
328     }
329
330     /* main loop */
331     while( !p_this->b_die )
332     {
333         /* verify if there is data to submit
334          * and if waiting interval is elapsed */
335         if ( ( p_sys->p_first_queue->i_songs_nb > 0 ) &&
336             ( time( NULL ) >= p_sys->time_next_exchange ) )
337         {
338             /* handshake if needed */
339             if( p_sys->b_handshaked == VLC_FALSE )
340             {
341                 msg_Dbg( p_this, "Handshaking with last.fm ..." );
342
343                 switch( Handshake( p_this ) )
344                 {
345                     case VLC_ENOMEM:
346                         MEM_ERROR
347                         break;
348
349                     case VLC_ENOVAR:
350                         /* username not set */
351                         vlc_mutex_unlock ( &p_sys->lock );
352                         intf_UserFatal( p_this, VLC_FALSE,
353                             _("Last.fm username not set"),
354                             _("Please set an username or disable "
355                             "audioscrobbler plugin, and then restart VLC.\n"
356                             "Visit https://www.last.fm/join/ to get an account")
357                         );
358                         free( psz_submit );
359                         free( psz_submit_song );
360                         free( p_buffer );
361                         return;
362                         break;
363
364                     case VLC_SUCCESS:
365                         msg_Dbg( p_this, "Handshake successfull :)" );
366                         vlc_mutex_lock ( &p_sys->lock );
367                         p_sys->b_handshaked = VLC_TRUE;
368                         vlc_mutex_unlock ( &p_sys->lock );
369                         break;
370
371                     case VLC_EGENERIC:
372                     default:
373                         /* protocol error : we'll try later */
374                         vlc_mutex_lock ( &p_sys->lock );
375                         time( &p_sys->time_next_exchange );
376                         p_sys->time_next_exchange += DEFAULT_INTERVAL;
377                         vlc_mutex_unlock ( &p_sys->lock );
378                         break;
379                 }
380                 /* handshake is done or failed, lets start from
381                  * beginning to check it out and wait INTERVAL if needed
382                  */
383                 continue;
384             }
385
386             msg_Dbg( p_this, "Going to submit some data..." );
387             vlc_mutex_lock ( &p_sys->lock );
388
389             snprintf( psz_submit, HTTPPOST_MAXLEN, "u=%s&s=%s",
390                 p_sys->psz_username, p_sys->psz_response_md5 );
391
392             /* forge the HTTP POST request */
393             for (i_song = 0 ; i_song < p_sys->p_first_queue->i_songs_nb ;
394                 i_song++ )
395             {
396                 snprintf( psz_submit_song, HTTPPOST_MAXLEN -1, POST_DATA,
397                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_a,
398                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_t,
399                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_b,
400                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_m,
401                     i_song, p_sys->p_first_queue->p_queue[i_song]->i_l,
402                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_i
403                 );
404                 strncat( psz_submit, psz_submit_song, HTTPPOST_MAXLEN - 1 );
405             }
406
407             i_post_socket = net_ConnectTCP( p_this,
408                 p_sys->psz_submit_host, p_sys->i_submit_port);
409
410             if ( i_post_socket == -1 )
411             {
412                 /* If connection fails, we assume we must handshake again */
413                 time( &p_sys->time_next_exchange );
414                 p_sys->time_next_exchange += DEFAULT_INTERVAL;
415                 p_sys->b_handshaked = VLC_FALSE;
416                 vlc_mutex_unlock( &p_sys->lock );
417                 continue;
418             }
419
420             /* we transmit the data */
421             i_net_ret = net_Printf(
422                 VLC_OBJECT(p_this), i_post_socket, NULL,
423                 POST_REQUEST, p_sys->psz_submit_file,
424                 (unsigned)strlen( psz_submit ), p_sys->psz_submit_file,
425                 VERSION, psz_submit
426             );
427
428             if ( i_net_ret == -1 )
429             {
430                 /* If connection fails, we assume we must handshake again */
431                 time( &p_sys->time_next_exchange );
432                 p_sys->time_next_exchange += DEFAULT_INTERVAL;
433                 p_sys->b_handshaked = VLC_FALSE;
434                 vlc_mutex_unlock( &p_sys->lock );
435                 continue;
436             }
437
438             memset( p_buffer, '\0', 1024 );
439
440             i_net_ret = net_Read( p_this, i_post_socket, NULL,
441                         p_buffer, 1024, VLC_FALSE );
442             if ( i_net_ret <= 0 )
443             {
444                 /* if we get no answer, something went wrong : try again */
445                 vlc_mutex_unlock( &p_sys->lock );
446                 continue;
447             }
448
449             net_Close( i_post_socket );
450
451             /* record interval */
452             p_buffer_pos = strstr( ( char * ) p_buffer, "INTERVAL " );
453             if ( p_buffer_pos )
454             {
455                 time( &p_sys->time_next_exchange );
456                 p_sys->time_next_exchange += atoi( p_buffer_pos +
457                                             strlen( "INTERVAL " ) );
458             }
459
460             p_buffer_pos = strstr( ( char * ) p_buffer, "FAILED" );
461             if ( p_buffer_pos )
462             {
463                 /* woops, submission failed */
464                 msg_Dbg( p_this, "%s", p_buffer_pos );
465                 /* Buggy last.fm server sometimes return INTERVAL 1 */
466                 p_sys->time_next_exchange += DEFAULT_INTERVAL;
467                 vlc_mutex_unlock ( &p_sys->lock );
468                 continue;
469             }
470
471             p_buffer_pos = strstr( ( char * ) p_buffer, "BADAUTH" );
472             if ( p_buffer_pos )
473             {
474                 msg_Dbg( p_this, "Authentification failed, handshaking again" );
475                 p_sys->b_handshaked = VLC_FALSE;
476                 vlc_mutex_unlock ( &p_sys->lock );
477                 continue;
478             }
479
480             p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
481             if ( p_buffer_pos )
482             {
483                 if ( p_sys->p_first_queue->i_songs_nb == 10 )
484                 {
485                     /* if there are more than one queue, delete the 1st */
486                     p_first_queue = p_sys->p_first_queue->p_next_queue;
487                     DeleteQueue( p_sys->p_first_queue );
488                     free( p_sys->p_first_queue );
489                     p_sys->p_first_queue = p_first_queue;
490                 }
491                 else
492                 {
493                     DeleteQueue( p_sys->p_first_queue );
494                     p_sys->p_first_queue->i_songs_nb = 0;
495                 }
496                 msg_Dbg( p_this, "Submission successfull!" );
497             }
498             vlc_mutex_unlock ( &p_sys->lock );
499         } /* data transmission finished or skipped */
500
501         msleep( INTF_IDLE_SLEEP );
502
503         p_playlist = pl_Yield( p_this );
504         PL_LOCK;
505         if( p_playlist->request.i_status == PLAYLIST_STOPPED )
506         {
507             /* if we stopped, we won't submit playing song */
508             vlc_mutex_lock( &p_sys->lock );
509             p_sys->b_queued = VLC_TRUE;
510             p_sys->b_metadata_read = VLC_TRUE;
511             vlc_mutex_unlock( &p_sys->lock );
512         }
513         PL_UNLOCK;
514         pl_Release( p_playlist );
515
516         vlc_mutex_lock( &p_sys->lock );
517         if( p_sys->b_metadata_read == VLC_FALSE )
518         {
519             /* we read the metadata of the playing song */
520             time( &played_time );
521             played_time -= p_sys->p_current_song->time_playing;
522             played_time -= p_sys->time_total_pauses;
523
524             vlc_mutex_unlock( &p_sys->lock );
525
526             if( played_time > 20 )
527             /* wait at least 20 secondes before reading the meta data
528              * since the songs must be at least 30s */
529             {
530                 if ( ReadMetaData( p_this ) == VLC_ENOMEM )
531                 {
532                     MEM_ERROR
533                 }
534             }
535         }
536         else
537         {
538             /* we add the playing song into the queue */
539             if( ( p_sys->b_queued == VLC_FALSE )
540                 && ( p_sys->b_paused == VLC_FALSE ) )
541             {
542                 vlc_mutex_unlock( &p_sys->lock );
543                 if( AddToQueue( p_this ) == VLC_ENOMEM )
544                 {
545                     MEM_ERROR
546                 }
547             }
548             else
549             {
550                 vlc_mutex_unlock( &p_sys->lock );
551             }
552         }
553     }
554 #undef MEM_ERROR
555 }
556
557 /*****************************************************************************
558  * PlayingChange: Playing status change callback
559  *****************************************************************************/
560 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
561                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
562 {
563     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
564     intf_sys_t      *p_sys  = p_intf->p_sys;
565
566     (void)p_this; (void)psz_var; (void)oldval;
567
568     /* don't bother if song has already been queued */
569     if( p_sys->b_queued == VLC_TRUE )
570         return VLC_SUCCESS;
571
572     vlc_mutex_lock( &p_sys->lock );
573
574     if( newval.i_int == PAUSE_S )
575     {
576         time( &p_sys->time_pause );
577         p_sys->b_paused = VLC_TRUE;
578     }
579
580     else if( newval.i_int == PLAYING_S )
581     {
582         p_sys->time_total_pauses += time( NULL ) - p_sys->time_pause;
583         p_sys->b_paused = VLC_FALSE;
584     }
585
586     vlc_mutex_unlock( &p_sys->lock );
587
588     return VLC_SUCCESS;
589 }
590
591 /*****************************************************************************
592  * ItemChange: Playlist item change callback
593  *****************************************************************************/
594 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
595                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
596 {
597     playlist_t          *p_playlist;
598     input_thread_t      *p_input    = NULL;
599     time_t              epoch;
600     struct tm           *epoch_tm;
601     char                psz_date[20];
602     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
603     intf_sys_t          *p_sys      = p_intf->p_sys;
604     (void)p_this; (void)psz_var; (void)oldval; (void)newval;
605
606     p_playlist = pl_Yield( p_intf );
607     PL_LOCK;
608     p_input = p_playlist->p_input;
609
610     if( !p_input )
611     {
612         PL_UNLOCK;
613         pl_Release( p_playlist );
614
615         vlc_mutex_lock( &p_sys->lock );
616
617         p_sys->b_queued = VLC_TRUE;
618         p_sys->b_metadata_read = VLC_TRUE;
619
620         vlc_mutex_unlock( &p_sys->lock );
621
622         return VLC_SUCCESS;
623     }
624
625     vlc_object_yield( p_input );
626     PL_UNLOCK;
627     pl_Release( p_playlist );
628
629     var_AddCallback( p_input, "state", PlayingChange, p_intf );
630
631     vlc_mutex_lock ( &p_sys->lock );
632
633     /* reset pause counter */
634     p_sys->time_total_pauses = 0;
635
636     /* we'll read metadata when it's present */
637     p_sys->b_metadata_read = VLC_FALSE;
638     p_sys->b_waiting_meta = VLC_FALSE;
639
640     time( &epoch );
641     epoch_tm = gmtime( &epoch );
642     snprintf( psz_date, 20, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
643         epoch_tm->tm_year+1900, epoch_tm->tm_mon+1, epoch_tm->tm_mday,
644         epoch_tm->tm_hour, epoch_tm->tm_min, epoch_tm->tm_sec );
645
646     p_sys->p_current_song->psz_i = encode_URI_component( psz_date );
647     p_sys->p_current_song->time_playing = epoch;
648
649     char *psz_name = input_item_GetName( input_GetItem( p_input ) );
650     p_sys->b_paused = ( p_input->b_dead || !psz_name )
651                       ? VLC_TRUE : VLC_FALSE;
652     free( psz_name );
653
654     vlc_mutex_unlock( &p_sys->lock );
655
656     vlc_object_release( p_input );
657     return VLC_SUCCESS;
658 }
659
660 /*****************************************************************************
661  * AddToQueue: Add the played song to the queue to be submitted
662  *****************************************************************************/
663 static int AddToQueue ( intf_thread_t *p_this )
664 {
665     int                         i_songs_nb;
666     time_t                      played_time;
667     audioscrobbler_queue_t      *p_queue        = NULL,
668                                 *p_next_queue   = NULL;
669     intf_sys_t                  *p_sys          = p_this->p_sys;
670
671     /* wait for the user to listen enough before submitting */
672     time ( &played_time );
673     vlc_mutex_lock( &p_sys->lock );
674
675     played_time -= p_sys->p_current_song->time_playing;
676     played_time -= p_sys->time_total_pauses;
677
678     #define NO_SUBMISSION \
679         p_sys->b_queued = VLC_TRUE; \
680         vlc_mutex_unlock( &p_sys->lock ); \
681         return VLC_SUCCESS;
682
683     if( ( played_time < 240 ) &&
684         ( played_time < ( p_sys->p_current_song->i_l / 2 ) ) )
685     {
686         //msg_Dbg( p_this, "Song not listened long enough -> waiting" );
687         vlc_mutex_unlock( &p_sys->lock );
688         return VLC_SUCCESS;
689     }
690
691     if( p_sys->p_current_song->i_l < 30 )
692     {
693         msg_Dbg( p_this, "Song too short (< 30s) -> not submitting" );
694         NO_SUBMISSION
695     }
696
697     if( !p_sys->p_current_song->psz_a || !*p_sys->p_current_song->psz_a ||
698         !p_sys->p_current_song->psz_t || !*p_sys->p_current_song->psz_t )
699     {
700         msg_Dbg( p_this, "Missing artist or title -> not submitting" );
701         NO_SUBMISSION
702     }
703
704     msg_Dbg( p_this, "Ok. We'll put it in the queue for submission" );
705
706     /* go to last queue */
707     p_queue = p_sys->p_first_queue;
708     while( ( p_queue->i_songs_nb == 10 ) && ( p_queue->p_next_queue != NULL ) )
709         p_queue = p_queue->p_next_queue;
710
711     i_songs_nb = p_queue->i_songs_nb;
712
713     #define MALLOC_CHECK( a ) \
714         if( !a ) { \
715             vlc_mutex_unlock( &p_sys->lock ); \
716             return VLC_ENOMEM; \
717         }
718
719     if( i_songs_nb == 10 )
720     {
721         p_next_queue = malloc( sizeof( audioscrobbler_queue_t ) );
722         MALLOC_CHECK( p_next_queue );
723         p_queue->p_next_queue = p_next_queue;
724         p_queue = p_next_queue;
725         i_songs_nb = 0;
726         p_queue->i_songs_nb = i_songs_nb;
727     }
728
729     p_queue->p_queue[i_songs_nb] = malloc( sizeof( audioscrobbler_song_t ) );
730     MALLOC_CHECK( p_queue->p_queue[i_songs_nb] );
731
732     #define QUEUE_COPY( a ) \
733         p_queue->p_queue[i_songs_nb]->a = p_sys->p_current_song->a
734
735     QUEUE_COPY(i_l);
736     QUEUE_COPY(psz_a);
737     QUEUE_COPY(psz_t);
738     QUEUE_COPY(psz_b);
739     QUEUE_COPY(psz_m);
740     QUEUE_COPY(psz_i);
741
742     p_queue->i_songs_nb++;
743     p_sys->b_queued = VLC_TRUE;
744
745     vlc_mutex_unlock( &p_sys->lock );
746
747     return VLC_SUCCESS;
748 #undef QUEUE_COPY
749 #undef MALLOC_CHECK
750 #undef NO_SUBMISSION
751 }
752
753 /*****************************************************************************
754  * Handshake : Init audioscrobbler connection
755  *****************************************************************************/
756 static int Handshake( intf_thread_t *p_this )
757 {
758     char                *psz_password           = NULL;
759     struct md5_s        *p_struct_md5           = NULL;
760     char                *psz_password_md5       = NULL;
761     char                *ps_challenge_md5       = NULL;
762     stream_t            *p_stream;
763     char                *psz_handshake_url      = NULL;
764     uint8_t             *p_buffer               = NULL;
765     char                *p_buffer_pos           = NULL;
766     char                *psz_url_parser         = NULL;
767     char                *psz_buffer_substring;
768     int                 i_url_pos, i;
769
770     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
771     intf_sys_t          *p_sys                  = p_this->p_sys;
772
773     vlc_mutex_lock ( &p_sys->lock );
774
775     #define MEM_ERROR \
776         free( p_buffer ); \
777         free( p_struct_md5 ); \
778         free( ps_challenge_md5 ); \
779         vlc_mutex_unlock( &p_sys->lock ); \
780         return VLC_ENOMEM;
781
782     #define PROTOCOL_ERROR \
783         free( p_buffer ); \
784         vlc_mutex_unlock( &p_sys->lock ); \
785         return VLC_EGENERIC;
786
787     #define MALLOC_CHECK( a ) \
788         if( !a ) \
789         { \
790             MEM_ERROR \
791         }
792
793     p_sys->psz_username = config_GetPsz(p_this, "lastfm-username");
794     MALLOC_CHECK( p_sys->psz_username )
795
796     /* username has not been setup, ignoring */
797     if ( !*p_sys->psz_username )
798         return VLC_ENOVAR;
799
800     psz_handshake_url = malloc( 1024 );
801     MALLOC_CHECK( p_sys->psz_username )
802
803     snprintf( psz_handshake_url, 1024,
804         "http://post.audioscrobbler.com/?hs=true&p=1.1&c=%s&v=%s&u=%s",
805         CLIENT_NAME, CLIENT_VERSION, p_sys->psz_username );
806
807     /* send the http handshake request */
808     p_stream = stream_UrlNew( p_intf, psz_handshake_url);
809
810     free( psz_handshake_url );
811
812     if( !p_stream )
813     {
814         vlc_mutex_unlock ( &p_sys->lock );
815         return VLC_EGENERIC;
816     }
817
818     p_buffer = ( uint8_t* ) calloc( 1, 1024 );
819     if ( !p_buffer )
820     {
821         stream_Delete( p_stream );
822         MEM_ERROR
823     }
824
825     /* read answer */
826     if ( stream_Read( p_stream, p_buffer, 1024 ) == 0 )
827     {
828         stream_Delete( p_stream );
829         PROTOCOL_ERROR
830     }
831
832     stream_Delete( p_stream );
833
834     /* record interval before next submission */
835     p_buffer_pos = strstr( ( char* ) p_buffer, "INTERVAL" );
836     if ( p_buffer_pos )
837     {
838         time( &p_sys->time_next_exchange );
839         p_sys->time_next_exchange +=
840                 atoi( p_buffer_pos + strlen( "INTERVAL " ) );
841     }
842
843     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED" );
844     if ( p_buffer_pos )
845     {
846         /* handshake request failed, sorry */
847         msg_Dbg( p_this, "%s", p_buffer_pos );
848         PROTOCOL_ERROR
849     }
850
851     p_buffer_pos = strstr( ( char* ) p_buffer, "BADUSER" );
852     if ( p_buffer_pos )
853     {
854         /* username does not exist on the server */
855         intf_UserFatal( p_this, VLC_FALSE, _("Bad last.fm Username"),
856             _("last.fm username is incorrect, please verify your settings")
857         );
858         PROTOCOL_ERROR
859     }
860
861     p_buffer_pos = strstr( ( char* ) p_buffer, "UPDATE" );
862     if ( p_buffer_pos )
863     {
864         /* protocol has been updated, time to update the code */
865         msg_Dbg( p_intf, "Protocol updated : plugin may be outdated" );
866         msg_Dbg( p_intf, "%s", p_buffer_pos );
867     }
868
869     else
870     {
871         p_buffer_pos = strstr( ( char* ) p_buffer, "UPTODATE" );
872         if ( !p_buffer_pos )
873         {
874             msg_Dbg( p_intf, "Can't recognize server protocol" );
875             PROTOCOL_ERROR
876         }
877     }
878
879     psz_buffer_substring = strstr( p_buffer_pos, "\n" );
880     if( ( psz_buffer_substring == NULL ) || \
881             ( strlen( psz_buffer_substring + 1 ) < 32 ) )
882     {
883         msg_Dbg( p_intf, "Can't recognize server protocol" );
884         PROTOCOL_ERROR
885     }
886     else
887     {
888         ps_challenge_md5 = malloc( 32 );
889         MALLOC_CHECK( ps_challenge_md5 )
890         memcpy( ps_challenge_md5, psz_buffer_substring + 1, 32 );
891     }
892
893     p_buffer_pos = ( void* ) strstr( ( char* ) p_buffer, "http://" );
894
895     /* free old information */
896     free( p_sys->psz_submit_host );
897     free( p_sys->psz_submit_file );
898
899     psz_url_parser = p_buffer_pos + strlen( "http://" );
900     i_url_pos = strcspn( psz_url_parser, ":" );
901
902     p_sys->psz_submit_host = strndup( psz_url_parser, i_url_pos );
903     MALLOC_CHECK( p_sys->psz_submit_host )
904
905     p_sys->i_submit_port = atoi( psz_url_parser + i_url_pos + 1 );
906
907     psz_url_parser += strcspn( psz_url_parser , "/" ) + 1;
908     i_url_pos = strcspn( psz_url_parser, "\n" );
909     p_sys->psz_submit_file = strndup( psz_url_parser, i_url_pos );
910     MALLOC_CHECK( p_sys->psz_submit_file )
911
912     free(p_buffer);
913
914     p_struct_md5 = malloc( sizeof( struct md5_s ) );
915     MALLOC_CHECK( p_struct_md5 )
916
917     psz_password = config_GetPsz(p_this, "lastfm-password");
918     MALLOC_CHECK( psz_password )
919
920     /* generates a md5 hash of the password */
921     InitMD5( p_struct_md5 );
922     AddMD5( p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
923     EndMD5( p_struct_md5 );
924
925     free( psz_password );
926
927     psz_password_md5 = malloc ( 33 );
928     MALLOC_CHECK( psz_password_md5 )
929
930     for ( i = 0; i < 4; i++ )
931     {
932         sprintf( &psz_password_md5[8*i], "%02x%02x%02x%02x",
933             p_struct_md5->p_digest[i] & 0xff,
934             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
935             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
936             p_struct_md5->p_digest[i] >> 24
937         );
938     }
939
940     /* generates a md5 hash of :
941      * - md5 hash of the password, plus
942      * - md5 challenge sent by last.fm server
943      */
944     InitMD5( p_struct_md5 );
945     AddMD5( p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
946     AddMD5( p_struct_md5, ( uint8_t* ) ps_challenge_md5, 32 );
947     EndMD5( p_struct_md5 );
948
949     free( ps_challenge_md5 );
950     free( psz_password_md5 );
951
952     for ( i = 0; i < 4; i++ )
953     {
954         sprintf( &p_sys->psz_response_md5[8*i], "%02x%02x%02x%02x",
955             p_struct_md5->p_digest[i] & 0xff,
956             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
957             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
958             p_struct_md5->p_digest[i] >> 24
959         );
960     }
961
962     p_sys->psz_response_md5[32] = '\0';
963
964     vlc_mutex_unlock ( &p_sys->lock );
965
966     return VLC_SUCCESS;
967 #undef MEM_ERROR
968 #undef PROTOCOL_ERROR
969 #undef MALLOC_CHECK
970 }
971
972 /*****************************************************************************
973  * DeleteQueue : Free all songs from an audioscrobbler_queue_t
974  *****************************************************************************/
975 void DeleteQueue( audioscrobbler_queue_t *p_queue )
976 {
977     int     i;
978
979     for( i = 0; i < p_queue->i_songs_nb; i++ )
980     {
981         free( p_queue->p_queue[i]->psz_a );
982         free( p_queue->p_queue[i]->psz_b );
983         free( p_queue->p_queue[i]->psz_t );
984         free( p_queue->p_queue[i]->psz_i );
985         free( p_queue->p_queue[i] );
986     }
987 }
988
989 /*****************************************************************************
990  * ReadMetaData : Read meta data when parsed by vlc
991  * or wait for fetching if unavailable
992  *****************************************************************************/
993 static int ReadMetaData( intf_thread_t *p_this )
994 {
995     playlist_t          *p_playlist;
996     input_thread_t      *p_input        = NULL;
997     vlc_value_t         video_val;
998
999     char                *psz_title      = NULL;
1000     char                *psz_artist     = NULL;
1001     char                *psz_album      = NULL;
1002     char                *psz_trackid    = NULL;
1003     int                 i_length        = -1;
1004     vlc_bool_t          b_waiting;
1005     intf_sys_t          *p_sys          = p_this->p_sys;
1006     int                 i_status;
1007
1008     p_playlist = pl_Yield( p_this );
1009     PL_LOCK;
1010     p_input = p_playlist->p_input;
1011
1012     if( !p_input )
1013     {
1014         PL_UNLOCK;
1015         pl_Release( p_playlist );
1016         return( VLC_SUCCESS );
1017     }
1018
1019     vlc_object_yield( p_input );
1020     PL_UNLOCK;
1021     pl_Release( p_playlist );
1022
1023     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
1024     if( ( video_val.i_int > 0 ) || \
1025         ( input_GetItem( p_input )->i_type == ITEM_TYPE_NET ) )
1026     {
1027         msg_Dbg( p_this, "Not an audio only local file -> no submission");
1028         vlc_object_release( p_input );
1029
1030         vlc_mutex_lock( &p_sys->lock );
1031         p_sys->b_queued = VLC_TRUE;
1032         p_sys->b_metadata_read = VLC_TRUE;
1033         vlc_mutex_unlock( &p_sys->lock );
1034
1035         return VLC_SUCCESS;
1036     }
1037
1038     #define FREE_INPUT_AND_CHARS \
1039         vlc_object_release( p_input ); \
1040         free( psz_title ); \
1041         free( psz_artist ); \
1042         free( psz_album ); \
1043         free( psz_trackid );
1044
1045     #define WAIT_METADATA_FETCHING( a ) \
1046         if ( b_waiting == VLC_TRUE ) \
1047         { \
1048             a = calloc( 1, 1 ); \
1049         } \
1050         else \
1051         { \
1052             vlc_object_release( p_input ); \
1053             vlc_mutex_lock( &p_sys->lock ); \
1054             p_sys->b_waiting_meta = VLC_TRUE; \
1055             vlc_mutex_unlock( &p_sys->lock ); \
1056             free( psz_artist ); \
1057             return VLC_SUCCESS; \
1058         }
1059
1060     char *psz_meta;
1061     #define ALLOC_ITEM_META( a, b ) \
1062         psz_meta = input_item_Get##b( input_GetItem( p_input ) ); \
1063         if( psz_meta ) \
1064         { \
1065             a = encode_URI_component( psz_meta ); \
1066             if( !a ) \
1067             { \
1068                 free( psz_meta ); \
1069                 FREE_INPUT_AND_CHARS \
1070                 return VLC_ENOMEM; \
1071             } \
1072             free( psz_meta ); \
1073         }
1074
1075     i_status = input_GetItem(p_input)->p_meta->i_status;
1076
1077     vlc_mutex_lock( &p_sys->lock );
1078     b_waiting = p_sys->b_waiting_meta;
1079     vlc_mutex_unlock( &p_sys->lock );
1080
1081     if( i_status & ( !b_waiting ? ITEM_PREPARSED : ITEM_META_FETCHED ) )
1082     {
1083         ALLOC_ITEM_META( psz_artist, Artist )
1084         else
1085         {
1086             msg_Dbg( p_this, "No artist.." );
1087             WAIT_METADATA_FETCHING( psz_artist )
1088         }
1089         psz_meta = input_item_GetTitle( input_GetItem( p_input ) );
1090         if( psz_meta )
1091         {
1092             psz_title = encode_URI_component( psz_meta );
1093             if( !psz_title )
1094             {
1095                 free( psz_meta );
1096                 FREE_INPUT_AND_CHARS
1097                 return VLC_ENOMEM;
1098             }
1099             free( psz_meta );
1100         }
1101         else
1102         {
1103             msg_Dbg( p_this, "No track name.." );
1104             WAIT_METADATA_FETCHING( psz_title );
1105         }
1106
1107         ALLOC_ITEM_META( psz_album, Album )
1108         else
1109             psz_album = calloc( 1, 1 );
1110
1111         ALLOC_ITEM_META( psz_trackid, TrackID )
1112         else
1113             psz_trackid = calloc( 1, 1 );
1114
1115         i_length = input_item_GetDuration( input_GetItem( p_input ) ) / 1000000;
1116
1117         vlc_mutex_lock ( &p_sys->lock );
1118
1119         p_sys->p_current_song->psz_a    = strdup( psz_artist );
1120         p_sys->p_current_song->psz_t    = strdup( psz_title );
1121         p_sys->p_current_song->psz_b    = strdup( psz_album );
1122         p_sys->p_current_song->psz_m    = strdup( psz_trackid );
1123         p_sys->p_current_song->i_l      = i_length;
1124         p_sys->b_queued                 = VLC_FALSE;
1125         p_sys->b_metadata_read          = VLC_TRUE;
1126
1127         vlc_mutex_unlock( &p_sys->lock );
1128
1129         msg_Dbg( p_this, "Meta data registered, waiting to be queued" );
1130     }
1131  
1132     FREE_INPUT_AND_CHARS
1133     return VLC_SUCCESS;
1134 #undef FREE_INPUT_AND_CHARS
1135 #undef ALLOC_ITEM_META
1136 #undef WAIT_METADATA_FETCHING
1137 }