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