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