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