Skip to content

Instantly share code, notes, and snippets.

@o-sam-o
Created June 16, 2015 04:31
Show Gist options
  • Save o-sam-o/5b07eb220d2e91aad976 to your computer and use it in GitHub Desktop.
Save o-sam-o/5b07eb220d2e91aad976 to your computer and use it in GitHub Desktop.
flickr_to_tumblr.rb
require 'mechanize'
require 'json'
require 'awesome_print'
require 'tumblr_client'
require 'base58'
require 'net/http'
require 'tempfile'
require 'uri'
FLICKR_API_KEY = "3fffd0917fa897e24bd5a442018df29a"
FLICKR_PHOTOSET = "72157625277593652"
ALREADY_POSTED_FILE = "/home/sam/Programming/Ruby/flick_tumblr/already_posted.txt"
Tumblr.configure do |config|
config.consumer_key = "..."
config.consumer_secret = "..."
config.oauth_token = "..."
config.oauth_token_secret = "..."
end
def post_photo_to_tumblr(flickr_url, description, image_url)
p "Attempting to post photo '#{description}' #{flickr_url} #{image_url}"
client = Tumblr::Client.new
result = client.photo("o-sam-o.tumblr.com", {:source => image_url, :caption => description, :link => flickr_url})
p "Posted with photo #{result}"
p "Done"
end
class FlickrPhoto
def initialize(photo_json)
@json = photo_json
end
def photo_id
@json['id']
end
def title
@json['title']
end
def flickr_url
"https://flic.kr/p/#{Base58.encode photo_id.to_i}"
end
def image_url
@json['url_m']
end
def to_s
"#{title} (#{photo_id})"
end
end
def random_flickr_photo
p "Fletching flickr photos for photoset #{FLICKR_PHOTOSET}"
agent = Mechanize.new
photos = []
page_count = 1
json_results = {}
begin
p "Fetch page #{page_count}"
page = agent.get "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&page=#{page_count}&api_key=#{FLICKR_API_KEY}&photoset_id=#{FLICKR_PHOTOSET}&format=json&nojsoncallback=1&extras=url_m"
json_results = JSON.parse(page.body)
photos = photos + json_results['photoset']['photo'].collect {|j| FlickrPhoto.new(j)}
page_count = page_count + 1
end while json_results['photoset']['total'].to_i > photos.size
p "Fetched #{photos.size} photos"
already_posted = IO.read(ALREADY_POSTED_FILE).split("\n").collect { |s| s.strip }.uniq rescue []
photos.reject! { |p| already_posted.include? p.photo_id }
raise "No photos to post!" if photos.empty?
p "Unposted photos #{photos.size}"
return photos.sample
end
photo = random_flickr_photo
p "Posting photo #{photo}"
post_photo_to_tumblr photo.flickr_url, photo.title, photo.image_url
open(ALREADY_POSTED_FILE, 'a') { |f| f << "#{photo.photo_id}\n" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment