spot2txt

Export Spotify Playlist Listings as Plaintext
git clone git://git.alexkarle.com.com/spot2txt
Log | Files | Refs | README | LICENSE

get-token.pl (1781B) [raw]


      1 #!/usr/bin/env perl
      2 use strict;
      3 use warnings;
      4 
      5 use Mojolicious::Lite;
      6 use LWP::UserAgent;
      7 use MIME::Base64;
      8 use JSON::PP;
      9 
     10 my $CLIENT_ID = $ENV{SPOTIFY_CLIENT_ID};
     11 my $CLIENT_SECRET = $ENV{SPOTIFY_CLIENT_SECRET};
     12 if (!$CLIENT_ID || !$CLIENT_SECRET) {
     13 	die "Spotify Env Vars not set\n";
     14 }
     15 
     16 my $AUTH_URL = "https://accounts.spotify.com/authorize"
     17 	. "?client_id=$CLIENT_ID"
     18 	. "&response_type=code"
     19 	. "&redirect_uri=http://localhost:3000/auth"
     20 	. "&scope=user-library-read%20playlist-read-private%20playlist-read-collaborative"
     21 	. "&state=" . int(rand() * 100);
     22 
     23 get '/' => sub {
     24 	my $c = shift;
     25 	$c->render(
     26 		template => "index",
     27 		AUTH_URL => $AUTH_URL,
     28 	);
     29 };
     30 
     31 get 'auth' => sub {
     32 	my $c = shift;
     33 
     34 	# TODO: check state too if ever productionize / allow multiple
     35 	# users instead of local-only
     36 	my $code = $c->param("code");
     37 	if (!$code) {
     38 		$c->render(text => "Failed to Authorize; Go back and try again");
     39 		return;
     40 	}
     41 	my $ua = LWP::UserAgent->new();
     42 	my $hash = encode_base64("$CLIENT_ID:$CLIENT_SECRET", "");
     43 	$ua->default_header('Authorization' => "Basic $hash");
     44 	my %form = (
     45 		grant_type => "authorization_code",
     46 		code => $code,
     47 		redirect_uri => "http://localhost:3000/auth",
     48 	);
     49 	my $res = $ua->post(
     50 		"https://accounts.spotify.com/api/token",
     51 		\%form,
     52 	);
     53 	if (!$res->is_success) {
     54 		my $err = $res->decoded_content;
     55 		return $c->render(text => "Error Authenticating: $err");
     56 	}
     57 	my $json = decode_json($res->decoded_content);
     58 	my $tok = $json->{access_token} . "";
     59 	$c->render(text => $tok);
     60 };
     61 
     62 
     63 app->start;
     64 
     65 __DATA__
     66 
     67 @@index.html.ep
     68 <h1>Spotify Playlist Exporter</h1>
     69 <p>Hello and welcome to the Spotify Playlist Exporter!</p>
     70 <p>To start, first log in to Spotify and authorize this
     71 app by clicking the link below:</p>
     72 <a href=<%= $AUTH_URL %>>
     73 Authorize
     74 </a>