summaryrefslogtreecommitdiff
path: root/plugins/lastfm/lastfm.c
blob: 15c9508ee70e0f663033c3f1fd1d55425a4f3471 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/*
    DeaDBeeF - ultimate music player for GNU/Linux systems with X11
    Copyright (C) 2009  Alexey Yakovenko

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include "../../deadbeef.h"

#define TESTMODE 1

static DB_misc_t plugin;
static DB_functions_t *deadbeef;

#define LFM_CLIENTID "ddb"
#define LFM_MAJORVER 0
#define LFM_MINORVER 1
#define SCROBBLER_URL_V1 "http://post.audioscrobbler.com"
#define SCROBBLER_URL_V2 "http://ws.audioscrobbler.com/2.0"
#define LFM_API_KEY "6b33c8ae4d598a9aff8fe63e334e6e86"
#define LFM_API_SECRET "a9f5e17e358377d96e96477d870b2b18"

static char lfm_user[100];
static char lfm_pass[100];

static char lfm_sess[33];
static char lfm_nowplaying_url[256];
static char lfm_submission_url[256];

static uintptr_t lfm_mutex;
static uintptr_t lfm_cond;
static int lfm_stopthread;

DB_plugin_t *
lastfm_load (DB_functions_t *api) {
    deadbeef = api;
    return DB_PLUGIN (&plugin);
}

#define MAX_REPLY 4096
static char lfm_reply[MAX_REPLY];
static char lfm_reply_sz;
static char lfm_err[CURL_ERROR_SIZE];

#define LFM_SUBMISSION_QUEUE_SIZE 5
static char lfm_nowplaying[2048]; // packet for nowplaying, or ""
static char lfm_subm_queue[LFM_SUBMISSION_QUEUE_SIZE][2048];

static size_t
lastfm_curl_res (void *ptr, size_t size, size_t nmemb, void *stream)
{
    int len = size * nmemb;
    if (lfm_reply_sz + len >= MAX_REPLY) {
        fprintf (stderr, "reply is too large. stopping.\n");
        return 0;
    }
    memcpy (lfm_reply + lfm_reply_sz, ptr, len);
    lfm_reply_sz += len;
//    char s[size*nmemb+1];
//    memcpy (s, ptr, size*nmemb);
//    s[size*nmemb] = 0;
//    fprintf (stderr, "got from net: %s\n", s);
    return len;
}

static int
curl_req_send (const char *req, const char *post) {
    fprintf (stderr, "sending request: %s\n", req);
    CURL *curl;
    curl = curl_easy_init ();
    if (!curl) {
        fprintf (stderr, "lastfm: failed to init curl\n");
        return -1;
    }
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
    curl_easy_setopt(curl, CURLOPT_URL, req);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, lastfm_curl_res);
    memset(lfm_err, 0, sizeof(lfm_err));
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, lfm_err);
    curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    if (post) {
        curl_easy_setopt(curl, CURLOPT_POST, 1);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(post));
    }
    int status = curl_easy_perform(curl);
    curl_easy_cleanup (curl);
    if (!status) {
        lfm_reply[lfm_reply_sz] = 0;
    }
    if (status != 0) {
        fprintf (stderr, "curl request failed, err:\n%s\n", lfm_err);
    }
    return status;
}

static void
curl_req_cleanup (void) {
    lfm_reply_sz = 0;
}

int
auth (void) {
    if (lfm_sess[0]) {
        return 0;
    }
    char req[4096];
    time_t timestamp = time(0);
    uint8_t sig[16];
    char passmd5[33];
    char token[100];
    deadbeef->md5 (sig, lfm_pass, strlen (lfm_pass));
    deadbeef->md5_to_str (passmd5, sig);
    snprintf (token, sizeof (token), "%s%d", passmd5, timestamp);
    deadbeef->md5 (sig, token, strlen (token));
    deadbeef->md5_to_str (token, sig);

#if TESTMODE
    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=tst&v=1.0&u=%s&t=%d&a=%s", SCROBBLER_URL_V1, lfm_user, timestamp, token);
#else
    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=%s&v=%d.%d&u=%s&t=%d&a=%s", SCROBBLER_URL_V1, LFM_CLIENTID, LFM_MAJORVER, LFM_MINORVER, lfm_user, timestamp, token);
#endif
    // handshake
    int status = curl_req_send (req, NULL);
    if (!status) {
        // check status and extract session id, nowplaying url, submission url
        if (strncmp (lfm_reply, "OK", 2)) {
            uint8_t *p = lfm_reply;
            while (*p && *p >= 0x20) {
                p++;
            }
            *p = 0;
            fprintf (stderr, "scrobbler auth failed, response: %s\n", lfm_reply);
            goto fail;
        }
        uint8_t *p = lfm_reply + 2;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get session
        if (!*p) {
            fprintf (stderr, "unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        uint8_t *end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end-p > 32) {
            fprintf (stderr, "scrobbler session id is invalid length. probably plugin needs fixing.\n");
            goto fail;
        }
        strncpy (lfm_sess, p, 32);
        lfm_sess[32] = 0;
        fprintf (stderr, "obtained scrobbler session: %s\n", lfm_sess);
        p = end;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get nowplaying url
        if (!*p) {
            fprintf (stderr, "unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end - p > sizeof (lfm_nowplaying_url)-1) {
            fprintf (stderr, "scrobbler nowplaying url is too long:\n", lfm_reply);
            goto fail;
        }
        strncpy (lfm_nowplaying_url, p, end-p);
        lfm_nowplaying_url[end-p] = 0;
        fprintf (stderr, "obtained scrobbler nowplaying url: %s\n", lfm_nowplaying_url);
        p = end;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get submission url
        if (!*p) {
            fprintf (stderr, "unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end - p > sizeof (lfm_submission_url)-1) {
            fprintf (stderr, "scrobbler submission url is too long:\n", lfm_reply);
            goto fail;
        }
        strncpy (lfm_submission_url, p, end-p);
        lfm_submission_url[end-p] = 0;
        fprintf (stderr, "obtained scrobbler submission url: %s\n", lfm_submission_url);
        p = end;
    }

    curl_req_cleanup ();
    return 0;
fail:
    lfm_sess[0] = 0;
    curl_req_cleanup ();
    return -1;
}

static int
lfm_fetch_song_info (DB_playItem_t *song, const char **a, const char **t, const char **b, float *l, const char **n, const char **m) {
    *a = deadbeef->pl_find_meta (song, "artist");
    if (!strcmp (*a, "?")) {
        return -1;
    }
    *t = deadbeef->pl_find_meta (song, "title");
    if (!strcmp (*t, "?")) {
        return -1;
    }
    *b = deadbeef->pl_find_meta (song, "album");
    if (!strcmp (*b, "?")) {
        return -1;
    }
    *l = song->duration;
    *n = deadbeef->pl_find_meta (song, "track");
    if (!strcmp (*n, "?")) {
        *n = "";
    }
    *m = deadbeef->pl_find_meta (song, "mbid");
    if (!strcmp (*m, "?")) {
        *m = "";
    }
    return 0;
}

static int
lastfm_songstarted (DB_event_song_t *ev, uintptr_t data) {
    fprintf (stderr, "song started, info:\n");
    const char *a; // artist
    const char *t; // title
    const char *b; // album
    float l; // duration
    const char *n; // tracknum
    const char *m; // muzicbrainz id
    if (lfm_fetch_song_info (ev->song, &a, &t, &b, &l, &n, &m) == 0) {
        fprintf (stderr, "playtime: %f\nartist: %s\ntitle: %s\nalbum: %s\nduration: %f\ntracknum: %s\n---\n", ev->song->playtime, a, t, b, l, n);
    }
    else {
        fprintf (stderr, "file %s doesn't have enough tags to submit to last.fm\n", ev->song->fname);
        return 0;
    }

    deadbeef->mutex_lock (lfm_mutex);
    snprintf (lfm_nowplaying, sizeof (lfm_nowplaying), "a=%s&t=%s&b=%s&l=%d&n=%s&m=%s", a, t, b, (int)l, n, m);
    deadbeef->mutex_unlock (lfm_mutex);
    deadbeef->cond_signal (lfm_cond);

    return 0;
}

static int
lastfm_songfinished (DB_event_song_t *ev, uintptr_t data) {
    fprintf (stderr, "song finished, info:\n");
    const char *a; // artist
    const char *t; // title
    const char *b; // album
    float l; // duration
    const char *n; // tracknum
    const char *m; // muzicbrainz id
    if (lfm_fetch_song_info (ev->song, &a, &t, &b, &l, &n, &m) == 0) {
        fprintf (stderr, "playtime: %f\nartist: %s\ntitle: %s\nalbum: %s\nduration: %f\ntracknum: %s\n---\n", ev->song->playtime, a, t, b, l, n);
    }
    else {
        fprintf (stderr, "file %s doesn't have enough tags to submit to last.fm\n", ev->song->fname);
        return 0;
    }

    // check submission rules
    // must be played for >=240sec of half the total time
    if (ev->song->playtime < 240 && ev->song->playtime < ev->song->duration/2) {
        return 0;
    }

    // duration must be >= 30 sec
    if (ev->song->duration < 30) {
        return 0;
    }

    deadbeef->mutex_lock (lfm_mutex);
    // find free place in queue
    for (int i = 0; i < LFM_SUBMISSION_QUEUE_SIZE; i++) {
        if (!lfm_subm_queue[i][0]) {
            snprintf (lfm_subm_queue[i], sizeof (lfm_subm_queue[i]), "a[0]=%s&t[0]=%s&i[0]=%d&o[0]=P&r[0]=&b[0]=%s&l[0]=%d&n[0]=%s&m[0]=%s", a, t, ev->song->started_timestamp, b, (int)l, n, m);
            break;
        }
    }
    deadbeef->mutex_unlock (lfm_mutex);
    deadbeef->cond_signal (lfm_cond);

    return 0;
}

static void
lfm_send_nowplaying (void) {
    if (auth () < 0) {
        lfm_nowplaying[0] = 0;
        return;
    }
    fprintf (stderr, "auth successful! setting nowplaying\n");
    char s[100];
    snprintf (s, sizeof (s), "&s=%s", lfm_sess);
    strcat (lfm_nowplaying, s);
    int status = curl_req_send (lfm_nowplaying_url, lfm_nowplaying);
    if (!status) {
        if (strncmp (lfm_reply, "OK", 2)) {
            fprintf (stderr, "nowplaying failed, response:\n%s\n", lfm_reply);
            lfm_sess[0] = 0;
        }
    }
    curl_req_cleanup ();
    lfm_nowplaying[0] = 0;
}

static void
lfm_send_submissions (void) {
    if (auth () < 0) {
        return;
    }
    for (;;) {
        int i;
        deadbeef->mutex_lock (lfm_mutex);
        for (i = 0; i < LFM_SUBMISSION_QUEUE_SIZE; i++) {
            if (lfm_subm_queue[i][0]) {
                break;
            }
        }
        deadbeef->mutex_unlock (lfm_mutex);
        if (i == LFM_SUBMISSION_QUEUE_SIZE) {
            break;
        }
        int status = curl_req_send (lfm_submission_url, lfm_subm_queue[i]);
        if (!status) {
            if (strncmp (lfm_reply, "OK", 2)) {
                fprintf (stderr, "submission failed, response:\n%s\n", lfm_reply);
                lfm_sess[0] = 0;
            }
            else {
                deadbeef->mutex_lock (lfm_mutex);
                lfm_subm_queue[i][0] = 0;
                deadbeef->mutex_unlock (lfm_mutex);
            }
        }
        curl_req_cleanup ();
        if (!lfm_sess[0]) {
            break;
        }
    }
}

void
lfm_thread (uintptr_t ctx) {
    //fprintf (stderr, "lfm_thread started\n");
    for (;;) {
        deadbeef->cond_wait (lfm_cond, lfm_mutex);
        fprintf (stderr, "cond signalled!\n");
        if (lfm_stopthread) {
            deadbeef->mutex_unlock (lfm_mutex);
            fprintf (stderr, "lfm_thread end\n");
            deadbeef->cond_free (lfm_cond);
            deadbeef->mutex_free (lfm_mutex);
            return;
        }
        deadbeef->mutex_unlock (lfm_mutex);

        // try to send nowplaying
        if (lfm_nowplaying[0]) {
            lfm_send_nowplaying ();
        }

        lfm_send_submissions ();
    }
}


// {{{ lastfm v2 get session
#if 0
int
auth_v2 (void) {
    if (lfm_sess[0]) {
        return 0;
    }
    char msg[4096];
    char sigstr[4096];
    uint8_t sig[16];
    snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getToken%s", LASTFM_API_KEY, LASTFM_API_SECRET);
    deadbeef->md5 (sig, sigstr, strlen (sigstr));
    deadbeef->md5_to_str (sigstr, sig);
    snprintf (msg, sizeof (msg), "%s/?api_key=%s&method=auth.getToken&api_sig=%s", SCROBBLER_URL, LASTFM_API_KEY, sigstr);
    // get token
    char lfm_token[33] = "";
    int status = curl_req_send (msg, NULL);
    if (!status) {
        // parse output
        if (strstr (lfm_reply, "<lfm status=\"ok\">")) {
            char *token = strstr (lfm_reply, "<token>");
            if (token) {
                token += 7;
                char *end = strstr (token, "</token>");
                if (end) {
                    *end = 0;
                    snprintf (msg, sizeof (msg), "http://www.last.fm/api/auth/?api_key=%s&token=%s", LASTFM_API_KEY, token);
                    fprintf (stderr, "Dear user. Please visit this URL and authenticate deadbeef. Thanks.\n");

                    fprintf (stderr, "%s\n", msg);
                    strncpy (lfm_token, token, 32);
                    lfm_token[32] = 0;
                }
            }
        }
    }
    curl_req_cleanup ();
    if (!lfm_token[0]) {
        // total fail, give up
        return -1;
    }
    // get session
    snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getSessiontoken%s%s", LASTFM_API_KEY, lfm_token, LASTFM_API_SECRET);
    deadbeef->md5 (sig, sigstr, strlen (sigstr));
    deadbeef->md5_to_str (sigstr, sig);
    snprintf (msg, sizeof (msg), "method=auth.getSession&token=%s&api_key=%s&api_sig=%s", lfm_token, LASTFM_API_KEY, sigstr);
    for (;;) {
        status = curl_req_send (SCROBBLER_URL, msg);
        if (!status) {
            char *sess = strstr (lfm_reply, "<key>");
            if (sess) {
                sess += 5;
                char *end = strstr (sess, "</key>");
                if (end) {
                    *end = 0;
                    char config[1024];
                    snprintf (config, sizeof (config), "%s/.config/deadbeef/lastfmv2", getenv ("HOME"));
                    fprintf (stderr, "got session key %s\n", sess);
                    FILE *fp = fopen (config, "w+b");
                    if (!fp) {
                        fprintf (stderr, "lastfm: failed to write config file %s\n", config);
                        curl_req_cleanup ();
                        return -1;
                    }
                    if (fwrite (sess, 1, 32, fp) != 32) {
                        fclose (fp);
                        fprintf (stderr, "lastfm: failed to write config file %s\n", config);
                        curl_req_cleanup ();
                        return -1;
                    }
                    fclose (fp);
                    strcpy (lfm_sess, sess);
                }
            }
//            fprintf (stderr, "reply: %s\n", lfm_reply);
        }
        curl_req_cleanup ();
        if (lfm_sess[0]) {
            break;
        }
        sleep (5);
    }
    return 0;
}
#endif
// }}}


static int
lastfm_start (void) {
    lfm_stopthread = 0;
    lfm_mutex = deadbeef->mutex_create ();
    lfm_cond = deadbeef->cond_create ();
    deadbeef->thread_start (lfm_thread, 0);
    // subscribe to frameupdate event
    deadbeef->ev_subscribe (DB_PLUGIN (&plugin), DB_EV_SONGSTARTED, DB_CALLBACK (lastfm_songstarted), 0);
    deadbeef->ev_subscribe (DB_PLUGIN (&plugin), DB_EV_SONGFINISHED, DB_CALLBACK (lastfm_songfinished), 0);
    // load login/pass
    char config[1024];

// {{{ lastfm v2 auth
#if 0
    snprintf (config, 1024, "%s/.config/deadbeef/lastfmv2", getenv ("HOME"));
    FILE *fp = fopen (config, "rt");
    if (fp) {
        if (fread (lfm_sess, 1, 32, fp) != 32) {
            lfm_sess[0] = 0;
        }
        else {
            lfm_sess[32] = 0;
        }
        fclose (fp);
    }
    auth_v2 ();
#endif
// }}}

    snprintf (config, 1024, "%s/.config/deadbeef/lastfm", getenv ("HOME"));
    FILE *fp = fopen (config, "rt");
    if (!fp) {
        fprintf (stderr, "lastfm: failed open %s\n", config);
        return -1;
    }
    if (!fgets (lfm_user, 50, fp)) {
        fprintf (stderr, "lastfm: failed to read login from %s\n", config);
        fclose (fp);
        return -1;
    }
    if (!fgets (lfm_pass, 50, fp)) {
        fprintf (stderr, "lastfm: failed to read pass from %s\n", config);
        fclose (fp);
        return -1;
    }
    fclose (fp);
    // remove trailing garbage
    int l;
    char *p;
    l = strlen (lfm_user);
    p = lfm_user+l-1;
    while (p >= lfm_user && *p < 0x20) {
        p--;
    }
    p++;
    *p = 0;
    l = strlen (lfm_pass);
    p = lfm_pass+l-1;
    while (p >= lfm_pass && *p < 0x20) {
        p--;
    }
    p++;
    *p = 0;

    return 0;
}

static int
lastfm_stop (void) {
    //fprintf (stderr, "lastfm_stop\n");
    deadbeef->ev_unsubscribe (DB_PLUGIN (&plugin), DB_EV_SONGSTARTED, DB_CALLBACK (lastfm_songstarted), 0);
    deadbeef->ev_unsubscribe (DB_PLUGIN (&plugin), DB_EV_SONGFINISHED, DB_CALLBACK (lastfm_songfinished), 0);
    lfm_stopthread = 1;
    deadbeef->cond_signal (lfm_cond);
    fprintf (stderr, "signalled to stop thread\n");
    return 0;
}

// define plugin interface
static DB_misc_t plugin = {
    .plugin.version_major = 0,
    .plugin.version_minor = 1,
    .plugin.type = DB_PLUGIN_MISC,
    .plugin.name = "last.fm scrobbler",
    .plugin.descr = "sends played songs information to your last.fm account",
    .plugin.author = "Alexey Yakovenko",
    .plugin.email = "waker@users.sourceforge.net",
    .plugin.website = "http://deadbeef.sf.net",
    .plugin.start = lastfm_start,
    .plugin.stop = lastfm_stop
};