Skip to content

Instantly share code, notes, and snippets.

@Hubro
Created July 30, 2015 15:09
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 Hubro/34bf634bab924853fdcf to your computer and use it in GitHub Desktop.
Save Hubro/34bf634bab924853fdcf to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "yaml"
require "uri"
require "openssl"
require "net/http"
require "nokogiri"
VERBOSE = !ENV["VERBOSE"].nil?
CONFIG_PATH = "#{ENV["HOME"]}/.config/freshontv-check.yaml"
HEADERS = {
"User-Agent" =>
"Mozilla/5.0 (X11; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0"
}
require "pp" if VERBOSE
module FreshontvCheck
extend self
def main
@config = load_config
@con = connect("freshon.tv")
@config["shows"].each { |show|
uri = URI(show["url"])
puts "# Checking #{show["name"]}" if VERBOSE
links = check_uri(uri)
count = links.count
# if count < 1
# puts "#{show["name"]}: No new episodes :-("
# elsif count > 1
# puts green_text("#{show["name"]} has #{count} new episodes!")
# else
# puts green_text("#{show["name"]} has one new episode!")
# end
links.each { |link|
path = download_torrent(link)
# puts green_text("Downloaded torrent: #{path}")
puts "Downloaded torrent: #{path}"
}
}
@con.finish
end
def load_config
begin
return YAML.load(File.read(CONFIG_PATH))
rescue Errno::ENOENT
abort "Config file not found (#{CONFIG_PATH})"
end
end
def check_uri(uri)
response = request(uri.path + "?" + uri.query)
if response.code != "200"
STDERR.puts "Error: Code response code #{response.code} from #{uri.host}"
return false
end
return check_html(response.body)
end
##
# Returns a list of download links. An empty list means no new torrents.
#
def check_html(html)
out = []
doc = Nokogiri::HTML(html) { |config| config.nonet }
torrent_rows = doc.css("tr.torrent_1, tr.torrent_2")
torrent_rows.each { |table_row|
next if table_row.css("img[alt=New]").count == 0
dl_link = table_row.at_css("img[alt=DW]").parent["href"]
out << dl_link
}
if VERBOSE
puts "Download links:"
pp out
end
return out
end
def download_torrent(link)
dl_folder = "#{@config["downloads"]}"
response = request(link)
torrent_name = response["Content-Disposition"].split('"').last.strip
dl_target = File.join(dl_folder, torrent_name)
# Saves torrent to disk
File.open(dl_target, "wb") { |file| file.write(response.body) }
return dl_target
end
def request(path)
cookie = @config["cookie"].to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("; ")
headers = HEADERS.merge({"Cookie" => cookie})
return @con.get(path, headers)
end
def connect(host)
con = Net::HTTP.new(host, 443)
con.use_ssl = true
con.verify_mode = OpenSSL::SSL::VERIFY_NONE
con.read_timeout = 5
con.start
puts "# Opened a new connection to: #{host}" if VERBOSE
return con
end
def green_text(text)
"\e[32m#{text}\e[0m"
end
end
FreshontvCheck.main if __FILE__ == $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment