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