Skip to content

Instantly share code, notes, and snippets.

@jonasrosland
Last active January 3, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasrosland/106829a06da0704a11fa to your computer and use it in GitHub Desktop.
Save jonasrosland/106829a06da0704a11fa to your computer and use it in GitHub Desktop.
YouTube Playlist Statistics widget for the Dashing dashboard

YouTube Playlist Statistics widget for the Dashing dashboard

Enables tracking of all video views stats in a playlist.

Sample HTML to put in your .erb file:

    <li data-row="1" data-col="2" data-sizex="4" data-sizey="1" onclick="location.href='https://www.youtube.com/playlist?list=PLbssOJyyvHuWiBQAg9EFWH570timj2fxt';">
      <div data-id="youtube_video_views" data-view="List" data-title="YouTube Views" style="background-color: #c0392b"></div>
      <i class="icon-youtube icon-background"></i>
    </li>
#!/usr/bin/env ruby
require 'net/http'
require 'openssl'
require 'json'
# This job can track some metrics of a single youtube video by accessing the
# public available api of youtube.
# Config
# ------
youtube_api_key = ENV['YOUTUBE_API_KEY'] || 'YOUR_KEY_HERE'
youtube_playlist_id = ENV['YOUTUBE_PLAYLIST_ID'] || 'PLbssOJyyvHuWiBQAg9EFWH570timj2fxt'
max_results = 50
# order the list by the numbers
ordered = true
max_length = 8
SCHEDULER.every '1m', :first_in => 0 do |job|
http = Net::HTTP.new("www.googleapis.com", Net::HTTP.https_default_port())
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # disable ssl certificate check
response = http.request(Net::HTTP::Get.new("/youtube/v3/playlistItems?part=snippet&playlistId=#{youtube_playlist_id}&maxResults=#{max_results}&key=#{youtube_api_key}"))
if response.code != "200"
puts "youtube api error (status-code: #{response.code})\n#{response.body}"
else
data = JSON.parse(response.body, :symbolize_names => true)
youtube_videos = Array.new
data[:items].each do |video|
youtube_videos.push({
label: video[:snippet][:title],
value: video[:snippet][:resourceId][:videoId]
})
end
youtube_stats = Array.new
for each in youtube_videos do
http = Net::HTTP.new("www.googleapis.com", Net::HTTP.https_default_port())
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # disable ssl certificate check
response = http.request(Net::HTTP::Get.new("/youtube/v3/videos?part=statistics&id=#{each[:value]}&key=#{youtube_api_key}"))
data = JSON.parse(response.body, :symbolize_names => true)
data[:items].each do |video|
youtube_stats.push({
label: each[:label],
value: video[:statistics][:viewCount].to_i
})
end
end
if ordered
youtube_stats = youtube_stats.sort_by { |obj| -obj[:value] }
end
if defined?(send_event)
send_event('youtube_video_views', { items: youtube_stats.slice(0, max_length) })
else
puts youtube_stats
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment