radio-rs

Place a description here.
git clone git://git.alex.balgavy.eu/reponame.git
Log | Files | Refs

radiogarden.rb (1521B)


      1 # TODO: convert to rust
      2 class RadioGarden < Radio
      3   require 'json'
      4   require 'open-uri'
      5   require 'cgi'
      6 
      7   def initialize(_)
      8     @base_url = 'https://radio.garden/api'
      9     puts 'No radio found, please try again.' while (retrieved_channels = search_channels).empty?
     10     channels = parse_channels(retrieved_channels)
     11     selected_channel = choose_from_list(channels, channels.map { |c| c[:name] }) while selected_channel.nil?
     12     @channel = get_channel_link(selected_channel)
     13     super()
     14   rescue Interrupt
     15     @channel = nil
     16   end
     17 
     18   def play
     19     if @player == 'mpc'
     20       system 'mpc', 'clear', 1 => '/dev/null'
     21       system 'mpc', 'add', @channel
     22     end
     23     super @channel
     24   end
     25 
     26   private
     27 
     28   def search_channels
     29     print 'Enter radio search: '
     30     query = gets.chomp
     31     URI.parse("#{@base_url}/search?q=#{CGI.escape query}").open do |response|
     32       JSON.parse(response.read)['hits']['hits']
     33     end
     34   rescue OpenURI::HTTPError
     35     []
     36   end
     37 
     38   def get_channel_link(selected_channel)
     39     # Will redirect
     40     @channel = URI.parse("#{@base_url}/ara/content/listen/#{selected_channel[:id]}/channel.mp3").open(redirect: false)
     41   rescue OpenURI::HTTPRedirect => e
     42     @channel = e.uri.to_s.gsub(/\?listening-from.*/, '')
     43   rescue OpenURI::HTTPError
     44     @channel = None
     45   end
     46 
     47   def parse_channels(retrieved_channels)
     48     retrieved_channels.inject([]) do |channels, c|
     49       channels << { name: "#{c['_source']['title']} (#{c['_source']['subtitle']})",
     50                     id: c['_source']['channelId'] }
     51     end
     52   end
     53 end