Skip to content

Instantly share code, notes, and snippets.

@sirishn
Last active December 11, 2018 08:33
Show Gist options
  • Save sirishn/6328860 to your computer and use it in GitHub Desktop.
Save sirishn/6328860 to your computer and use it in GitHub Desktop.
tumblr downloader, download all pictures and videos from a tumblog usage ruby tumblr.rb blog #ofposts(optional) example ruby tumblr.rb internet.tumblr.com ruby tumblr.rb internet.tumblr.com 50
#!/usr/bin/ruby
# Tumblr downloader (video and images only)
require 'rubygems'
require 'open-uri'
require 'json'
def get_media(blog, max_posts)
@key = "fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4"
# ;)
@blog = blog
puts "Blog: #{@blog}"
@offset = 0
@url = "http://api.tumblr.com/v2/blog/#{@blog}/posts?api_key=#{@key}&offset=#{@offset}"
@posts = JSON.parse(open(@url).read)
@num_of_posts = @posts["response"]["total_posts"]
puts "Total posts: #{@num_of_posts}"
@max_posts = @num_of_posts
@max_posts = [max_posts.to_i, @num_of_posts].min unless max_posts == nil
puts "Grabbing #{@max_posts} posts"
Dir.mkdir(@blog) unless File.directory?(@blog)
while @offset < @max_posts
media_url = ""
@url = "http://api.tumblr.com/v2/blog/#{@blog}/posts?api_key=#{@key}&offset=#{@offset}"
@posts = JSON.parse(open(@url).read)
@posts["response"]["posts"].each do |post|
media_url = post["video_url"] if post["type"] == "video"
if post["type"] == "photo"
post["photos"].each do |photo|
media_url = photo["original_size"]["url"]
end
end
puts post["type"]
puts media_url
begin
if ["photo", "video"].include? post["type"]
filename = File.basename(URI.parse(media_url).path)
unless File.exist?(@blog+"/"+filename)
File.open(@blog+"/"+filename, 'wb') do |fo|
fo.write open(media_url).read
end
end
end
rescue
next
end
end
@offset += 20
end
end
if __FILE__ == $0
blog = ARGV[0]
max_posts = ARGV[1]
get_media blog, max_posts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment