]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
e4c8e9216f96f9a3a8b9f8587a9d538813495826
[vlc] / 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: %d\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                 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                 vlc_mutex_unlock ( &p_sys->lock );
466                 continue;
467             }
468
469             p_buffer_pos = strstr( ( char * ) p_buffer, "BADAUTH" );
470             if ( p_buffer_pos )
471             {
472                 msg_Dbg( p_this, "Authentification failed, handshaking again" );
473                 p_sys->b_handshaked = VLC_FALSE;
474                 vlc_mutex_unlock ( &p_sys->lock );
475                 continue;
476             }
477
478             p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
479             if ( p_buffer_pos )
480             {
481                 if ( p_sys->p_first_queue->i_songs_nb == 10 )
482                 {
483                     /* if there are more than one queue, delete the 1st */
484                     p_first_queue = p_sys->p_first_queue->p_next_queue;
485                     DeleteQueue( p_sys->p_first_queue );
486                     free( p_sys->p_first_queue );
487                     p_sys->p_first_queue = p_first_queue;
488                 }
489                 else
490                 {
491                     DeleteQueue( p_sys->p_first_queue );
492                     p_sys->p_first_queue->i_songs_nb = 0;
493                 }
494                 msg_Dbg( p_this, "Submission successfull!" );
495             }
496             vlc_mutex_unlock ( &p_sys->lock );
497         } /* data transmission finished or skipped */
498
499         msleep( INTF_IDLE_SLEEP );
500
501         p_playlist = pl_Yield( p_this );
502         PL_LOCK;
503         if( p_playlist->request.i_status == PLAYLIST_STOPPED )
504         {
505             /* if we stopped, we won't submit playing song */
506             vlc_mutex_lock( &p_sys->lock );
507             p_sys->b_queued = VLC_TRUE;
508             p_sys->b_metadata_read = VLC_TRUE;
509             vlc_mutex_unlock( &p_sys->lock );
510         }
511         PL_UNLOCK;
512         pl_Release( p_playlist );
513
514         vlc_mutex_lock( &p_sys->lock );
515         if( p_sys->b_metadata_read == VLC_FALSE )
516         {
517             /* we read the metadata of the playing song */
518             time( &played_time );
519             played_time -= p_sys->p_current_song->time_playing;
520             played_time -= p_sys->time_total_pauses;
521
522             vlc_mutex_unlock( &p_sys->lock );
523
524             if( played_time > 20 )
525             /* wait at least 20 secondes before reading the meta data
526              * since the songs must be at least 30s */
527             {
528                 if ( ReadMetaData( p_this ) == VLC_ENOMEM )
529                 {
530                     MEM_ERROR
531                 }
532             }
533         }
534         else
535         {
536             /* we add the playing song into the queue */
537             if( ( p_sys->b_queued == VLC_FALSE )
538                 && ( p_sys->b_paused == VLC_FALSE ) )
539             {
540                 vlc_mutex_unlock( &p_sys->lock );
541                 if( AddToQueue( p_this ) == VLC_ENOMEM )
542                 {
543                     MEM_ERROR
544                 }
545             }
546             else
547             {
548                 vlc_mutex_unlock( &p_sys->lock );
549             }
550         }
551     }
552 #undef MEM_ERROR
553 }
554
555 /*****************************************************************************
556  * PlayingChange: Playing status change callback
557  *****************************************************************************/
558 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
559                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
560 {
561     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
562     intf_sys_t      *p_sys  = p_intf->p_sys;
563
564     (void)p_this; (void)psz_var; (void)oldval;
565
566     /* don't bother if song has already been queued */
567     if( p_sys->b_queued == VLC_TRUE )
568         return VLC_SUCCESS;
569
570     vlc_mutex_lock( &p_sys->lock );
571
572     if( newval.i_int == PAUSE_S )
573     {
574         time( &p_sys->time_pause );
575         p_sys->b_paused = VLC_TRUE;
576     }
577
578     else if( newval.i_int == PLAYING_S )
579     {
580         p_sys->time_total_pauses += time( NULL ) - p_sys->time_pause;
581         p_sys->b_paused = VLC_FALSE;
582     }
583
584     vlc_mutex_unlock( &p_sys->lock );
585
586     return VLC_SUCCESS;
587 }
588
589 /*****************************************************************************
590  * ItemChange: Playlist item change callback
591  *****************************************************************************/
592 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
593                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
594 {
595     playlist_t          *p_playlist;
596     input_thread_t      *p_input    = NULL;
597     time_t              epoch;
598     struct tm           *epoch_tm;
599     char                psz_date[20];
600     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
601     intf_sys_t          *p_sys      = p_intf->p_sys;
602     (void)p_this; (void)psz_var; (void)oldval; (void)newval;
603
604     p_playlist = pl_Yield( p_intf );
605     PL_LOCK;
606     p_input = p_playlist->p_input;
607
608     if( !p_input )
609     {
610         PL_UNLOCK;
611         pl_Release( p_playlist );
612
613         vlc_mutex_lock( &p_sys->lock );
614
615         p_sys->b_queued = VLC_TRUE;
616         p_sys->b_metadata_read = VLC_TRUE;
617
618         vlc_mutex_unlock( &p_sys->lock );
619
620         return VLC_SUCCESS;
621     }
622
623     vlc_object_yield( p_input );
624     PL_UNLOCK;
625     pl_Release( p_playlist );
626
627     var_AddCallback( p_input, "state", PlayingChange, p_intf );
628
629     vlc_mutex_lock ( &p_sys->lock );
630
631     /* reset pause counter */
632     p_sys->time_total_pauses = 0;
633
634     /* we'll read metadata when it's present */
635     p_sys->b_metadata_read = VLC_FALSE;
636     p_sys->b_waiting_meta = VLC_FALSE;
637
638     time( &epoch );
639     epoch_tm = gmtime( &epoch );
640     snprintf( psz_date, 20, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
641         epoch_tm->tm_year+1900, epoch_tm->tm_mon+1, epoch_tm->tm_mday,
642         epoch_tm->tm_hour, epoch_tm->tm_min, epoch_tm->tm_sec );
643
644     p_sys->p_current_song->psz_i = encode_URI_component( psz_date );
645     p_sys->p_current_song->time_playing = epoch;
646
647     char *psz_name = input_item_GetName( input_GetItem( p_input ) );
648     p_sys->b_paused = ( p_input->b_dead || !psz_name )
649                       ? VLC_TRUE : VLC_FALSE;
650     free( psz_name );
651
652     vlc_mutex_unlock( &p_sys->lock );
653
654     vlc_object_release( p_input );
655     return VLC_SUCCESS;
656 }
657
658 /*****************************************************************************
659  * AddToQueue: Add the played song to the queue to be submitted
660  *****************************************************************************/
661 static int AddToQueue ( intf_thread_t *p_this )
662 {
663     int                         i_songs_nb;
664     time_t                      played_time;
665     audioscrobbler_queue_t      *p_queue        = NULL,
666                                 *p_next_queue   = NULL;
667     intf_sys_t                  *p_sys          = p_this->p_sys;
668
669     /* wait for the user to listen enough before submitting */
670     time ( &played_time );
671     vlc_mutex_lock( &p_sys->lock );
672
673     played_time -= p_sys->p_current_song->time_playing;
674     played_time -= p_sys->time_total_pauses;
675
676     #define NO_SUBMISSION \
677         p_sys->b_queued = VLC_TRUE; \
678         vlc_mutex_unlock( &p_sys->lock ); \
679         return VLC_SUCCESS;
680
681     if( ( played_time < 240 ) &&
682         ( played_time < ( p_sys->p_current_song->i_l / 2 ) ) )
683     {
684         //msg_Dbg( p_this, "Song not listened long enough -> waiting" );
685         vlc_mutex_unlock( &p_sys->lock );
686         return VLC_SUCCESS;
687     }
688
689     if( p_sys->p_current_song->i_l < 30 )
690     {
691         msg_Dbg( p_this, "Song too short (< 30s) -> not submitting" );
692         NO_SUBMISSION
693     }
694
695     if( !*p_sys->p_current_song->psz_a || !*p_sys->p_current_song->psz_t )
696     {
697         msg_Dbg( p_this, "Missing artist or title -> not submitting" );
698         NO_SUBMISSION
699     }
700
701     msg_Dbg( p_this, "Ok. We'll put it in the queue for submission" );
702
703     /* go to last queue */
704     p_queue = p_sys->p_first_queue;
705     while( ( p_queue->i_songs_nb == 10 ) && ( p_queue->p_next_queue != NULL ) )
706         p_queue = p_queue->p_next_queue;
707
708     i_songs_nb = p_queue->i_songs_nb;
709
710     #define MALLOC_CHECK( a ) \
711         if( !a ) { \
712             vlc_mutex_unlock( &p_sys->lock ); \
713             return VLC_ENOMEM; \
714         }
715
716     if( i_songs_nb == 10 )
717     {
718         p_next_queue = malloc( sizeof( audioscrobbler_queue_t ) );
719         MALLOC_CHECK( p_next_queue );
720         p_queue->p_next_queue = p_next_queue;
721         p_queue = p_next_queue;
722         i_songs_nb = 0;
723         p_queue->i_songs_nb = i_songs_nb;
724     }
725
726     p_queue->p_queue[i_songs_nb] = malloc( sizeof( audioscrobbler_song_t ) );
727     MALLOC_CHECK( p_queue->p_queue[i_songs_nb] );
728
729     #define QUEUE_COPY( a ) \
730         p_queue->p_queue[i_songs_nb]->a = p_sys->p_current_song->a
731
732     QUEUE_COPY(i_l);
733     QUEUE_COPY(psz_a);
734     QUEUE_COPY(psz_t);
735     QUEUE_COPY(psz_b);
736     QUEUE_COPY(psz_m);
737     QUEUE_COPY(psz_i);
738
739     p_queue->i_songs_nb++;
740     p_sys->b_queued = VLC_TRUE;
741
742     vlc_mutex_unlock( &p_sys->lock );
743
744     return VLC_SUCCESS;
745 #undef QUEUE_COPY
746 #undef MALLOC_CHECK
747 #undef NO_SUBMISSION
748 }
749
750 /*****************************************************************************
751  * Handshake : Init audioscrobbler connection
752  *****************************************************************************/
753 static int Handshake( intf_thread_t *p_this )
754 {
755     char                *psz_password           = NULL;
756     struct md5_s        *p_struct_md5           = NULL;
757     char                *psz_password_md5       = NULL;
758     char                *ps_challenge_md5       = NULL;
759     stream_t            *p_stream;
760     char                *psz_handshake_url      = NULL;
761     uint8_t             *p_buffer               = NULL;
762     char                *p_buffer_pos           = NULL; 
763     char                *psz_url_parser         = NULL;
764     char                *psz_buffer_substring;
765     int                 i_url_pos, i;
766
767     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
768     intf_sys_t          *p_sys                  = p_this->p_sys;
769
770     vlc_mutex_lock ( &p_sys->lock );
771
772     #define MEM_ERROR \
773         free( p_buffer ); \
774         free( p_struct_md5 ); \
775         free( ps_challenge_md5 ); \
776         vlc_mutex_unlock( &p_sys->lock ); \
777         return VLC_ENOMEM;
778
779     #define PROTOCOL_ERROR \
780         free( p_buffer ); \
781         vlc_mutex_unlock( &p_sys->lock ); \
782         return VLC_EGENERIC;
783
784     #define MALLOC_CHECK( a ) \
785         if( !a ) \
786         { \
787             MEM_ERROR \
788         }
789
790     p_sys->psz_username = config_GetPsz(p_this, "lastfm-username");
791     MALLOC_CHECK( p_sys->psz_username )
792
793     /* username has not been setup, ignoring */
794     if ( !*p_sys->psz_username )
795         return VLC_ENOVAR;
796
797     psz_handshake_url = malloc( 1024 );
798     MALLOC_CHECK( p_sys->psz_username )
799
800     snprintf( psz_handshake_url, 1024,
801         "http://post.audioscrobbler.com/?hs=true&p=1.1&c=%s&v=%s&u=%s",
802         CLIENT_NAME, CLIENT_VERSION, p_sys->psz_username );
803
804     /* send the http handshake request */
805     p_stream = stream_UrlNew( p_intf, psz_handshake_url);
806
807     free( psz_handshake_url );
808
809     if( !p_stream )
810     {
811         vlc_mutex_unlock ( &p_sys->lock );
812         return VLC_EGENERIC;
813     }
814
815     p_buffer = ( uint8_t* ) calloc( 1, 1024 );
816     if ( !p_buffer )
817     {
818         stream_Delete( p_stream );
819         MEM_ERROR
820     }
821
822     /* read answer */
823     if ( stream_Read( p_stream, p_buffer, 1024 ) == 0 )
824     {
825         stream_Delete( p_stream );
826         PROTOCOL_ERROR
827     }
828
829     stream_Delete( p_stream );
830
831     /* record interval before next submission */
832     p_buffer_pos = strstr( ( char* ) p_buffer, "INTERVAL" );
833     if ( p_buffer_pos )
834     {
835         time( &p_sys->time_next_exchange );
836         p_sys->time_next_exchange +=
837                 atoi( p_buffer_pos + strlen( "INTERVAL " ) );
838     }
839
840     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED" );
841     if ( p_buffer_pos )
842     {
843         /* handshake request failed, sorry */
844         msg_Dbg( p_this, "%s", p_buffer_pos );
845         PROTOCOL_ERROR
846     }
847
848     p_buffer_pos = strstr( ( char* ) p_buffer, "BADUSER" );
849     if ( p_buffer_pos )
850     {
851         /* username does not exist on the server */
852         intf_UserFatal( p_this, VLC_FALSE, _("Bad last.fm Username"),
853             _("last.fm username is incorrect, please verify your settings")
854         );
855         PROTOCOL_ERROR
856     }
857
858     p_buffer_pos = strstr( ( char* ) p_buffer, "UPDATE" );
859     if ( p_buffer_pos )
860     {
861         /* protocol has been updated, time to update the code */
862         msg_Dbg( p_intf, "Protocol updated : plugin may be outdated" );
863         msg_Dbg( p_intf, "%s", p_buffer_pos );
864     }
865
866     else
867     {
868         p_buffer_pos = strstr( ( char* ) p_buffer, "UPTODATE" );
869         if ( !p_buffer_pos )
870         {
871             msg_Dbg( p_intf, "Can't recognize server protocol" );
872             PROTOCOL_ERROR
873         }
874     }
875
876     psz_buffer_substring = strstr( p_buffer_pos, "\n" );
877     if( ( psz_buffer_substring == NULL ) || \
878             ( strlen( psz_buffer_substring + 1 ) < 32 ) )
879     {
880         msg_Dbg( p_intf, "Can't recognize server protocol" );
881         PROTOCOL_ERROR
882     }
883     else
884     {
885         ps_challenge_md5 = malloc( 32 );
886         MALLOC_CHECK( ps_challenge_md5 )
887         memcpy( ps_challenge_md5, psz_buffer_substring + 1, 32 );
888     }
889
890     p_buffer_pos = ( void* ) strstr( ( char* ) p_buffer, "http://" );
891
892     /* free old information */
893     free( p_sys->psz_submit_host );
894     free( p_sys->psz_submit_file );
895
896     psz_url_parser = p_buffer_pos + strlen( "http://" );
897     i_url_pos = strcspn( psz_url_parser, ":" );
898
899     p_sys->psz_submit_host = strndup( psz_url_parser, i_url_pos );
900     MALLOC_CHECK( p_sys->psz_submit_host )
901
902     p_sys->i_submit_port = atoi( psz_url_parser + i_url_pos + 1 );
903
904     psz_url_parser += strcspn( psz_url_parser , "/" ) + 1;
905     i_url_pos = strcspn( psz_url_parser, "\n" );
906     p_sys->psz_submit_file = strndup( psz_url_parser, i_url_pos );
907     MALLOC_CHECK( p_sys->psz_submit_file )
908
909     free(p_buffer);
910
911     p_struct_md5 = malloc( sizeof( struct md5_s ) );
912     MALLOC_CHECK( p_struct_md5 )
913
914     psz_password = config_GetPsz(p_this, "lastfm-password");
915     MALLOC_CHECK( psz_password )
916
917     /* generates a md5 hash of the password */
918     InitMD5( p_struct_md5 );
919     AddMD5( p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
920     EndMD5( p_struct_md5 );
921
922     free( psz_password );
923
924     psz_password_md5 = malloc ( 33 );
925     MALLOC_CHECK( psz_password_md5 )
926
927     for ( i = 0; i < 4; i++ )
928     {
929         sprintf( &psz_password_md5[8*i], "%02x%02x%02x%02x",
930             p_struct_md5->p_digest[i] & 0xff,
931             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
932             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
933             p_struct_md5->p_digest[i] >> 24
934         );
935     }
936
937     /* generates a md5 hash of :
938      * - md5 hash of the password, plus
939      * - md5 challenge sent by last.fm server
940      */
941     InitMD5( p_struct_md5 );
942     AddMD5( p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
943     AddMD5( p_struct_md5, ( uint8_t* ) ps_challenge_md5, 32 );
944     EndMD5( p_struct_md5 );
945
946     free( ps_challenge_md5 );
947     free( psz_password_md5 );
948
949     for ( i = 0; i < 4; i++ )
950     {
951         sprintf( &p_sys->psz_response_md5[8*i], "%02x%02x%02x%02x",
952             p_struct_md5->p_digest[i] & 0xff,
953             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
954             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
955             p_struct_md5->p_digest[i] >> 24
956         );
957     }
958
959     p_sys->psz_response_md5[32] = '\0';
960
961     vlc_mutex_unlock ( &p_sys->lock );
962
963     return VLC_SUCCESS;
964 #undef MEM_ERROR
965 #undef PROTOCOL_ERROR
966 #undef MALLOC_CHECK
967 }
968
969 /*****************************************************************************
970  * DeleteQueue : Free all songs from an audioscrobbler_queue_t
971  *****************************************************************************/
972 void DeleteQueue( audioscrobbler_queue_t *p_queue )
973 {
974     int     i;
975
976     for( i = 0; i < p_queue->i_songs_nb; i++ )
977     {
978         free( p_queue->p_queue[i]->psz_a );
979         free( p_queue->p_queue[i]->psz_b );
980         free( p_queue->p_queue[i]->psz_t );
981         free( p_queue->p_queue[i]->psz_i );
982         free( p_queue->p_queue[i] );
983     }
984 }
985
986 /*****************************************************************************
987  * ReadMetaData : Read meta data when parsed by vlc
988  * or wait for fetching if unavailable
989  *****************************************************************************/
990 static int ReadMetaData( intf_thread_t *p_this )
991 {
992     playlist_t          *p_playlist;
993     input_thread_t      *p_input        = NULL;
994     vlc_value_t         video_val;
995
996     char                *psz_title      = NULL;
997     char                *psz_artist     = NULL;
998     char                *psz_album      = NULL;
999     char                *psz_trackid    = NULL;
1000     int                 i_length        = -1;
1001     vlc_bool_t          b_waiting;
1002     intf_sys_t          *p_sys          = p_this->p_sys;
1003     int                 i_status;
1004
1005     p_playlist = pl_Yield( p_this );
1006     PL_LOCK;
1007     p_input = p_playlist->p_input;
1008
1009     if( !p_input )
1010     {
1011         PL_UNLOCK;
1012         pl_Release( p_playlist );
1013         return( VLC_SUCCESS );
1014     }
1015
1016     vlc_object_yield( p_input );
1017     PL_UNLOCK;
1018     pl_Release( p_playlist );
1019
1020     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
1021     if( ( video_val.i_int > 0 ) || \
1022         ( input_GetItem( p_input )->i_type == ITEM_TYPE_NET ) )
1023     {
1024         msg_Dbg( p_this, "Not an audio only local file -> no submission");
1025         vlc_object_release( p_input );
1026
1027         vlc_mutex_lock( &p_sys->lock );
1028         p_sys->b_queued = VLC_TRUE;
1029         p_sys->b_metadata_read = VLC_TRUE;
1030         vlc_mutex_unlock( &p_sys->lock );
1031
1032         return VLC_SUCCESS;
1033     }
1034
1035     #define FREE_INPUT_AND_CHARS \
1036         vlc_object_release( p_input ); \
1037         free( psz_title ); \
1038         free( psz_artist ); \
1039         free( psz_album ); \
1040         free( psz_trackid );
1041
1042     #define WAIT_METADATA_FETCHING( a ) \
1043         if ( b_waiting == VLC_TRUE ) \
1044         { \
1045             a = calloc( 1, 1 ); \
1046         } \
1047         else \
1048         { \
1049             vlc_object_release( p_input ); \
1050             vlc_mutex_lock( &p_sys->lock ); \
1051             p_sys->b_waiting_meta = VLC_TRUE; \
1052             vlc_mutex_unlock( &p_sys->lock ); \
1053             free( psz_artist ); \
1054             return VLC_SUCCESS; \
1055         }
1056
1057     char *psz_meta;
1058     #define ALLOC_ITEM_META( a, b ) \
1059         psz_meta = input_item_Get##b( input_GetItem( p_input ) ); \
1060         if( psz_meta ) \
1061         { \
1062             a = encode_URI_component( psz_meta ); \
1063             if( !a ) \
1064             { \
1065                 free( psz_meta ); \
1066                 FREE_INPUT_AND_CHARS \
1067                 return VLC_ENOMEM; \
1068             } \
1069             free( psz_meta ); \
1070         }
1071
1072     i_status = input_GetItem(p_input)->p_meta->i_status;
1073
1074     vlc_mutex_lock( &p_sys->lock );
1075     b_waiting = p_sys->b_waiting_meta;
1076     vlc_mutex_unlock( &p_sys->lock );
1077
1078     if( i_status & ( !b_waiting ? ITEM_PREPARSED : ITEM_META_FETCHED ) )
1079     {
1080         ALLOC_ITEM_META( psz_artist, Artist )
1081         else
1082         {
1083             msg_Dbg( p_this, "No artist.." );
1084             WAIT_METADATA_FETCHING( psz_artist )
1085         }
1086         psz_meta = input_item_GetTitle( input_GetItem( p_input ) );
1087         if( psz_meta )
1088         {
1089             psz_title = encode_URI_component( psz_meta );
1090             if( !psz_title )
1091             {
1092                 free( psz_meta );
1093                 FREE_INPUT_AND_CHARS
1094                 return VLC_ENOMEM;
1095             }
1096             free( psz_meta );
1097         }
1098         else
1099         {
1100             msg_Dbg( p_this, "No track name.." );
1101             WAIT_METADATA_FETCHING( psz_title );
1102         }
1103
1104         ALLOC_ITEM_META( psz_album, Album )
1105         else
1106             psz_album = calloc( 1, 1 );
1107
1108         ALLOC_ITEM_META( psz_trackid, TrackID )
1109         else
1110             psz_trackid = calloc( 1, 1 );
1111
1112         i_length = input_item_GetDuration( input_GetItem( p_input ) ) / 1000000;
1113
1114         vlc_mutex_lock ( &p_sys->lock );
1115
1116         p_sys->p_current_song->psz_a    = strdup( psz_artist );
1117         p_sys->p_current_song->psz_t    = strdup( psz_title );
1118         p_sys->p_current_song->psz_b    = strdup( psz_album );
1119         p_sys->p_current_song->psz_m    = strdup( psz_trackid );
1120         p_sys->p_current_song->i_l      = i_length;
1121         p_sys->b_queued                 = VLC_FALSE;
1122         p_sys->b_metadata_read          = VLC_TRUE;
1123
1124         vlc_mutex_unlock( &p_sys->lock );
1125
1126         msg_Dbg( p_this, "Meta data registered, waiting to be queued" );
1127     }
1128    
1129     FREE_INPUT_AND_CHARS 
1130     return VLC_SUCCESS;
1131 #undef FREE_INPUT_AND_CHARS
1132 #undef ALLOC_ITEM_META
1133 #undef WAIT_METADATA_FETCHING
1134 }