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