class MixcloudParser::Parser
Public Class Methods
new(url, path)
click to toggle source
# File lib/mixcloud_parser/parser.rb, line 3 def initialize(url, path) @url = url @path = path end
Public Instance Methods
parse()
click to toggle source
Main parser method
# File lib/mixcloud_parser/parser.rb, line 9 def parse # Try parse file begin # Open browser window for getting file name and URL (Mixcloud gives link only after starting a podcast) browser = Watir::Browser.new browser.goto @url # Parse the resulted page through nokogiri page = Nokogiri::HTML(browser.html) # Close browser browser.close # Get file name filename = page.search('cloudcast-title', '//h1').last.content puts "Downloading '#{ filename }'..." # Get file URL url = page.css('audio') url = URI.extract(url.to_s).first # Check the download check_file(url, filename) # Return error message and retry rescue puts 'Error. Retrying...' browser.close retry end end
Private Instance Methods
check_file(url, filename)
click to toggle source
Checking the download
# File lib/mixcloud_parser/parser.rb, line 46 def check_file(url, filename) # Set full file name (with path and extension) filename = @path + filename unless filename.include?(@path) filename += '.m4a' unless filename.include?('m4a') # Create a path if him is not exist FileUtils.mkdir_p(@path) unless File.directory?(@path) # Print message if file successfuly downloaded if File.exist?(filename) && File.size(filename) > 0 puts "#{ filename.split('/').last } successfuly downloaded!" # Download file if him exist, but him size is 0 elsif File.exist?(filename) && File.size(filename) == 0 download_file(url, filename) # Create and download file if him is not exist else File.new(filename, 'w+') download_file(url, filename) end end
download_file(url, filename)
click to toggle source
Downloading
# File lib/mixcloud_parser/parser.rb, line 70 def download_file(url, filename) File.open(filename, 'wb') do |saved_file| open(url) do |read_file| saved_file.write(read_file.read) end end check_file(url, filename) end