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