Sha256: 3a287db7074884e24a424a97ff7ab8bdc19b065466258bb5ccdc53974683439d

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

require 'json'
require 'bremen/base'

module Bremen
  class Soundcloud < Bremen::Base
    BASE_URL = 'http://api.soundcloud.com/'
    self.default_options = {
      keyword: '',
      order: 'created_at', #created_at/hotness
      limit: 50,
      filter: '', #(all)/public/private/streamable/downloadable
    }

    class << self
      attr_accessor :consumer_key

      def build_query options = {}
        raise %Q{"#{self.name}.consumer_key" must be set} unless consumer_key
        super(options.merge(consumer_key: consumer_key))
      end

      def find_url uid_or_url
        if uid_or_url.to_s =~ %r{\A\d+\Z}
          "#{BASE_URL}tracks/#{uid_or_url}.json?#{build_query}"
        else
          "#{BASE_URL}resolve.json?#{build_query({url: uid_or_url})}"
        end
      end

      def search_url options = {}
        options = default_options.merge(options)
        query = {
          q: options[:keyword],
          order: options[:order],
          limit: options[:limit],
          filter: options[:filter],
        }
        "#{BASE_URL}tracks.json?#{build_query(query)}"
      end

      def from_api hash = {}
        new({
          uid: hash['id'],
          url: hash['permalink_url'],
          title: hash['title'],
          author: Bremen::Author.new({
            uid: hash['user']['id'],
            url: hash['user']['permalink_url'],
            name: hash['user']['username'],
            thumbnail_url: hash['user']['avatar_url'].sub(%r{\?.*}, ''),
          }),
          length: (hash['duration'].to_i / 1000).round,
          thumbnail_url: hash['artwork_url'] ? hash['artwork_url'].sub(%r{\?.*}, '') : nil,
          created_at: Time.parse(hash['created_at']),
          updated_at: Time.parse(hash['created_at']),
        })
      end

      private
      def convert_singly response
        from_api(JSON.parse(response))
      end

      def convert_multiply response
        JSON.parse(response).map{|t| from_api(t) }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bremen-0.1.2 lib/bremen/soundcloud.rb