Automatically downloads YT subscriptions

youtube.rb 2.4KB

    class Youtube def self.update_from_subs() Channel.all.each do |s| begin h = self.get_channel_videos(s.url) s.name = h["title"] s.save h["entry"].each do |v| if Video.find_by(video_url: v["link"]["href"]).nil? a = s.videos.create(title: v["title"], description: v["group"]["description"], video_id: v["videoId"], video_url: v["link"]["href"], published_date: v["published"].to_datetime, is_downloaded: false, thumbnail_url: v["group"]["thumbnail"]["url"]) #Get thumbnail a.remote_thumb_url = a.thumbnail_url a.save end end rescue if s.name.nil? s.name = "BROKEN!" s.save end end end end def self.get_channel_videos(s) url = "https://www.youtube.com/feeds/videos.xml?channel_id=#{s}" xml = Net::HTTP.get(URI.parse(url)) h = Hash.from_xml(xml) return h["feed"] end def self.scrape_videos Video.where(is_downloaded: false).order(published_date: :desc).each do |v| v.is_downloaded = nil #In progress v.save cmd = "youtube-dl -ciw -o \"#{v.local_path}\" #{v.video_url}" filename = `#{cmd} --get-filename`.delete("\n").delete("\r") puts `#{cmd}` if !File.exist?(filename) filename = filename.rpartition('.')[0] + ".mkv" end if File.exist?(filename) puts `ffmpeg -n -i #{filename} #{v.local_path_ext} && rm #{filename}` else puts "#{filename} DNE!" end if File.exist?(v.local_path_ext) #Success v.is_downloaded = true v.save else v.is_downloaded = false v.save puts "ERROR: Was unable to scrape video #{v.id}" end end end def self.remove_broken_vids vids = Video.where(is_downloaded: true) vids.each do |v| if !File.exist?(v.local_path_ext) v.is_downloaded = false v.save end end end #def self.download_channel(s) # channel = "https://www.youtube.com/user/#{s}" # cmd = "/usr/bin/youtube-dl -f best -ciw -o \"#{Rails.root.to_s}/public/videos/#{s}/%(title)s.%(ext)s\" -v #{channel}" # `#{cmd}` #end end