#!/usr/bin/env ruby unless maildir = ARGV[0] puts 'Usage: script/process_mails directory [time between checks in minutes]' puts 'Example: script/process_mails Maildir/.Rails/new 5' exit end sleeptime = ARGV[1].to_i require File.dirname(__FILE__) + '/../config/environment' require 'fileutils' require 'breakpoint' def do_update puts "Reading last update time from last_update.yaml... " begin from = YAML.load(File.read(RAILS_ROOT + '/last_update.yaml')) puts "done." rescue puts "could not load file. Using default (1 day ago)." from = 1.day.ago end puts "Updating index starting from #{from.to_s}..." last_update = Time.now number = Post.search_handler.rebuild_index(from).size puts "done (#{number} posts)." puts "Saving last update time to last_update.yaml... " File.open(RAILS_ROOT + '/last_update.yaml', 'w') do |file| file.write(last_update.to_yaml) end puts "done." end def do_import(maildir) puts "Checking for new mails" Dir[File.join(maildir, '*')].each do |file| begin if Mailer.process_email(File.read(file)) puts "Imported #{file}" File.delete(file) else puts "Could not import #{file}" end rescue => e if e.is_a? Iconv::InvalidEncoding puts "Skipped file #{file} (invalid encoding)" FileUtils.move(file, RAILS_ROOT + '/mails/rejected/invalid_encoding/') rescue ArgumentError elsif e.message['messageid : has already been taken'] puts "Skipped & deleted file #{file} (messageid already in database)" File.delete(file) rescue ArgumentError elsif e.is_a? RForum::ValidationError puts "Skipped file #{file} (ValidationError): #{e.inspect}" FileUtils.move(file, RAILS_ROOT + '/mails/rejected/validation_error/') rescue ArgumentError elsif e.message['parent not found'] puts "Skipped file #{file} (parent not found): #{e.inspect}" FileUtils.move(file, RAILS_ROOT + '/mails/rejected/parent_not_found/') rescue ArgumentError else puts "Skipped file #{file} (unknown error): #{e.inspect}" FileUtils.move(file, RAILS_ROOT + '/mails/rejected/unknown_error/') rescue ArgumentError end end end end if sleeptime == 0 do_import(maildir) else loop do do_import(maildir) GC.start do_update() GC.start puts "sleeping for #{sleeptime} minutes..." sleep sleeptime * 60 end end