#!/usr/bin/ruby require 'tmail' require 'net/smtp' require "RMagick" require "base64" # ルートパスの設定 require 'pathname' ROOT = Pathname.new(File.expand_path(__FILE__)).parent.to_s # ログの設定 require 'logger' $log = Logger.new(ROOT + "/entry.log") $log.level = Logger::INFO # ERROR, FATAL, WARN, INFO, DEBUG $log.info("------------------") TEMP_PATH = ROOT + "/temp.jpg" # メールの受け取り # /home/tumb-r/.forward から標準入力経由でメールが渡される # TMail形式で読み込み def receive_mail begin mail_text = STDIN.read raise if mail_text == nil or mail_text == "" mail = TMail::Mail.parse(mail_text) rescue $log.error("input mail malformed") exit else process_mail(mail) end end # メールの処理メイン def process_mail(mail) $log.info("starting process_mail") mail = rewrite_destination(mail) mail = rewrite_attachment(mail) send_mail(mail) $log.info("completed process_mail") end # 宛先の書き換え def rewrite_destination(mail) mail["to"] = mail.to[0].sub("@tumb-r.com", "@tumblr.com") return mail end # 添付ファイルの編集 def rewrite_attachment(mail) src_img_data = pop_attachment(mail) dest_img_data = rewrite_img(src_img_data) mail = push_attachment(mail, dest_img_data) return mail end # 添付ファイルを取り除いてバイナリデータを返す # 前提: 処理対象の画像はメールの最後のpartに書かれている def pop_attachment(mail) attachment = mail.parts.pop attachment.base64_decode return attachment.body end # 添付ファイルの追記 def push_attachment(mail, img_data) attachment = TMail::Mail.new attachment.body = Base64.encode64(img_data) attachment.transfer_encoding = 'base64' attachment.set_content_type('image', 'jpg', 'name' => 'temp.jpg') attachment.set_content_disposition('attachment', 'filename' => 'temp.jpg') mail.parts.push(attachment) return mail end # 画像を編集してバイナリデータを返す def rewrite_img(src_data) src_img = Magick::Image.from_blob(src_data) dest_img = src_img[0].rotate(-90) #左に90度回転 return dest_img.to_blob end # メールを送信 # TODO: 循環送信の中止 def send_mail(mail) $log.info("starting send_mail") Net::SMTP.start("localhost", 25) {|smtp| smtp.send_mail(mail.encoded, mail.from, mail.to) } $log.info("completed send_mail") end receive_mail