Skip to content

Instantly share code, notes, and snippets.

@shaiguitar
Created March 27, 2011 15:58
Show Gist options
  • Save shaiguitar/889320 to your computer and use it in GitHub Desktop.
Save shaiguitar/889320 to your computer and use it in GitHub Desktop.
class MigrateMailAppRulesToGmailFilters
require 'pp'
# TODO HERE IS WHERE YOU REQUIRE plist lib.
# There's a good chance you can just "gem install plist"
# But I didn't get there, so I'm just showing you what I hacked up.
# Feel free to gem install and require of course.
Dir.chdir("/Users/shair/work/filters/plist/lib") # this is to require plist below.
require 'plist'
MAIL_API_KEYWORDS = %w(MarkRead CopyToMailboxURL)
## http://code.google.com/googleapps/domain/email_settings/developers_guide_protocol.html#GA_email_filter_main
GOOGLE_API_CRITERIA = [ "from", "to", "subject", "hasTheWord", "doesNotHaveTheWord", "hasAttachment" ]
GOOGLE_API_ACTIONS = [ "label", "shouldMarkAsRead", "shouldArchive" ]
GOOGLE_API_KEYWORDS = (GOOGLE_API_CRITERIA + GOOGLE_API_ACTIONS)
@@all_keys = []
def self.get_all_keys
@@all_keys
end
def do_parse
Plist::parse_xml(File.expand_path("~/Library/Mail/MessageRules.plist"))["rules"].each { |rule|
criteria = rule["Criteria"]
if not criteria.nil?
criteria_arr = criteria.collect{|e| { e["Header"] => e["Expression"] } }
create_xml(criteria_arr,rule)
end
}
end
def create_xml(criteria,rule)
str = String.new
str=<<-EOF
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">
EOF
criteria.each { |c|
c.each{ |k,v|
next unless is_api_compatible?(k)
str<<%Q( <apps:property name="#{k}" value="#{v}" />\n)
}
}
# the "actions" according to the attributes of a Mail.app Rule.
rule.each { |k,v|
if MAIL_API_KEYWORDS.include?(k) && v!="NO"
if k=="MarkRead"
str<<%Q( <apps:property name="shouldMarkAsRead" value="true" />\n)
elsif k=="CopyToMailboxURL"
str<<%Q( <apps:property name="shouldArchive" value="true" />\n)
str<<%Q( <apps:property name="label" value="#{v.gsub("imap://","")}" />\n)
end
end
}
str << " </atom:entry>"
if str.include?("apps:property name") # hack to exclude empty atoms.
puts str
else
puts ""
end
end
# this should work for From/To/Subject.
def is_api_compatible?(str)
GOOGLE_API_KEYWORDS.each {|api| return true if api.downcase==str.downcase }
false
end
def is_not_api_compatible?(str)
! is_api_compatible?(str)
end
end
puts %Q(<?xml version="1.0" encoding="utf-8"?>\n)
MigrateMailAppRulesToGmailFilters.new.do_parse
#puts MigrateMailAppRulesToGmailFilters.get_all_keys.sort.uniq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment