Class: Echonest::ApiMethods::Track

Inherits:
Base
  • Object
show all
Defined in:
lib/echonest/api.rb

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Echonest::ApiMethods::Base

Instance Method Details

#analysis(filename) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/echonest/api.rb', line 123

def analysis(filename)
  md5 = Digest::MD5.hexdigest(open(filename).read)
  cache_path = DIRECTORY + 'analysis' + md5

  if File.exists?(cache_path)
    analysis = Analysis.new(open(cache_path).read)
  else
    analysis = Analysis.new_from_url(analysis_url(filename, md5))
    cache_path.dirname.mkpath
    open(cache_path, 'w') do |file|
      file.write analysis.json
    end
  end

  analysis
end

#analysis_url(filename, md5) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/echonest/api.rb', line 140

def analysis_url(filename, md5)
  while true
    begin
      response = profile(:md5 => md5)
    rescue Api::Error => e
      if e.message =~ /^The Identifier specified does not exist/
        response = upload(:filename => filename)
      else
        raise
      end
    end

    case response.body.track.status
    when 'unknown'
      upload(:filename => filename)
    when 'pending'
      sleep 60
    when 'complete'
      return response.body.track.audio_summary.analysis_url
    when 'error'
      raise Error.new(response.body.track.status)
    when 'unavailable'
      analyze(:md5 => md5)
    end

    sleep 5
  end
end

#analyze(options) ⇒ Object



99
100
101
102
103
# File 'lib/echonest/api.rb', line 99

def analyze(options)
  @api.request('track/analyze',
    :post,
    options.merge(:bucket => 'audio_summary'))
end

#profile(options) ⇒ Object



93
94
95
96
97
# File 'lib/echonest/api.rb', line 93

def profile(options)
  @api.request('track/profile',
    :get,
    options.merge(:bucket => 'audio_summary'))
end

#upload(options) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/echonest/api.rb', line 105

def upload(options)
  options.update(:bucket => 'audio_summary')

  if options.has_key?(:filename)
    filename = options.delete(:filename)
    filetype = parse_filetype(filename)

    open(filename) do |f|
      @api.request('track/upload',
        :post,
        options.merge(:filetype => filetype),
        f)
    end
  else
    @api.request('track/upload', :post, options)
  end
end