-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlastfm
executable file
·724 lines (543 loc) · 14.4 KB
/
lastfm
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
#!/usr/bin/env perl
# This is a Kitchen Sink Tool for Last.fm
# (C) 2021 Martin Frederic
use strict;
use warnings;
use v5.18;
# = BEGIN COMMON FUNCTIONS =
use Carp qw{croak};
use Digest::MD5 qw{md5_hex};
use Encode qw{decode};
use File::Basename qw{basename dirname};
use File::Path qw{make_path};
use IPC::Open3 qw{open3};
use Pod::Usage qw{pod2usage};
use Symbol qw{gensym};
use LWP::UserAgent qw{};
use JSON qw{decode_json};
use URI::Escape qw{uri_escape_utf8};
use XML::LibXML;
use open qw{:std :utf8};
use Data::Dumper;
$Data::Dumper::Maxdepth = 2;
$Data::Dumper::Sortkeys = 1;
my $api_base = 'https://ws.audioscrobbler.com/2.0/';
my $debug = 0;
sub make_api_url {
return $api_base unless @_;
my %args = @_;
my $full = $api_base;
my $sep = '?';
for my $key (sort keys %args) {
my $val = $args{$key};
$full .= $sep;
$full .= uri_escape_utf8($key) . '=' . uri_escape_utf8($val);
$sep = '&';
}
return $full;
}
sub make_api_signature {
my $secret = shift;
my %args = @_;
my $s;
# Keys need to be sorted!
# Fascists...
for my $key (sort keys %args) {
my $val = $args{$key};
$s .= $key . $val;
}
$s .= $secret;
utf8::encode($s);
return md5_hex($s);
}
sub api_request {
my $ua = shift;
my $url = shift;
my $method = shift || '';
my $res;
if ($method eq 'POST') {
$res = $ua->post($url);
} else {
$res = $ua->get($url);
}
if ($res->is_success) {
# We're done here!
return $res->decoded_content;
}
# Even if we didn't get a 200 OK, the Last.fm API might have
# returned something useful as JSON.
# Might contain a "useful" error message later on.
my ($api_err, $err_msg);
eval {
$api_err = decode_json($res->decoded_content);
$err_msg = sprintf "API error #%d: %s [%s]",
$api_err->{error}, $api_err->{message}, $url;
};
if ($@) {
# OK, nothing useful here, seems like a fundamental error.
print STDERR "Did not receive a valid JSON response!\n";
print STDERR $res->decoded_content, "\n";
die $res->status_line;
} else {
if ($api_err->{error} == 8) {
# 8 is "Operation failed - Something else went wrong"
print $err_msg, "\nRetrying...\n";
sleep 5;
return __SUB__->($ua, $url);
}
die $api_err;
}
}
sub get_auth_token {
my $ua = shift;
my $conf = get_config();
my %args = (
method => 'auth.getToken',
api_key => $conf->{api}->{key},
format => 'json'
);
my $sig = make_api_signature($conf->{api}->{secret}, %args);
my $url = make_api_url(%args, api_sig => $sig);
my $json = api_request($ua, $url);
my $data = decode_json $json;
return $data->{token};
}
sub get_auth_session {
my $ua = shift;
my $token = shift;
my $conf = get_config();
my %args = (
method => 'auth.getSession',
api_key => $conf->{api}->{key},
token => $token
# Note: no format => json allowed here... oh well.
);
my $sig = make_api_signature($conf->{api}->{secret}, %args);
my $url = make_api_url(%args, api_sig => $sig);
my $xml = api_request($ua, $url);
# TODO: unify XML parsing (that is: not use regexes!!1!11)
my $res = $xml =~ m@<key>([[:alnum:]_-]+)</key>@;
if ($res) {
my $key = $1;
return $key;
} else {
die "Could not extract key from XML, got:\n\n$xml\n";
}
}
sub request_user_auth {
my $token = shift;
my $config = get_config();
my $api_key = $config->{api}->{key};
my $url = "http://www.last.fm/api/auth/"
. "?api_key=$api_key&token=$token";
print STDERR "Authentication request! Point your browser to:\n";
print STDERR $url, "\n";
}
sub get_sk {
my $ua = shift;
my $user = shift;
# Build path to cache file
die "Missing env: \$HOME\n" unless exists $ENV{HOME};
# say STDERR $ENV{HOME};
my $cache_dn = "$ENV{HOME}/.cache/lastfm-tools";
my $cache_fn = "$cache_dn/$user.session";
my $sk;
if (-e -f $cache_fn) {
# cache file exists, read sk from it!
$sk = read_utf8($cache_fn);
# print STDERR "Read sk: $sk\n";
} else {
# cache file does not exist, create it
my $token = get_auth_token($ua);
request_user_auth($token);
print STDERR "(Hit RETURN to continue.)\n";
<STDIN>;
$sk = get_auth_session($ua, $token);
make_path($cache_dn);
write_utf8($cache_fn, $sk);
print STDERR "Session stored at $cache_fn\n";
}
return $sk;
}
sub scrobble {
my $ua = shift;
my $track = shift;
my $success_cb = shift;
my $conf = get_config();
my $sk = get_sk($ua, $conf->{core}->{user});
my %args = (
method => 'track.scrobble',
# Let's be explicit
artist => $track->{artist},
track => $track->{title},
(exists $track->{album} ?
(album => $track->{album}) : ()),
# Use current time if none is provided
timestamp => ($track->{time} // time()),
api_key => $conf->{api}->{key},
sk => $sk
);
my $sig = make_api_signature($conf->{api}->{secret}, %args);
my $url = make_api_url(%args, api_sig => $sig);
# Technically, we should send the arguments as a
# POST body, but simply doing a POST with the args
# in the URL seems to work fine...
my $xml = api_request($ua, $url, 'POST');
my $dom = XML::LibXML->load_xml(string => $xml);
my $status = $dom->find('//lfm/@status');
if ($status ne 'ok') {
die "LastFM: not ok\n" . $xml;
}
# It is ok to check for exactly 1 accepted scrobble since
# we're never scrobbling multiple tracks in a batch.
# Also, we do string comparison since LibXML does not seem
# to overload the != operator, ugh.
my $accepted = $dom->find('//lfm/scrobbles/@accepted');
if ($accepted ne '1') {
warn "LastFM: not accepted\n" . $xml;
}
if (defined $success_cb) {
$success_cb->($track);
}
return 1;
}
sub scrobble_success_cb {
my $track = shift;
print "Scrobbled: $track->{artist} - $track->{title}\n";
}
sub get_ua {
my ($c_pkg, $c_fn) = caller;
my $ua = LWP::UserAgent->new(timeout => 10);
$ua->env_proxy;
$ua->agent("nanont-lastfm/0.1");
return $ua;
}
sub get_config {
# TODO: use XDG conventions
my $conf_path = "$ENV{HOME}/.config/lastfm-tools.conf";
unless (-e -f $conf_path) {
die "Missing config file! ($conf_path)\n";
}
my %config;
my @lines = split /\r?\n/, read_utf8($conf_path);
my $top_key;
for (@lines) {
if (/ \[ ([[:alnum:]]+) \] /x) {
# say STDERR "LABEL: {$1}";
$top_key = $1;
} elsif (/ ([[:alnum:]]+) \s* = \s* ([[:alnum:]]+) /x) {
# say STDERR "VAL: {$1} -> {$2}";
$config{$top_key}->{$1} = $2;
}
}
return \%config;
}
sub write_binary {
my $fn = shift;
my $dataref = shift;
open(my $fh, '>', $fn) or croak "$!";
binmode $fh;
print $fh $$dataref;
close $fh;
}
sub write_utf8 {
my $fn = shift;
my $str = shift;
# print STDERR "WRITE_UTF8: <<$str>>\n";
utf8::encode($str);
write_binary($fn, \$str);
}
sub read_binary {
my $fn = shift;
open(my $fh, '<', $fn) or croak "$!";
binmode $fh;
local $/ = undef;
my $bin = <$fh>;
close $fh;
return $bin;
}
sub read_utf8 {
my $fn = shift;
my $bin = read_binary($fn);
utf8::decode($bin);
return $bin;
}
# = BEGIN DAP FUNCTIONS =
# Resources:
# https://web.archive.org/web/20180315041951/ \
# http://www.audioscrobbler.net/wiki/Portable_Player_Logging
sub dap_validate_log {
my $logref = shift;
my %expected = (
0 => '#AUDIOSCROBBLER/1.1',
1 => '#TZ/UNKNOWN'
);
for my $i (sort keys %expected) {
my $exact_match = $expected{$i};
if ($logref->[$i] !~ /^\Q$exact_match\E$/) {
die sprintf("Expected <%s>, got <%s>\n",
$exact_match, $logref->[$i]);
}
}
# The header is made up of 3 lines,
# so check if we have at least 4
if (scalar @{ $logref } < 4) {
die "Expecting at least one log entry\n";
}
}
sub dap_make_track {
my ($artist, $album, $track,
$position, $duration, $rating,
$timestamp, $mbid) = @_;
my %track = (
artist => $artist,
album => $album,
track => $track,
position => $position,
duration => $duration,
rating => $rating,
timestamp => $timestamp,
mbid => $mbid
);
return \%track;
}
sub dap_parse_log {
my @raw = @{ shift() };
# Remove the first three lines
splice @raw, 0, 3;
my @log =
map { dap_make_track @{ $_ } }
# Break lines by tabs into track
map { [ split /\t/, $_ ] }
@raw;
}
sub dap_scrobble_log {
my $ua = shift;
my $logref = shift;
my @log = dap_parse_log($logref);
# Ignore skipped tracks
my @listened = grep { $_->{rating} eq 'L' } @log;
for my $listen (@listened) {
# Consider time offset
my $tz_offset = +(60 * 60 * 2); # CEST: +2h
my $local_timestamp = $listen->{timestamp} - $tz_offset;
# Move relevant bits into a structure
# that Common::scrobble understands
# (Yes, this sucks bad.)
my $submission = {
artist => $listen->{artist},
title => $listen->{track},
album => $listen->{album},
time => $local_timestamp
};
scrobble($ua, $submission, \&scrobble_success_cb);
}
#p @listened;
}
sub dap_maybe_delete_log {
my $file = shift;
my $bn = basename $file;
local $| = 1;
print "Delete logfile ($bn)? [y/N] ";
my $resp = <STDIN>;
if ($resp !~ /[yY]/) {
return;
}
if (unlink $file) {
print "Deleted: $file\n";
} else {
print "unlink failed: $file\n";
}
}
# = BEGIN STATION FUNCTIONS =
my $station_now;
station_clear_now($station_now);
sub station_update_now {
my $artist = shift;
my $title = shift;
$station_now = {artist => $artist, title => $title};
if ($debug) {
print STDERR "Update!\n";
print STDERR Dumper($station_now);
}
}
sub station_pending_now {
my $artist = shift;
my $title = shift;
if (station_clearp_now($station_now)) {
return 0;
}
if (($station_now->{artist} ne $artist) or
($station_now->{title} ne $title)) {
if ($debug) {
printf STDERR "Pending! (%s = %s | %s = %s)\n",
$station_now->{artist}, $artist,
$station_now->{title}, $title;
}
return 1;
}
return 0;
}
sub station_clear_now {
$station_now = undef;
}
sub station_clearp_now {
return !(defined $station_now);
}
sub station_scrobble_now {
if ($debug) {
printf "station_clearp_now: %d\n", station_clearp_now();
}
if (!(station_clearp_now())) {
scrobble(get_ua(), $station_now);
}
station_clear_now();
}
sub station_handle_ok {
my $fh_out = shift;
my $fh_err = shift;
my $artist = readline $fh_out;
my $title = readline $fh_out;
chomp($artist, $title);
if (station_pending_now($artist, $title)) {
station_scrobble_now;
}
station_update_now($artist, $title);
};
sub station_handle_skip {
station_scrobble_now;
}
sub station_handle_error {
my $fh_out = shift;
my $fh_err = shift;
station_scrobble_now;
}
# = TASK RUNNER =
sub task_scrobble {
my @args = @_;
print "Artist > ";
my $artist = <STDIN>;
print "Title > ";
my $title = <STDIN>;
chomp($artist, $title);
if ($artist eq '' or $title eq '') {
print STDERR "Artist and Title are required.\n";
exit -1;
}
print "Album (optional) > ";
my $album = <STDIN>;
chomp($album);
my $submission = {
artist => $artist,
title => $title,
($album ne '' ?
(album => $album) : ())
};
my $ua = get_ua;
scrobble($ua, $submission, \&scrobble_success_cb);
}
sub task_scrobble_dap {
my @args = @_;
my $file;
while (local $_ = shift @args) {
if (/--?f(ile)?/) { $file = shift @args }
}
unless (defined $file) {
pod2usage "Missing: --file";
}
my @log = split /\n/, read_utf8($file);
dap_validate_log(\@log);
my $ua = get_ua;
dap_scrobble_log($ua, \@log);
dap_maybe_delete_log($file);
}
sub task_scrobble_station {
my @args = @_;
my $station = shift @args;
my $script = "$ENV{HOME}/.nanont-lastfm/stations/$station"; # TODO improve
if (!(-e -f -x $script)) {
print STDERR "Provider does not exist or is not executable\n";
print STDERR "(Looked for: $script)\n";
exit -1;
}
print STDOUT "Listening to $station ...\n";
while (1) {
my $pid = open3(my $s_in, my $s_out, my $s_err = gensym,
$script);
binmode($_, ':encoding(UTF-8)') for ($s_in, $s_out, $s_err);
waitpid($pid, 0);
my $rc = $? >> 8;
my $handlers = {
OK => \&station_handle_ok,
SKIP => \&station_handle_skip,
ERROR => \&station_handle_error
};
my $status = readline $s_out;
chomp $status;
if (exists $handlers->{$status}) {
$handlers->{$status}->($s_out, $s_err);
} else {
die "Station Provider not working as intended (status: $status)\n";
}
sleep 30;
}
}
sub task_recent {
my $ua = get_ua;
my $conf = get_config;
my $url = make_api_url(method => 'user.getrecenttracks',
user => 'nanont',
limit => 10,
api_key => $conf->{api}->{key});
my $xml = api_request($ua, $url);
my $doc = XML::LibXML->load_xml(string => $xml);
# say $doc;
my @tracks = $doc->findnodes(q(//lfm/recenttracks/track));
for my $t (@tracks) {
printf "%s - %s\n",
$t->find(q(./artist/text())),
$t->find(q(./name/text()));
}
}
# = MAIN =
sub main {
my @cli_argv = @ARGV;
if (scalar(@cli_argv) == 0 or
$cli_argv[0] =~ /--?h(elp)?/) { pod2usage(1) } # exits
my $tasks = {
'scrobble' => \&task_scrobble,
'scrobble-dap' => \&task_scrobble_dap,
'scrobble-station' => \&task_scrobble_station,
'recent' => \&task_recent
};
my $selection = shift @cli_argv;
if (exists $tasks->{$selection}) {
$tasks->{$selection}->(@cli_argv);
} else {
local $" = ', ';
my @available = sort keys %{ $tasks };
die "Task not found: $selection (try: @available)\n";
}
}
main;
__END__
=head1 lastfm
Submit a scrobble log (e.g. from Rockbox) to Last.fm.
=head1 SYNOPSIS
lastfm TASK [task-specific options]
Available TASKs are:
scrobble
Scrobble a single track. Interactive.
scrobble-dap
Use this to submit scrobbler.log files from your mp3 player.
Options:
-f PATH
--file PATH Path to log file.
scrobble-station
Scrobble from a radio station or other sources.
Options:
NAME Name of the station provider binary.
Example:
lastfm scrobble-station fm4
recent
Show the 10 most recent scrobbles.