自动刷新rails中的页面以获取用户当前的spotify歌曲

问题描述 投票:0回答:1

在我的应用程序中,当用户播放列表中的歌曲发生变化时,我需要更新页面上的详细信息。我目前的解决方案是在对页面的ajax请求中使用javascript的setInterval。这导致500错误。有更好的解决方案吗?有谁知道spotify api中的东西是否已经处理了这个?

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

此外,这是一个由播放动作生成的好请求:

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

这是ajax方法生成的错误(500错误)请求:

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
javascript ruby-on-rails ruby spotify
1个回答
0
投票

在Web播放器视图的脚本中,我以3秒的间隔调用location.reload()。更有效的方法是获取当前歌曲的长度并将间隔更改为我猜测的轨道长度。但这并不能说明用户是否要跳过这首歌。

<script>
  setInterval(function(){
   location.reload();
  }, 3000);
</script>

对此解决方案不一定满意,但它现在可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.