maildrop_serializer.rb 1.37 KB
class MaildropSerializer
  def serialize(filters)
    filters.map do |filter|
      ["# filter '#{filter.name}'",
       "if (#{filter_expressions(filter)})",
       "{",
       "  exception {",
       "    `test -d '#{dest_folder(filter)}'`",
       "    if( $RETURNCODE == 1 )",
       "    {",
       "      `maildirmake #{dest_folder(filter)}`",
       "    }",
       "    to #{dest_folder(filter)}",
       "  }",
       "}"].join("\n")
    end.join("\n\n")
  end
  
  private
  
  def dest_folder(filter)
    '$DEFAULT/' << filter.destination_folder.sub(Regexp.new("(INBOX)(.*)"), '\2')
  end
  
  def escape_expr_value(text)
    text.gsub(".", "\\.").gsub("*", "\\*").gsub("[", "\\[").gsub("]", "\\]").gsub("(", "\\(").gsub(")", "\\)").
      gsub("?", "\\?")
  end
  
  def filter_expressions(filter)
    fe = ""
    for exp in filter.expressions 
      post_flag = ""
      fe << " #{filter.operator} " unless fe == ""
      if exp.field_name == "Body"
        fe << "/"
        post_flag = "b"
      else
        fe << "/^#{exp.field_name}:"
      end
      if exp.operator == 'contains'
        fe << ".*(#{escape_expr_value(exp.expr_value)})/"
      else
        # starts with
        fe << "[ ]*(#{escape_expr_value(exp.expr_value)}).*/"
      end
      if exp.case_sensitive == 1
        fe << "D" << post_flag
      else
        fe << post_flag  
      end  
    end  
    fe
  end
end