Skip to content

Instantly share code, notes, and snippets.

@LevitatingBusinessMan
Created May 7, 2024 23:58
Show Gist options
  • Save LevitatingBusinessMan/4d4cdbb65848b2472a83a8e8618b140c to your computer and use it in GitHub Desktop.
Save LevitatingBusinessMan/4d4cdbb65848b2472a83a8e8618b140c to your computer and use it in GitHub Desktop.
Proving that spotify isn't random
RSpotify.authenticate CLIENT_ID, CLIENT_SECRET
REDIRECT_URI = "http://localhost:3000"
SCOPE = [
"user-read-playback-state",
"streaming"
]
begin
credentials = JSON.parse File.read ".token"
me_uri = URI("https://api.spotify.com/v1/me")
http = Net::HTTP.new(me_uri.host, me_uri.port)
req = Net::HTTP::Get.new(me_uri)
req["Authorization"] = "Bearer " + credentials["access_token"]
http.use_ssl = true
res = http.request(req)
info = JSON.parse res.body
credentials["token"] = credentials["access_token"]
opt = {"info" => info, "credentials" => credentials}
@account = RSpotify::User.new opt
puts "Logged in via saved token"
rescue
auth_url = "#{RSpotify::AUTHORIZE_URI}?client_id=#{CLIENT_ID}&response_type=code&redirect_uri=#{REDIRECT_URI}&scope=#{SCOPE.join ","}"
server = TCPServer.new 3000
puts "Open #{auth_url} and do your thing:"
client = server.accept
res = client.gets
client.puts "HTTP/1.1 200 OK\r\n\r\nthankyou"
client.close
server.close
res.split("\n")[0]
code = /GET \/\?code=([\w-]*) HTTP\/1\.1/.match(res).captures[0]
api_url = URI("#{RSpotify::TOKEN_URI}?grant_type=authorization_code&code=#{code}&redirect_uri=#{REDIRECT_URI}")
req = Net::HTTP::Post.new(api_url)
req.basic_auth CLIENT_ID, CLIENT_SECRET
req["Content-Type"] = "application/x-www-form-urlencoded"
http = Net::HTTP.new(api_url.host, api_url.port)
http.use_ssl = true
res = http.request(req)
File.write ".token", res.body
credentials = JSON.parse res.body
me_uri = URI("https://api.spotify.com/v1/me")
http = Net::HTTP.new(me_uri.host, me_uri.port)
req = Net::HTTP::Get.new(me_uri)
req["Authorization"] = "Bearer " + credentials["access_token"]
http.use_ssl = true
res = http.request(req)
info = JSON.parse res.body
credentials["token"] = credentials["access_token"]
opt = {"info" => info, "credentials" => credentials}
@account = RSpotify::User.new opt
puts "Finalized login"
end
#!/usr/bin/env ruby
require 'bundler/inline'
gemfile install = true do
source "https://rubygems.org"
gem "rspotify"
gem "json"
end
CLIENT_ID = "e358308685904dec8b8df102c7581df1"
CLIENT_SECRET = `pass spotifyisnotrandom`.chomp
require "./authenticate"
player = @account.player
loop do
song = player.currently_playing
p "#{song.uri} #{song.name} (#{song.popularity})"
player.next
sleep 3
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment