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