subreddit.rb (1187B)
1 # TODO: convert to rust 2 class Subreddit < Radio 3 require 'json' 4 require 'open-uri' 5 require 'shellwords' 6 7 def initialize(_) 8 puts 'Subreddit has no music posts or does not exist.' while (posts = retrieve_subreddit_posts).empty? 9 @links = extract_post_links(posts) 10 super() 11 rescue Interrupt 12 @channel = nil 13 end 14 15 def play 16 puts "Number of tracks: #{@links.length}" 17 # TODO: support mpd 18 system("mpv --vid=no --volume=50 -- #{@links.map { |l| l[:url] }.shelljoin}") 19 end 20 21 private 22 23 def retrieve_subreddit_posts 24 print 'Enter subreddit name: ' 25 sub = gets.chomp 26 url = "https://www.reddit.com/r/#{sub}/top.json?t=month&limit=100&show=all" 27 URI.parse(url).open('User-Agent' => 'ruby/2.7', 'Accept' => 'application/json') do |response| 28 @channel = sub 29 JSON.parse(response.read)['data']['children'] 30 end 31 rescue OpenURI::HTTPError 32 [] 33 end 34 35 def extract_post_links(posts) 36 posts.each_with_object([]) do |post, links| 37 p = post['data'] 38 if !p['is_self'] && p['post_hint'] != 'image' 39 links.append(title: p['title'], url: p['url'], reddit: "https://reddit.com#{p['permalink']}") 40 end 41 end 42 end 43 end