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