Created
August 4, 2011 05:49
-
-
Save robinsloan/1124577 to your computer and use it in GitHub Desktop.
Netflix Watch Instantly script for @queuenoodle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'net/http' | |
require 'json' | |
require 'date' | |
module WatchInstantly | |
NUM_DAYS = 13 | |
# main method | |
def self.soon_to_expire | |
movies = get_movies_from_netflix | |
movies_output = [] | |
today = Date.today | |
movies.each do |movie| | |
mo = {} | |
mo[:deadline] = convert_date(movie["Instant"]["AvailableTo"]) | |
if ((mo[:deadline] - today) > 0) then | |
mo[:name] = movie["Name"] | |
mo[:url] = movie["Url"] | |
mo[:rating] = movie["AverageRating"] | |
mo[:img_hd] = movie["BoxArt"]["HighDefinitionUrl"] | |
mo[:img_medium] = movie["BoxArt"]["MediumUrl"] | |
mo[:img_small] = movie["BoxArt"]["SmallUrl"] | |
movies_output << mo | |
end | |
end | |
movies_output = sort_movies(movies_output) | |
return movies_output | |
end | |
private | |
def self.convert_date(netflix_date) | |
netflix_numeric = netflix_date.match(/\/Date\((\d+)\)\//)[1] | |
epoch_time = Time.at(netflix_numeric.to_i/1000) | |
movie_date = Date.new(epoch_time.year,epoch_time.month,epoch_time.day) | |
return movie_date | |
end | |
def self.get_movies_from_netflix | |
today = Date.today | |
this_week = today + WatchInstantly::NUM_DAYS | |
query_today = today.strftime("%Y-%m-%d") | |
query_this_week = this_week.strftime("%Y-%m-%d") | |
base_url = "http://odata.netflix.com/" | |
query = "(Type eq 'Movie') and Instant/Available eq true and Instant/AvailableTo le datetime'#{query_this_week}'" | |
url = (base_url+"Catalog/Titles?$filter="+query+"&$orderby=AverageRating&$format=json").gsub(" ","%20") | |
resp = Net::HTTP.get_response(URI.parse(url)) | |
data = resp.body | |
result = JSON.parse(data) | |
return result["d"]["results"] # gotcha | |
end | |
def self.sort_movies(unsorted_movies) | |
# sort by expiration date, then by rating, then by name | |
sorted_movies = unsorted_movies.sort do |a,b| | |
rv = 0 | |
if (a[:deadline] > b[:deadline]) then rv = 1 end | |
if (a[:deadline] < b[:deadline]) then rv = -1 end | |
if (a[:deadline] === b[:deadline]) then | |
# sort by rating | |
# ratings go big to small, so * -1 | |
r = (a[:rating] <=> b[:rating]) * -1 | |
if (r != 0) then | |
# ratings were different, so we sort | |
rv = r | |
else | |
# ratings must have been the same, so alphabetize by title | |
# the dark knight goes under D, not T | |
rv = (a[:name].gsub("The ","") <=> b[:name].gsub("The ","")) | |
end | |
end | |
rv # no return | |
end | |
return sorted_movies | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment