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