-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlast.played.psgi
82 lines (61 loc) · 2 KB
/
last.played.psgi
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
#!/usr/bin/perl
use v5.16;
use strict;
use warnings;
use Last::Played;
use Plack::Request;
my $key = $ENV{LASTFM_API_KEY};
my $user = $ENV{LASTFM_USER_ID};
die "FATAL: Please set an env var of LASTFM_API_KEY to store your API key!" unless $key;
my %routes = (
'/' => \&get_last_played,
'/now' => \&get_last_played,
'/top-alltime' => \&get_top_alltime,
'/top-week' => \&get_top_week,
'/top-year' => \&get_top_year,
'/widget' => \&make_widget,
);
my $lfm = Last::Played->new(api_key => $key);
sub error {
my ($msg, $code) = @_;
return [ $code, [ 'Content-Type' => 'application/json' ],
[ "{\"message\": \"$msg\", \"status\": \"error\"}" ] ];
}
sub get_last_played {
my $last_played = $lfm->get_last_played(shift);
my $status = ($last_played =~ /error/) ? 500 : 200;
return [ $status, [ 'Content-Type' => 'application/json' ], [ $last_played ] ];
}
sub get_top_alltime {
my $top = $lfm->get_top_track_alltime(shift);
my $status = ($top =~ /error/) ? 500 : 200;
return [ $status, [ 'Content-Type' => 'application/json' ], [ $top ] ];
}
sub get_top_year {
my $top = $lfm->get_top_track_year(shift);
my $status = ($top =~ /error/) ? 500 : 200;
return [ $status, [ 'Content-Type' => 'application/json' ], [ $top ] ];
}
sub make_widget {
my $widget = $lfm->make_widget(shift);
my $status = ($widget =~ /error/) ? 500 : 200;
return [ $status, [ 'Content-Type' => 'image/png' ], [ $widget ] ];
}
sub get_top_week {
my $top = $lfm->get_top_track_week(shift);
my $status = ($top =~ /error/) ? 500 : 200;
return [ $status, [ 'Content-Type' => 'application/json' ], [ $top ] ];
}
my $app = sub {
my $env = shift;
my $req = Plack::Request->new($env);
my $route = $routes{$req->path_info};
return error("Not found", 404) unless $route;
if ($req->param('user')) {
&$route($req->param('user'));
} elsif ($user) {
&$route($user);
} else {
return error("UserID is required", 500);
}
};