#!/usr/bin/env ruby

=begin
	Library for grab all daily Explore images on Flickr.com 
	Copyright (C) 2006  Michele Ferretti
	
	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 2
	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, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
=end

require 'net/http'
require 'date'

FlickrPhoto = Struct.new(:author, :title, :server, :photoid, :secret, :photosize)

class DayExplorePhotosGrabber

	def initialize()
		now 	= DateTime::now()
		@day 	= now.day()
		@month 	= now.month()
		@year	= now.year()
	end
	
	def httpGrabber(url)
		url = URI.parse(url)
		req = Net::HTTP::Get.new(url.path)
		res = Net::HTTP.start(url.host, url.port) {|http|
			http.request(req)
		}
		return res
	end
	private :httpGrabber
	
	def grab(year=nil, month=nil, day=nil)

		flickr_photos = Array.new
		
		day 	||= @day
		month 	||= @month
		year 	||= @year
		
		single_day_url = "http://flickr.com/explore/interesting/#{year}/#{month}/#{day}/"

		res = httpGrabber(single_day_url)

		if res.code.to_i == 302
			single_day_url = "http://flickr.com"+ res['Location']
		end
		
		res = httpGrabber(single_day_url)
		
		1.upto(50) do |i|
			res = httpGrabber("#{single_day_url}page#{i}")
			
			res.body.scan(/<a href="\/photos\/(.+)\/.+".*title="(.+)">.*com\/([0-9]+)\/([0-9]+)_([0-9_a-z_A-Z]+)_([a-z]{1})/) { 
				|author,title,server,photoid,secret,photosize|
				
				flickr_photo = FlickrPhoto.new(author, title, server, photoid, secret, photosize)
				flickr_photos.push(flickr_photo)
			}
		end

		return flickr_photos
	end
end

