78 lines
2.5 KiB
Ruby
78 lines
2.5 KiB
Ruby
require 'uri'
|
|
require 'net/http'
|
|
|
|
class MusicController < ApplicationController
|
|
def get_current_track
|
|
if Rails.cache.exist?("current_track")
|
|
return Rails.cache.read("current_track")
|
|
end
|
|
|
|
uri = URI.parse('https://ws.audioscrobbler.com/2.0/')
|
|
params = {
|
|
:method => 'user.getrecenttracks',
|
|
:user => Rails.application.credentials.lastfm.username,
|
|
:format => 'json',
|
|
:nowplaying => 'true',
|
|
:api_key => Rails.application.credentials.lastfm.api_key
|
|
}
|
|
uri.query = URI.encode_www_form(params)
|
|
req = Net::HTTP::Get.new(uri.to_s)
|
|
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) {|http|
|
|
http.request(req)
|
|
}
|
|
data = JSON.parse(res.body)
|
|
track_data = data["recenttracks"]["track"][0]
|
|
image = defined?(track_data["image"][-1]) ? track_data["image"][-1] : false
|
|
now_playing = false
|
|
if track_data["@attr"] != nil
|
|
now_playing = track_data["@attr"]["nowplaying"] == "true"
|
|
end
|
|
|
|
current_track = {
|
|
:title => track_data["name"],
|
|
:artist => track_data["artist"]["#text"],
|
|
:url => track_data["url"],
|
|
:image => image["#text"],
|
|
:header => if now_playing then "Now Playing" else "Last Track" end
|
|
}
|
|
return current_track
|
|
end
|
|
|
|
def get_top_tracks
|
|
if Rails.cache.exist?("top_tracks")
|
|
return Rails.cache.read("top_tracks")
|
|
end
|
|
|
|
uri = URI.parse('https://ws.audioscrobbler.com/2.0/')
|
|
params = {
|
|
:method => 'user.gettoptracks',
|
|
:user => Rails.application.credentials.lastfm.username,
|
|
:format => 'json',
|
|
:period => '1month',
|
|
:limit => 10,
|
|
:api_key => Rails.application.credentials.lastfm.api_key
|
|
}
|
|
uri.query = URI.encode_www_form(params)
|
|
req = Net::HTTP::Get.new(uri.to_s)
|
|
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) {|http|
|
|
http.request(req)
|
|
}
|
|
data = JSON.parse(res.body)
|
|
top_tracks = []
|
|
data["toptracks"]["track"].each do |track|
|
|
top_tracks.push({
|
|
:title => track["name"],
|
|
:artist => track["artist"]["name"],
|
|
:url => track["url"],
|
|
:plays => track["playcount"]
|
|
})
|
|
end
|
|
|
|
return top_tracks
|
|
end
|
|
|
|
def index
|
|
@current_track = get_current_track
|
|
@top_tracks = get_top_tracks
|
|
end
|
|
end
|