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