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