class Soundyoink::Audio
Represents an audio post; given only a link, can name the file intelligently and write it to disk, as well as check whether the file has already been downloaded.
Public Class Methods
new(url)
click to toggle source
Drawing the title from the URL is a little uglier than drawing it from the page text itself, but lets us skip files we already have without having to request the page. This saves a ton of time on user profiles. @param url [String] URL for a specific audio post.
# File lib/soundyoink/audio.rb, line 10 def initialize(url) user = url.match(%r{\/u\/(.+)\/})[1] title = url.match(%r{\/u\/.+\/(.+)})[1] @filename = "#{user} - #{title}.m4a" unless already_exists? @file_url = open(url).read.match(%r{(https://.+net/sounds/.+[.]m4a)})[1] end end
Public Instance Methods
already_exists?()
click to toggle source
Check that not only does the file exist, but that it is over 10 KB, so that we can overwrite files that were opened but never written properly. @return [Boolean]
# File lib/soundyoink/audio.rb, line 44 def already_exists? File.exist?(@filename) && File.size(@filename) > 10_000 end
download()
click to toggle source
Writes the file to disk (in the form _author - title.m4a_) unless it already exists and is over 10 KB.
# File lib/soundyoink/audio.rb, line 21 def download return nil if already_exists? bar = ProgressBar.create(title: 'Downloading', format: '%t |%B| %p%') filesize = nil puts @filename target = open(@file_url, 'rb', content_length_proc: -> (size) { filesize = size }, progress_proc: lambda do |accumulated| # Set bar.progress to the 'percent complete' figure bar.progress = (accumulated.to_f / filesize * 100).to_i end ) File.open(@filename, 'wb') do |f| while chunk = target.read(1_000_000) f.write(chunk) end end puts "\n" end