]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
audioscrobbler: *Never* do module unloading from within the module. You are basically...
[vlc] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright © 2006-2008 the VideoLAN team
5  * $Id$
6  *
7  * Author: Rafaël Carré <funman at videolanorg>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /* audioscrobbler protocol version: 1.2
25  * http://www.audioscrobbler.net/development/protocol/
26  *
27  * TODO:    "Now Playing" feature (not mandatory)
28  */
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32
33 #if defined( WIN32 ) 
34 #include <time.h> 
35 #endif 
36
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_interface.h>
44 #include <vlc_meta.h>
45 #include <vlc_md5.h>
46 #include <vlc_block.h>
47 #include <vlc_stream.h>
48 #include <vlc_url.h>
49 #include <vlc_network.h>
50 #include <vlc_interface.h>
51 #include <vlc_playlist.h>
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56
57 #define QUEUE_MAX 50
58
59 /* Keeps track of metadata to be submitted */
60 typedef struct audioscrobbler_song_t
61 {
62     char        *psz_a;             /**< track artist     */
63     char        *psz_t;             /**< track title      */
64     char        *psz_b;             /**< track album      */
65     char        *psz_n;             /**< track number     */
66     int         i_l;                /**< track length     */
67     char        *psz_m;             /**< musicbrainz id   */
68     time_t      date;               /**< date since epoch */
69     mtime_t     i_start;            /**< playing start    */
70 } audioscrobbler_song_t;
71
72 struct intf_sys_t
73 {
74     audioscrobbler_song_t   p_queue[QUEUE_MAX]; /**< songs not submitted yet*/
75     int                     i_songs;            /**< number of songs        */
76
77     vlc_mutex_t             lock;               /**< p_sys mutex            */
78
79     /* data about audioscrobbler session */
80     mtime_t                 next_exchange;      /**< when can we send data  */
81     unsigned int            i_interval;         /**< waiting interval (secs)*/
82
83     /* submission of played songs */
84     char                    *psz_submit_host;   /**< where to submit data   */
85     int                     i_submit_port;      /**< port to which submit   */
86     char                    *psz_submit_file;   /**< file to which submit   */
87
88     /* submission of playing song */
89 #if 0 //NOT USED
90     char                    *psz_nowp_host;     /**< where to submit data   */
91     int                     i_nowp_port;        /**< port to which submit   */
92     char                    *psz_nowp_file;     /**< file to which submit   */
93 #endif
94     bool              b_handshaked;       /**< are we authenticated ? */
95     char                    psz_auth_token[33]; /**< Authentication token */
96
97     /* data about song currently playing */
98     audioscrobbler_song_t   p_current_song;     /**< song being played      */
99
100     mtime_t                 time_pause;         /**< time when vlc paused   */
101     mtime_t                 time_total_pauses;  /**< total time in pause    */
102
103     bool              b_submit;           /**< do we have to submit ? */
104
105     bool              b_state_cb;         /**< if we registered the
106                                                  * "state" callback         */
107
108     bool              b_meta_read;        /**< if we read the song's
109                                                  * metadata already         */
110 };
111
112 static int  Open            ( vlc_object_t * );
113 static void Close           ( vlc_object_t * );
114 static void Run             ( intf_thread_t * );
115
116 static int ItemChange       ( vlc_object_t *, const char *, vlc_value_t,
117                                 vlc_value_t, void * );
118 static int PlayingChange    ( vlc_object_t *, const char *, vlc_value_t,
119                                 vlc_value_t, void * );
120
121 static void AddToQueue      ( intf_thread_t * );
122 static int Handshake        ( intf_thread_t * );
123 static int ReadMetaData     ( intf_thread_t * );
124 static void DeleteSong      ( audioscrobbler_song_t* );
125 static int ParseURL         ( char *, char **, char **, int * );
126 static void HandleInterval  ( mtime_t *, unsigned int * );
127
128 /*****************************************************************************
129  * Module descriptor
130  ****************************************************************************/
131
132 #define USERNAME_TEXT       N_("Username")
133 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
134 #define PASSWORD_TEXT       N_("Password")
135 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
136
137 /* This error value is used when last.fm plugin has to be unloaded. */
138 #define VLC_AUDIOSCROBBLER_EFATAL -69
139
140 /* last.fm client identifier */
141 #define CLIENT_NAME     PACKAGE
142 #define CLIENT_VERSION  VERSION
143
144 /* HTTP POST request : to submit data */
145 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
146                         "Accept-Encoding: identity\n"                       \
147                         "Content-length: %u\n"                              \
148                         "Connection: close\n"                               \
149                         "Content-type: application/x-www-form-urlencoded\n" \
150                         "Host: %s\n"                                        \
151                         "User-agent: VLC Media Player/%s\r\n"               \
152                         "\r\n"                                              \
153                         "%s\r\n"                                            \
154                         "\r\n"
155
156 vlc_module_begin();
157     set_category( CAT_INTERFACE );
158     set_subcategory( SUBCAT_INTERFACE_CONTROL );
159     set_shortname( N_( "Audioscrobbler" ) );
160     set_description( N_("Submission of played songs to last.fm") );
161     add_string( "lastfm-username", "", NULL,
162                 USERNAME_TEXT, USERNAME_LONGTEXT, false );
163     add_password( "lastfm-password", "", NULL,
164                 PASSWORD_TEXT, PASSWORD_LONGTEXT, false );
165     set_capability( "interface", 0 );
166     set_callbacks( Open, Close );
167 vlc_module_end();
168
169 /*****************************************************************************
170  * Open: initialize and create stuff
171  *****************************************************************************/
172 static int Open( vlc_object_t *p_this )
173 {
174     playlist_t      *p_playlist;
175     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
176     intf_sys_t      *p_sys      = calloc( 1, sizeof( intf_sys_t ) );
177
178     if( !p_sys )
179         return VLC_ENOMEM;
180
181     p_intf->p_sys = p_sys;
182
183     vlc_mutex_init( &p_sys->lock );
184
185     p_playlist = pl_Yield( p_intf );
186     PL_LOCK;
187     var_AddCallback( p_playlist, "playlist-current", ItemChange, p_intf );
188     PL_UNLOCK;
189     pl_Release( p_intf );
190
191     p_intf->pf_run = Run;
192
193     return VLC_SUCCESS;
194 }
195
196 /*****************************************************************************
197  * Close: destroy interface stuff
198  *****************************************************************************/
199 static void Close( vlc_object_t *p_this )
200 {
201     playlist_t                  *p_playlist;
202     input_thread_t              *p_input;
203     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
204     intf_sys_t                  *p_sys  = p_intf->p_sys;
205
206     p_playlist = pl_Yield( p_intf );
207     if( p_playlist )
208     {
209         PL_LOCK;
210
211         var_DelCallback( p_playlist, "playlist-current", ItemChange, p_intf );
212
213         p_input = p_playlist->p_input;
214         if ( p_input )
215         {
216             vlc_object_yield( p_input );
217
218             if( p_sys->b_state_cb )
219                 var_DelCallback( p_input, "state", PlayingChange, p_intf );
220
221             vlc_object_release( p_input );
222         }
223
224         PL_UNLOCK;
225         pl_Release( p_intf );
226     }
227
228     p_intf->b_dead = true;
229     /* we lock the mutex in case p_sys is being accessed from a callback */
230     vlc_mutex_lock ( &p_sys->lock );
231     int i;
232     for( i = 0; i < p_sys->i_songs; i++ )
233         DeleteSong( &p_sys->p_queue[i] );
234     free( p_sys->psz_submit_host );
235     free( p_sys->psz_submit_file );
236 #if 0 //NOT USED
237     free( p_sys->psz_nowp_host );
238     free( p_sys->psz_nowp_file );
239 #endif
240     vlc_mutex_unlock ( &p_sys->lock );
241     vlc_mutex_destroy( &p_sys->lock );
242     free( p_sys );
243 }
244
245
246 /*****************************************************************************
247  * Run : call Handshake() then submit songs
248  *****************************************************************************/
249 static void Run( intf_thread_t *p_intf )
250 {
251     char                    *psz_submit, *psz_submit_song, *psz_submit_tmp;
252     int                     i_net_ret;
253     int                     i_song;
254     uint8_t                 p_buffer[1024];
255     char                    *p_buffer_pos;
256     int                     i_post_socket;
257
258     intf_sys_t *p_sys = p_intf->p_sys;
259
260     /* main loop */
261     for( ;; )
262     {
263         bool b_wait = false;
264
265         vlc_object_lock( p_intf );
266         if( !vlc_object_alive( p_intf ) )
267         {
268             vlc_object_unlock( p_intf );
269             msg_Dbg( p_intf, "audioscrobbler is dying");
270             return;
271         }
272         if( mdate() < p_sys->next_exchange )
273             /* wait until we can resubmit, i.e.  */
274             b_wait = vlc_object_timedwait( p_intf, p_sys->next_exchange ) == 0;
275         else
276             /* wait for data to submit */
277             /* we are signaled each time there is a song to submit */
278             vlc_object_wait( p_intf );
279         vlc_object_unlock( p_intf );
280
281         if( b_wait )
282             continue; /* holding on until next_exchange */
283
284         /* handshake if needed */
285         if( p_sys->b_handshaked == false )
286         {
287             msg_Dbg( p_intf, "Handshaking with last.fm ..." );
288
289             switch( Handshake( p_intf ) )
290             {
291                 case VLC_ENOMEM:
292                     return;
293
294                 case VLC_ENOVAR:
295                     /* username not set */
296                     intf_UserFatal( p_intf, false,
297                         _("Last.fm username not set"),
298                         _("Please set a username or disable the "
299                         "audioscrobbler plugin, and restart VLC.\n"
300                         "Visit http://www.last.fm/join/ to get an account.")
301                     );
302                     return;
303
304                 case VLC_SUCCESS:
305                     msg_Dbg( p_intf, "Handshake successfull :)" );
306                     p_sys->b_handshaked = true;
307                     p_sys->i_interval = 0;
308                     p_sys->next_exchange = mdate();
309                     break;
310
311                 case VLC_AUDIOSCROBBLER_EFATAL:
312                     msg_Warn( p_intf, "Exiting..." );
313                     return;
314
315                 case VLC_EGENERIC:
316                 default:
317                     /* protocol error : we'll try later */
318                     HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
319                     break;
320             }
321             /* if handshake failed let's restart the loop */
322             if( p_sys->b_handshaked == false )
323                 continue;
324         }
325
326         msg_Dbg( p_intf, "Going to submit some data..." );
327
328         if( !asprintf( &psz_submit, "s=%s", p_sys->psz_auth_token ) )
329         {   /* Out of memory */
330             return;
331         }
332
333         /* forge the HTTP POST request */
334         vlc_mutex_lock( &p_sys->lock );
335         audioscrobbler_song_t *p_song;
336         for( i_song = 0 ; i_song < p_sys->i_songs ; i_song++ )
337         {
338             p_song = &p_sys->p_queue[i_song];
339             if( !asprintf( &psz_submit_song,
340                     "&a%%5B%d%%5D=%s&t%%5B%d%%5D=%s"
341                     "&i%%5B%d%%5D=%ju&o%%5B%d%%5D=P&r%%5B%d%%5D="
342                     "&l%%5B%d%%5D=%d&b%%5B%d%%5D=%s"
343                     "&n%%5B%d%%5D=%s&m%%5B%d%%5D=%s",
344                     i_song, p_song->psz_a,           i_song, p_song->psz_t,
345                     i_song, (uintmax_t)p_song->date, i_song, i_song,
346                     i_song, p_song->i_l,             i_song, p_song->psz_b,
347                     i_song, p_song->psz_n,           i_song, p_song->psz_m
348             ) )
349             {   /* Out of memory */
350                 vlc_mutex_unlock( &p_sys->lock );
351                 return;
352             }
353             psz_submit_tmp = psz_submit;
354             if( !asprintf( &psz_submit, "%s%s",
355                     psz_submit_tmp, psz_submit_song ) )
356             {   /* Out of memory */
357                 free( psz_submit_tmp );
358                 free( psz_submit_song );
359                 vlc_mutex_unlock( &p_sys->lock );
360                 return;
361             }
362             free( psz_submit_song );
363             free( psz_submit_tmp );
364         }
365         vlc_mutex_unlock( &p_sys->lock );
366
367         i_post_socket = net_ConnectTCP( p_intf,
368             p_sys->psz_submit_host, p_sys->i_submit_port );
369
370         if ( i_post_socket == -1 )
371         {
372             /* If connection fails, we assume we must handshake again */
373             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
374             p_sys->b_handshaked = false;
375             free( psz_submit );
376             continue;
377         }
378
379         /* we transmit the data */
380         i_net_ret = net_Printf(
381             VLC_OBJECT( p_intf ), i_post_socket, NULL,
382             POST_REQUEST, p_sys->psz_submit_file,
383             (unsigned)strlen( psz_submit ), p_sys->psz_submit_file,
384             VERSION, psz_submit
385         );
386
387         free( psz_submit );
388         if ( i_net_ret == -1 )
389         {
390             /* If connection fails, we assume we must handshake again */
391             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
392             p_sys->b_handshaked = false;
393             continue;
394         }
395
396         i_net_ret = net_Read( p_intf, i_post_socket, NULL,
397                     p_buffer, 1023, false );
398         if ( i_net_ret <= 0 )
399         {
400             /* if we get no answer, something went wrong : try again */
401             continue;
402         }
403
404         net_Close( i_post_socket );
405         p_buffer[i_net_ret] = '\0';
406
407         p_buffer_pos = strstr( ( char * ) p_buffer, "FAILED" );
408         if ( p_buffer_pos )
409         {
410             msg_Warn( p_intf, "%s", p_buffer_pos );
411             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
412             continue;
413         }
414
415         p_buffer_pos = strstr( ( char * ) p_buffer, "BADSESSION" );
416         if ( p_buffer_pos )
417         {
418             msg_Err( p_intf, "Authentication failed (BADSESSION), are you connected to last.fm with another program ?" );
419             p_sys->b_handshaked = false;
420             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
421             continue;
422         }
423
424         p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
425         if ( p_buffer_pos )
426         {
427             int i;
428             for( i = 0; i < p_sys->i_songs; i++ )
429                 DeleteSong( &p_sys->p_queue[i] );
430             p_sys->i_songs = 0;
431             p_sys->i_interval = 0;
432             p_sys->next_exchange = mdate();
433             msg_Dbg( p_intf, "Submission successful!" );
434         }
435         else
436         {
437             msg_Err( p_intf, "Authentication failed, handshaking again (%s)", 
438                              p_buffer );
439             p_sys->b_handshaked = false;
440             HandleInterval( &p_sys->next_exchange, &p_sys->i_interval );
441             continue;
442         }
443     }
444 }
445
446 /*****************************************************************************
447  * PlayingChange: Playing status change callback
448  *****************************************************************************/
449 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
450                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
451 {
452     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
453     intf_sys_t      *p_sys  = p_intf->p_sys;
454
455     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
456
457     if( p_intf->b_dead )
458         return VLC_SUCCESS;
459
460     if( p_sys->b_meta_read == false && newval.i_int >= PLAYING_S )
461     {
462         ReadMetaData( p_intf );
463         return VLC_SUCCESS;
464     }
465
466     if( newval.i_int >= END_S )
467         AddToQueue( p_intf );
468     else if( oldval.i_int == PLAYING_S && newval.i_int == PAUSE_S )
469         p_sys->time_pause = mdate();
470     else if( oldval.i_int == PAUSE_S && newval.i_int == PLAYING_S )
471         p_sys->time_total_pauses += ( mdate() - p_sys->time_pause );
472
473     return VLC_SUCCESS;
474 }
475
476 /*****************************************************************************
477  * ItemChange: Playlist item change callback
478  *****************************************************************************/
479 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
480                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
481 {
482     playlist_t          *p_playlist;
483     input_thread_t      *p_input;
484     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
485     intf_sys_t          *p_sys      = p_intf->p_sys;
486     input_item_t        *p_item;
487     vlc_value_t         video_val;
488
489     VLC_UNUSED( p_this ); VLC_UNUSED( psz_var );
490     VLC_UNUSED( oldval ); VLC_UNUSED( newval );
491
492     if( p_intf->b_dead )
493         return VLC_SUCCESS;
494
495     p_sys->b_state_cb       = false;
496     p_sys->b_meta_read      = false;
497     p_sys->b_submit         = false;
498
499     p_playlist = pl_Yield( p_intf );
500     PL_LOCK;
501     p_input = p_playlist->p_input;
502
503     if( !p_input || p_input->b_dead )
504     {
505         PL_UNLOCK;
506         pl_Release( p_intf );
507         return VLC_SUCCESS;
508     }
509
510     vlc_object_yield( p_input );
511     PL_UNLOCK;
512     pl_Release( p_intf );
513
514     p_item = input_GetItem( p_input );
515     if( !p_item )
516     {
517         vlc_object_release( p_input );
518         return VLC_SUCCESS;
519     }
520
521     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
522     if( ( video_val.i_int > 0 ) || p_item->i_type == ITEM_TYPE_NET )
523     {
524         msg_Dbg( p_this, "Not an audio local file, not submitting");
525         vlc_object_release( p_input );
526         return VLC_SUCCESS;
527     }
528
529     p_sys->time_total_pauses = 0;
530     time( &p_sys->p_current_song.date );        /* to be sent to last.fm */
531     p_sys->p_current_song.i_start = mdate();    /* only used locally */
532
533     var_AddCallback( p_input, "state", PlayingChange, p_intf );
534     p_sys->b_state_cb = true;
535
536     if( input_item_IsPreparsed( p_item ) )
537         ReadMetaData( p_intf );
538     /* if the input item was not preparsed, we'll do it in PlayingChange()
539      * callback, when "state" == PLAYING_S */
540
541     vlc_object_release( p_input );
542     return VLC_SUCCESS;
543 }
544
545 /*****************************************************************************
546  * AddToQueue: Add the played song to the queue to be submitted
547  *****************************************************************************/
548 static void AddToQueue ( intf_thread_t *p_this )
549 {
550     mtime_t                     played_time;
551     intf_sys_t                  *p_sys = p_this->p_sys;
552
553     vlc_mutex_lock( &p_sys->lock );
554     if( !p_sys->b_submit )
555         goto end;
556
557     /* wait for the user to listen enough before submitting */
558     played_time = mdate() - p_sys->p_current_song.i_start -
559                             p_sys->time_total_pauses;
560     played_time /= 1000000; /* µs → s */
561
562     if( ( played_time < 240 ) &&
563         ( played_time < ( p_sys->p_current_song.i_l / 2 ) ) )
564     {
565         msg_Dbg( p_this, "Song not listened long enough, not submitting" );
566         goto end;
567     }
568
569     if( p_sys->p_current_song.i_l < 30 )
570     {
571         msg_Dbg( p_this, "Song too short (< 30s), not submitting" );
572         goto end;
573     }
574
575     if( !p_sys->p_current_song.psz_a || !*p_sys->p_current_song.psz_a ||
576         !p_sys->p_current_song.psz_t || !*p_sys->p_current_song.psz_t )
577     {
578         msg_Dbg( p_this, "Missing artist or title, not submitting" );
579 /*XXX*/        msg_Dbg( p_this, "%s %s", p_sys->p_current_song.psz_a, p_sys->p_current_song.psz_t );
580         goto end;
581     }
582
583     if( p_sys->i_songs >= QUEUE_MAX )
584     {
585         msg_Warn( p_this, "Submission queue is full, not submitting" );
586         goto end;
587     }
588
589     msg_Dbg( p_this, "Song will be submitted." );
590
591 #define QUEUE_COPY( a ) \
592     p_sys->p_queue[p_sys->i_songs].a = p_sys->p_current_song.a
593
594 #define QUEUE_COPY_NULL( a ) \
595     QUEUE_COPY( a ); \
596     p_sys->p_current_song.a = NULL
597
598     QUEUE_COPY( i_l );
599     QUEUE_COPY_NULL( psz_n );
600     QUEUE_COPY_NULL( psz_a );
601     QUEUE_COPY_NULL( psz_t );
602     QUEUE_COPY_NULL( psz_b );
603     QUEUE_COPY_NULL( psz_m );
604     QUEUE_COPY( date );
605 #undef QUEUE_COPY_NULL
606 #undef QUEUE_COPY
607
608     p_sys->i_songs++;
609
610     /* signal the main loop we have something to submit */
611     vlc_object_signal( VLC_OBJECT( p_this ) );
612
613 end:
614     DeleteSong( &p_sys->p_current_song );
615     p_sys->b_submit = false;
616     vlc_mutex_unlock( &p_sys->lock );
617 }
618
619 /*****************************************************************************
620  * ParseURL : Split an http:// URL into host, file, and port
621  *
622  * Example: "62.216.251.205:80/protocol_1.2"
623  *      will be split into "62.216.251.205", 80, "protocol_1.2"
624  *
625  * psz_url will be freed before returning
626  * *psz_file & *psz_host will be freed before use
627  *
628  * Return value:
629  *  VLC_ENOMEM      Out Of Memory
630  *  VLC_EGENERIC    Invalid url provided
631  *  VLC_SUCCESS     Success
632  *****************************************************************************/
633 static int ParseURL( char *psz_url, char **psz_host, char **psz_file,
634                         int *i_port )
635 {
636     int i_pos;
637     int i_len = strlen( psz_url );
638     FREENULL( *psz_host );
639     FREENULL( *psz_file );
640
641     i_pos = strcspn( psz_url, ":" );
642     if( i_pos == i_len )
643         return VLC_EGENERIC;
644
645     *psz_host = strndup( psz_url, i_pos );
646     if( !*psz_host )
647         return VLC_ENOMEM;
648
649     i_pos++; /* skip the ':' */
650     *i_port = atoi( psz_url + i_pos );
651     if( *i_port <= 0 )
652     {
653         FREENULL( *psz_host );
654         return VLC_EGENERIC;
655     }
656
657     i_pos = strcspn( psz_url, "/" );
658
659     if( i_pos == i_len )
660         return VLC_EGENERIC;
661
662     i_pos++; /* skip the '/' */
663     *psz_file = strdup( psz_url + i_pos );
664     if( !*psz_file )
665     {
666         FREENULL( *psz_host );
667         return VLC_ENOMEM;
668     }
669
670     free( psz_url );
671     return VLC_SUCCESS;
672 }
673
674 /*****************************************************************************
675  * Handshake : Init audioscrobbler connection
676  *****************************************************************************/
677 static int Handshake( intf_thread_t *p_this )
678 {
679     char                *psz_username, *psz_password;
680     time_t              timestamp;
681     char                psz_timestamp[21];
682
683     struct md5_s        p_struct_md5;
684
685     stream_t            *p_stream;
686     char                *psz_handshake_url;
687     uint8_t             p_buffer[1024];
688     char                *p_buffer_pos;
689
690     int                 i_ret;
691     char                *psz_url;
692
693     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
694     intf_sys_t          *p_sys                  = p_this->p_sys;
695
696     psz_username = config_GetPsz( p_this, "lastfm-username" );
697     if( !psz_username )
698         return VLC_ENOMEM;
699
700     psz_password = config_GetPsz( p_this, "lastfm-password" );
701     if( !psz_password )
702     {
703         free( psz_username );
704         return VLC_ENOMEM;
705     }
706
707     /* username or password have not been setup */
708     if ( !*psz_username || !*psz_password )
709     {
710         free( psz_username );
711         free( psz_password );
712         return VLC_ENOVAR;
713     }
714
715     time( &timestamp );
716
717     /* generates a md5 hash of the password */
718     InitMD5( &p_struct_md5 );
719     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
720     EndMD5( &p_struct_md5 );
721
722     free( psz_password );
723
724     char *psz_password_md5 = psz_md5_hash( &p_struct_md5 );
725     if( !psz_password_md5 )
726     {
727         free( psz_username );
728         return VLC_ENOMEM;
729     }
730
731     snprintf( psz_timestamp, sizeof( psz_timestamp ), "%"PRIu64,
732               (uint64_t)timestamp );
733
734     /* generates a md5 hash of :
735      * - md5 hash of the password, plus
736      * - timestamp in clear text
737      */
738     InitMD5( &p_struct_md5 );
739     AddMD5( &p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
740     AddMD5( &p_struct_md5, ( uint8_t* ) psz_timestamp, strlen( psz_timestamp ));
741     EndMD5( &p_struct_md5 );
742     free( psz_password_md5 );
743
744     char *psz_auth_token = psz_md5_hash( &p_struct_md5 );
745     if( !psz_auth_token )
746     {
747         free( psz_username );
748         return VLC_ENOMEM;
749     }
750     strncpy( p_sys->psz_auth_token, psz_auth_token, 33 );
751     free( psz_auth_token );
752
753     if( !asprintf( &psz_handshake_url,
754     "http://post.audioscrobbler.com/?hs=true&p=1.2&c=%s&v=%s&u=%s&t=%s&a=%s",
755         CLIENT_NAME, CLIENT_VERSION, psz_username, psz_timestamp,
756         p_sys->psz_auth_token ) )
757     {
758         free( psz_username );
759         return VLC_ENOMEM;
760     }
761     free( psz_username );
762
763     /* send the http handshake request */
764     p_stream = stream_UrlNew( p_intf, psz_handshake_url );
765     free( psz_handshake_url );
766
767     if( !p_stream )
768         return VLC_EGENERIC;
769
770     /* read answer */
771     i_ret = stream_Read( p_stream, p_buffer, 1023 );
772     if( i_ret == 0 )
773     {
774         stream_Delete( p_stream );
775         return VLC_EGENERIC;
776     }
777     p_buffer[i_ret] = '\0';
778     stream_Delete( p_stream );
779
780     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED " );
781     if ( p_buffer_pos )
782     {
783         /* handshake request failed, sorry */
784         msg_Err( p_this, "last.fm handshake failed: %s", p_buffer_pos + 7 );
785         return VLC_EGENERIC;
786     }
787
788     p_buffer_pos = strstr( ( char* ) p_buffer, "BADAUTH" );
789     if ( p_buffer_pos )
790     {
791         /* authentication failed, bad username/password combination */
792         intf_UserFatal( p_this, false,
793             _("last.fm: Authentication failed"),
794             _("last.fm username or password is incorrect. "
795               "Please verify your settings and relaunch VLC." ) );
796         return VLC_AUDIOSCROBBLER_EFATAL;
797     }
798
799     p_buffer_pos = strstr( ( char* ) p_buffer, "BANNED" );
800     if ( p_buffer_pos )
801     {
802         /* oops, our version of vlc has been banned by last.fm servers */
803         msg_Err( p_intf, "This version of VLC has been banned by last.fm. "
804                          "You should upgrade VLC, or disable the last.fm plugin." );
805         return VLC_AUDIOSCROBBLER_EFATAL;
806     }
807
808     p_buffer_pos = strstr( ( char* ) p_buffer, "BADTIME" );
809     if ( p_buffer_pos )
810     {
811         /* The system clock isn't good */
812         msg_Err( p_intf, "last.fm handshake failed because your clock is too "
813                          "much shifted. Please correct it, and relaunch VLC." );
814         return VLC_AUDIOSCROBBLER_EFATAL;
815     }
816
817     p_buffer_pos = strstr( ( char* ) p_buffer, "OK" );
818     if ( !p_buffer_pos )
819         goto proto;
820
821     p_buffer_pos = strstr( p_buffer_pos, "\n" );
822     if( !p_buffer_pos || strlen( p_buffer_pos ) < 34 )
823         goto proto;
824     p_buffer_pos++; /* we skip the '\n' */
825
826     /* save the session ID */
827     snprintf( p_sys->psz_auth_token, 33, "%s", p_buffer_pos );
828
829     p_buffer_pos = strstr( p_buffer_pos, "http://" );
830     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
831         goto proto;
832
833     /* We need to read the nowplaying url */
834     p_buffer_pos += 7; /* we skip "http://" */
835 #if 0 //NOT USED
836     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
837     if( !psz_url )
838         goto oom;
839
840     switch( ParseURL( psz_url, &p_sys->psz_nowp_host,
841                 &p_sys->psz_nowp_file, &p_sys->i_nowp_port ) )
842     {
843         case VLC_ENOMEM:
844             goto oom;
845         case VLC_EGENERIC:
846             goto proto;
847         case VLC_SUCCESS:
848         default:
849             break;
850     }
851 #endif
852     p_buffer_pos = strstr( p_buffer_pos, "http://" );
853     if( !p_buffer_pos || strlen( p_buffer_pos ) == 7 )
854         goto proto;
855
856     /* We need to read the submission url */
857     p_buffer_pos += 7; /* we skip "http://" */
858     psz_url = strndup( p_buffer_pos, strcspn( p_buffer_pos, "\n" ) );
859     if( !psz_url )
860         goto oom;
861
862     switch( ParseURL( psz_url, &p_sys->psz_submit_host,
863                 &p_sys->psz_submit_file, &p_sys->i_submit_port ) )
864     {
865         case VLC_ENOMEM:
866             goto oom;
867         case VLC_EGENERIC:
868             goto proto;
869         case VLC_SUCCESS:
870         default:
871             break;
872     }
873
874     return VLC_SUCCESS;
875
876 oom:
877     return VLC_ENOMEM;
878
879 proto:
880     msg_Err( p_intf, "Handshake: can't recognize server protocol" );
881     return VLC_EGENERIC;
882 }
883
884 /*****************************************************************************
885  * DeleteSong : Delete the char pointers in a song
886  *****************************************************************************/
887 static void DeleteSong( audioscrobbler_song_t* p_song )
888 {
889     FREENULL( p_song->psz_a );
890     FREENULL( p_song->psz_b );
891     FREENULL( p_song->psz_t );
892     FREENULL( p_song->psz_m );
893     FREENULL( p_song->psz_n );
894 }
895
896 /*****************************************************************************
897  * ReadMetaData : Read meta data when parsed by vlc
898  *****************************************************************************/
899 static int ReadMetaData( intf_thread_t *p_this )
900 {
901     playlist_t          *p_playlist;
902     input_thread_t      *p_input;
903     input_item_t        *p_item;
904
905     intf_sys_t          *p_sys = p_this->p_sys;
906
907     p_playlist = pl_Yield( p_this );
908     PL_LOCK;
909     p_input = p_playlist->p_input;
910     if( !p_input )
911     {
912         PL_UNLOCK;
913         pl_Release( p_this );
914         return( VLC_SUCCESS );
915     }
916
917     vlc_object_yield( p_input );
918     PL_UNLOCK;
919     pl_Release( p_this );
920
921     p_item = input_GetItem( p_input );
922     if( !p_item )
923         return VLC_SUCCESS;
924
925     char *psz_meta;
926 #define ALLOC_ITEM_META( a, b ) \
927     psz_meta = input_item_Get##b( p_item ); \
928     if( psz_meta && *psz_meta ) \
929     { \
930         a = encode_URI_component( psz_meta ); \
931         if( !a ) \
932         { \
933             free( psz_meta ); \
934             return VLC_ENOMEM; \
935         } \
936     }
937
938     vlc_mutex_lock( &p_sys->lock );
939
940     p_sys->b_meta_read = true;
941
942     ALLOC_ITEM_META( p_sys->p_current_song.psz_a, Artist )
943     else
944     {
945         vlc_mutex_unlock( &p_sys->lock );
946         msg_Dbg( p_this, "No artist.." );
947         vlc_object_release( p_input );
948         free( psz_meta );
949         return VLC_EGENERIC;
950     }
951     free( psz_meta );
952
953     ALLOC_ITEM_META( p_sys->p_current_song.psz_t, Title )
954     else
955     {
956         vlc_mutex_unlock( &p_sys->lock );
957         msg_Dbg( p_this, "No track name.." );
958         vlc_object_release( p_input );
959         free( p_sys->p_current_song.psz_a );
960         free( psz_meta );
961         return VLC_EGENERIC;
962     }
963     free( psz_meta );
964
965     /* Now we have read the mandatory meta data, so we can submit that info */
966     p_sys->b_submit = true;
967
968     ALLOC_ITEM_META( p_sys->p_current_song.psz_b, Album )
969     else
970         p_sys->p_current_song.psz_b = calloc( 1, 1 );
971     free( psz_meta );
972
973     ALLOC_ITEM_META( p_sys->p_current_song.psz_m, TrackID )
974     else
975         p_sys->p_current_song.psz_m = calloc( 1, 1 );
976     free( psz_meta );
977
978     p_sys->p_current_song.i_l = input_item_GetDuration( p_item ) / 1000000;
979
980     ALLOC_ITEM_META( p_sys->p_current_song.psz_n, TrackNum )
981     else
982         p_sys->p_current_song.psz_n = calloc( 1, 1 );
983     free( psz_meta );
984 #undef ALLOC_ITEM_META
985
986     msg_Dbg( p_this, "Meta data registered" );
987
988     vlc_mutex_unlock( &p_sys->lock );
989     vlc_object_release( p_input );
990     return VLC_SUCCESS;
991
992 }
993
994 static void HandleInterval( mtime_t *next, unsigned int *i_interval )
995 {
996     if( *i_interval == 0 )
997     {
998         /* first interval is 1 minute */
999         *i_interval = 1;
1000     }
1001     else
1002     {
1003         /* else we double the previous interval, up to 120 minutes */
1004         *i_interval <<= 1;
1005         if( *i_interval > 120 )
1006             *i_interval = 120;
1007     }
1008     *next = mdate() + ( *i_interval * 1000000 * 60 );
1009 }
1010