shokai / Flickr downloader

Flickr download tool written with Ruby.

Flickr downloader / FlickrAPI.rb
r3:4dd993a2dee3 98 loc 2.0 KB embed / history / annotate / raw /
require 'uri'
require 'rexml/document'

class FlickrAPI
  def initialize(api_key, api_secret)
    @api_key = api_key
    @api_secret = api_secret
  end
  
  def search(tags, user)
    tags = URI.encode(tags)
    photos = Array.new
    page = 1
    while(true) do
      uri = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=#{@api_key}&tags=#{tags}&tag_mode=all&user_id=#{user}&page=#{page}"
      puts uri
       doc = REXML::Document.new(open(uri).read)
      REXML::XPath.each(doc, '//photo/attribute::id'){ |id|
        photos << id
      }
      pages = REXML::XPath.first(doc, '//photos/attribute::pages').value.to_i
      break if page >= pages
      print "(#{page}/#{pages}) "
      page += 1
      sleep 3
    end
    photos
  end
  
  def getInfo(id)
    info = PhotoInfo.new
    uri = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=#{@api_key}&photo_id=#{id}"
    doc = REXML::Document.new(open(uri).read)
    info.id = REXML::XPath.first(doc, '//photo/attribute::id')
    info.farm = REXML::XPath.first(doc, '//photo/attribute::farm')
    info.server = REXML::XPath.first(doc, '//photo/attribute::server')
    info.secret = REXML::XPath.first(doc, '//photo/attribute::secret')
    info.o_secret = REXML::XPath.first(doc, '//photo/attribute::originalsecret')
    info.format = REXML::XPath.first(doc, '//photo/attribute::originalformat')
    return info
  end

end

class PhotoInfo
  def farm=(val)
    @farm = val
  end
  
  def farm
    @farm
  end
  
  def server=(val)
    @server = val
  end
  
  def id
    @id
  end

  def id=(val)
    @id = val
  end
  
  def secret
    @secret
  end
  
  def secret=(val)
    @secret = val
  end
  
  def o_secret
    @o_secret
  end
  
  def o_secret=(val)
    @o_secret = val
  end
  
  def format
    @format
  end

  def format=(val)
    @format = val
  end
  
  def photo_uri
    "http://farm#{@farm}.static.flickr.com/#{@server}/#{@id}_#{@secret}.jpg"
  end
  
  def original_uri
    "http://farm#{@farm}.static.flickr.com/#{@server}/#{@id}_#{@o_secret}_o.#{@format}"
  end
  
end