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