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