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