aboutsummaryrefslogtreecommitdiffstats
path: root/lib/seventy_eights/application.rb
blob: afe59145795ade847000e2b4759d0a2b0f6346d4 (plain) (blame)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Copyright (C) 2014 Harald Eilertsen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

require_relative 'record'
require 'nokogiri'
require 'open-uri'

module SeventyEights
  class Application
    def initialize(site_url, target_dir)
      @site = site_url
      @target_dir = target_dir
      @records = []
    end

    def run
      read_site
      parse
      download_files
    end

    private

    def read_site
      puts "Opening #{@site}..."
      @doc = Nokogiri::HTML(open(@site, :http_basic_authentication => %w{New090908  654321}))
    end

    def parse
      puts "Parsing..."
      @doc.xpath('//tr').each do |row|
        columns = row.xpath('td')
        if columns.size >= 4
          link = columns[0].xpath('a/@href').text
          title = columns[0].xpath('a/b').text
          artist = columns[1].text
          label = columns[2].text
          catalog = columns[3].text
          unless link.empty?
            @records << Record.new(title, artist, label, catalog, URI.parse(link))
          end
        end
      end
    end

    def download_files
      puts "Downloading #{@records.size} tracks..."
      i = 1
      @records.each do |r|
        outfile = File.join(@target_dir, r.to_filename)
        if File.exists?(outfile)
          puts "Skipping #{i}: #{r.title} by #{r.artist}..."
        else
          puts "#{i}: #{r.title} by #{r.artist}..."
          track = open(r.url, :http_basic_authentication => %w{New090908  654321})
          IO.write(outfile, track.read)
        end
        i += 1
      end
    end

  end
end