#!/usr/bin/env ruby
class User
require 'rubygems'
require 'sqlite3'
def self.db
SQLite3::Database.new(File.join(ENV["HOME"], "tumblr.db"))
end
def self.create_table
db.execute("CREATE TABLE users (email varchar, email_login varchar, password varchar)");
end
def self.find(email)
begin
email_login, password = db.get_first_row("SELECT email_login, password FROM users WHERE email = ?", email)
rescue SQLite3::SQLException
create_table
end
if (email_login && password)
return {:email => email_login, :password => password}
end
nil
end
def self.add(email, email_login, password)
begin
db.execute("DELETE FROM users WHERE email = ?", email) if (find(email))
rescue SQLite3::SQLException
create_table
end
db.execute("INSERT INTO users (email, email_login, password) VALUES (?, ?, ?)", email, email_login, password)
end
end
class Tumblr
require 'net/http'
def initialize(email, password)
@email, @password = email, password
end
def post_regular(subject, body)
params = {
'email' => @email,
'password' => @password,
'type' => "regular",
'title' => subject,
'body' => body
}
res = Net::HTTP.post_form(URI.parse("http://www.tumblr.com/api/write"), params)
end
end
class Part
require 'base64'
attr_reader :content_type, :filename, :contents
def initialize(text)
@filename = ""
header, body = text.split("\n\n")
@content_type = header.match(/Content-Type: (.*);/i)[1]
@filename = header.match(/filename="(.*)"/)[1] if header.match(/filename="(.*)"/)
if (header.match(/Content-Transfer-Encoding: base64/))
@contents = Base64.decode64(body)
else
@contents = body
end
end
end
email = STDIN.read
# email = open('email2.txt').read
from = email.match(/^From:.*[^a-zA-Z0-9\.\-_]([a-zA-Z0-9\.\-_]+@[\w\.-]+)/)[1]
subject = email.match(/^Subject: (.*)$/)[1]
boundary = email.match(/boundary="(.*)"/)[1] if email.match(/boundary="/)
post_body = ""
if boundary # multi-part
email.sub!(/^.+?[^"]#{boundary}/m, '')
email.split(/-*#{boundary}/).each do |part|
next if part.empty? or part.match(/^-+$/)
p = Part.new(part)
post_body = p.contents if (p.content_type == "text/plain")
# TODO - upload images to tumblr. This pulls them from sane emails
# open(p.filename, 'w') {|f| f.puts p.contents } if (!p.filename.empty?)
end
else
email.sub!(/^.+?\n\n/m, '')
post_body = email
end
if (post_body.match(/email:/i) && post_body.match(/password:/i))
User.add(from, post_body.match(/email:(.*)$/i)[1], post_body.match(/password:(.*)$/i)[1])
else
user = User.find(from)
t = Tumblr.new(user[:email], user[:password])
t.post_regular(subject, post_body)
end