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