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