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