Stream Recording With Ruby

One my favorite Greek journalists recently changed station and timetable. Since my schedule is messed up, I couldn’t listen to the show live. So I wrote a ruby script, as an exercise, to fetch the stream. The script is meant to work with cron.

Here is the code:

real-recording (real-recording.rb) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'syslog/logger'

$log = Syslog::Logger.new 'real-recording'

def get_stream
  Signal.trap("INT") { $log.info "caught in SIGINT! exiting :-)"; exit }
  url = URI.parse('http://realfm2.live24.gr')
  filename = "real-akrivopoulou-#{Time.now.strftime("%d-%m")}.mp3"
  Net::HTTP.start(url.host, 80) do |http|
    f = open(filename, "w")
    begin
      http.request_get('/realfm') do |resp|
        resp.read_body do |segment|
          f.write(segment)
        end
      end
    ensure
      f.close()
    end
  end
end


# Run process in the background
job =  fork do
  exec get_stream
end
$log.info "stream catching started with process pid: #{myproc.pid}"
myproc = Process.detach(job)
sleep 7800 # 2 hours and 10 minutes  in seconds
Process.kill('INT', myproc.pid)

Dumping the stream into an .mp3 file is pretty straight forward. My main problem was how to make the script stay up and running 2 hours and 10 minutes. I opted for sleep method here, but a better way would be to detach the process in the background, save the pid and kill the process later using the predefined pid directory. I wonder if there are drawbacks having a process sleeping for 2 hours, but we’ll see.

When time permits I will roll out a gem to make the whole procedure more secure and easier.