В моем приложении мне нужно обновить детали на странице, когда песня в плейлисте пользователя меняется.Мое текущее решение состоит в том, чтобы использовать javascript setInterval при запросе ajax к странице.Что приводит к ошибке 500.Есть ли лучшее решение?Кто-нибудь знает, есть ли что-то в API-интерфейсе spotify, который уже обрабатывает это?
web_player.html.erb (представление, которое должно обновляться автоматически)
<!DOCTYPE html>
<% @playlists_new.each do |t_info| %>
<% if t_info[0][0].eql? @current_song %>
<body>
<%= link_to 'back', {:controller => "players", :action => "index", :user => @user.to_hash} %>
<h1>Player</h1>
<div id="player">
<div id="track-info">
<img id="track-cover" src=<%=@player_response['item']['album']['images'][0]['url'].to_s%>></img>
<h3 id="track-name"><%= @current_song %></h3>
<h3 id="artist-name"><%= @player_response['item']['artists'][0]['name'] %></h3>
</div>
<div id="memories">
<h3 id="text-memory"><%= t_info[1][0] %></h3>
</div>
</div>
<body>
<style>
body {
background:
linear-gradient(
rgba(30, 32, 35, 0.45),
rgba(30, 32, 35, 0.45)
),
url(<%= t_info[2][0].to_s %>);
}
</style>
<% end %>
<% end %>
<script>
setInterval(function(){
$.ajax({
url: "web_player",
data: {
playlist_info: <%= raw(@playlists).html_safe %>,
user: <%= raw(@user.to_json).html_safe %>,
},
dataType: 'html'
})
}, 3000);
</script>
Players_controller.rb
require 'net/http'
require 'json'
class PlayersController < ApplicationController
protect_from_forgery except: :web_player
def index
params.require(:user).permit!
@playlists = Hash.new
@user = RSpotify::User.new(params[:user]);
#all tracks with a memory attached
@tracks = Track.where(:username => @user.display_name).order(:playlist_name)
#we need to organize the tracks and memories by playlist
@tracks.each do |t|
if @playlists[t.playlist_name].nil?
@playlists[t.playlist_name] = []
end
#get playlist URI !!
@user.playlists.each do |p|
if p.name.eql? t.playlist_name
@playlist_uri = p.uri
end
end
@playlists[t.playlist_name] << [t.title, t.memory, t.imageurl, @playlist_uri]
end
@player_response = RSpotify.resolve_auth_request(@user.display_name, "me/player/")
@current_song = @player_response
if @current_song.nil?
@current_song = " "
else
@current_song = @player_response['item']['name']
end
end
#plays playlist
def play
params.require(:user).permit!
@user = RSpotify::User.new(params[:user]);
@uri = URI('https://api.spotify.com/v1/me/player/play')
#request body tells spotify what playlist to play
@body = {
"context_uri": params[:playlist_uri]
}.to_json
#headers
req = Net::HTTP::Put.new(@uri.path, initheader = {'Content-Type' =>'application/json', 'Authorization' => 'Bearer ' + @user.credentials['token'].to_s})
req.body = @body
http = Net::HTTP.new(@uri.host, @uri.port)
http.use_ssl = true
response = http.start {|h|
h.request(req)
}
sleep 1.5
#redirecting to new action so the user can refresh the web player and not restart the playlist
redirect_to :action => "web_player", :user => @user.to_hash, :playlist_info => params[:playlist_info]
end
def web_player
params.require(:user).permit!
@user = RSpotify::User.new(params[:user]);
#get currrent song playing to decide what memory to display
@player_response = RSpotify.resolve_auth_request(@user.display_name, "me/player/")
@current_song = @player_response
if @current_song.nil?
@current_song = " "
else
@current_song = @player_response['item']['name']
end
@playlists = params[:playlist_info]
@playlists_new = []
#uhh so the playlists hash gets fucked so i'm rebuilding it here hehehe
(@playlists.length/4).times do |t|
@playlists_new << [@playlists[(t * 4)], @playlists[(t * 4) + 1], @playlists[(t * 4) + 2]]
end
end
end
Кроме того, это хороший запрос, сгенерированный действием play:
http://localhost:3000/players/web_player?playlist_info%5B%5D%5B%5D=Guilty&playlist_info%5B%5D%5B%5D=farted+eheh&playlist_info%5B%5D%5B%5D=&playlist_info%5B%5D%5B%5D=spotify%3Aplaylist%3A23zfZIyQInLuAyxZzv4taL&playlist_info%5B%5D%5B%5D=Lissoms&playlist_info%5B%5D%5B%5D=farting+large+%3E%3A%29&playlist_info%5B%5D%5B%5D=http%3A%2F%2Fclipart-library.com%2Fdata_images%2F80305.png&playlist_info%5B%5D%5B%5D=spotify%3Aplaylist%3A23zfZIyQInLuAyxZzv4taL&user%5Bbirthdate%5D=&user%5Bcountry%5D=&user%5Bcredentials%5D%5Bexpires%5D=true&user%5Bcredentials%5D%5Bexpires_at%5D=1554571172&user%5Bcredentials%5D%5Brefresh_token%5D=AQBuXWgqyvHVsvV0L138RtuvTmc8gKX-PMxvBQ3ovQVyR_40wlPRjvskR6E3s3btEctUYtx44HKMq22Xen7Le_eLg5w70VXl_YTMX-fmCGGnqJqLLWGXAaXrRyqZSBt1mdu2wg&user%5Bcredentials%5D%5Btoken%5D=BQDoUpwrQUsIrc1qDksp--ilhqV6sC0CBnG2e2AZaY1DGj-wgHAWtvnOxkrebfw2C2r5QT-GnAQtJe7sAdH6lc4HF-edb6JnXzy-GZgeIwfYVTugzwNgVQ9uLCTkztPQQu86IsRrEVbtWvdlufVem-S47ms99ZWcujS2fz1Jb6aZGj3_MVtgeicdN5XRuA4zRzYUQoaWxbng_KO9muuUofDr&user%5Bdisplay_name%5D=jakeherman-3&user%5Bemail%5D=jakeherman%40outlook.com&user%5Bexternal_urls%5D%5Bspotify%5D=https%3A%2F%2Fopen.spotify.com%2Fuser%2Fjakeherman-3&user%5Bfollowers%5D%5Bhref%5D=&user%5Bfollowers%5D%5Btotal%5D=15&user%5Bhref%5D=https%3A%2F%2Fapi.spotify.com%2Fv1%2Fusers%2Fjakeherman-3&user%5Bid%5D=jakeherman-3&user%5Bimages%5D%5B%5D%5Bheight%5D=&user%5Bimages%5D%5B%5D%5Burl%5D=https%3A%2F%2Fprofile-images.scdn.co%2Fimages%2Fuserprofile%2Fdefault%2Ffa01ec91c49ec1bfc76c3b32b7b7260af83b3903&user%5Bimages%5D%5B%5D%5Bwidth%5D=&user%5Bproduct%5D=&user%5Btype%5D=user&user%5Buri%5D=spotify%3Auser%3Ajakeherman-3
И это неправильный (500 ошибка) запрос, сгенерированный методом ajax:
http://localhost:3000/players/web_player?playlist_info%5B0%5D%5B%5D=Guilty&playlist_info%5B1%5D%5B%5D=farted+eheh&playlist_info%5B2%5D%5B%5D=&playlist_info%5B3%5D%5B%5D=spotify%3Aplaylist%3A23zfZIyQInLuAyxZzv4taL&playlist_info%5B4%5D%5B%5D=Lissoms&playlist_info%5B5%5D%5B%5D=farting+large+%3E%3A)&playlist_info%5B6%5D%5B%5D=http%3A%2F%2Fclipart-library.com%2Fdata_images%2F80305.png&playlist_info%5B7%5D%5B%5D=spotify%3Aplaylist%3A23zfZIyQInLuAyxZzv4taL&user%5Bbirthdate%5D=&user%5Bcountry%5D=&user%5Bdisplay_name%5D=jakeherman-3&user%5Bemail%5D=jakeherman%40outlook.com&user%5Bfollowers%5D%5Bhref%5D=&user%5Bfollowers%5D%5Btotal%5D=15&user%5Bimages%5D%5B0%5D%5Bheight%5D=&user%5Bimages%5D%5B0%5D%5Burl%5D=https%3A%2F%2Fprofile-images.scdn.co%2Fimages%2Fuserprofile%2Fdefault%2Ffa01ec91c49ec1bfc76c3b32b7b7260af83b3903&user%5Bimages%5D%5B0%5D%5Bwidth%5D=&user%5Bproduct%5D=&user%5Bexternal_urls%5D%5Bspotify%5D=https%3A%2F%2Fopen.spotify.com%2Fuser%2Fjakeherman-3&user%5Bhref%5D=https%3A%2F%2Fapi.spotify.com%2Fv1%2Fusers%2Fjakeherman-3&user%5Bid%5D=jakeherman-3&user%5Btype%5D=user&user%5Buri%5D=spotify%3Auser%3Ajakeherman-3&user%5Bcredentials%5D%5Bexpires%5D=true&user%5Bcredentials%5D%5Bexpires_at%5D=1554571172&user%5Bcredentials%5D%5Brefresh_token%5D=AQBuXWgqyvHVsvV0L138RtuvTmc8gKX-PMxvBQ3ovQVyR_40wlPRjvskR6E3s3btEctUYtx44HKMq22Xen7Le_eLg5w70VXl_YTMX-fmCGGnqJqLLWGXAaXrRyqZSBt1mdu2wg&user%5Bcredentials%5D%5Btoken%5D=BQDoUpwrQUsIrc1qDksp--ilhqV6sC0CBnG2e2AZaY1DGj-wgHAWtvnOxkrebfw2C2r5QT-GnAQtJe7sAdH6lc4HF-edb6JnXzy-GZgeIwfYVTugzwNgVQ9uLCTkztPQQu86IsRrEVbtWvdlufVem-S47ms99ZWcujS2fz1Jb6aZGj3_MVtgeicdN5XRuA4zRzYUQoaWxbng_KO9muuUofDr