Skip to content

Instantly share code, notes, and snippets.

@dpick
Created July 29, 2012 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpick/3200431 to your computer and use it in GitHub Desktop.
Save dpick/3200431 to your computer and use it in GitHub Desktop.
Mountain Lion Gmail Notifications
#! /usr/bin/ruby
require 'net/https'
def previous_count_location
Dir.mkdir('/Users/davidpick/.gmail_notifier') unless File.directory?('/Users/davidpick/.gmail_notifier')
'/Users/davidpick/.gmail_notifier'
end
def baseurl_for(name)
account_domain = name.split("@")
if account_domain.length == 2 && !["gmail.com", "googlemail.com"].include?(account_domain[1])
"https://mail.google.com/a/#{account_domain[1]}/"
else
"https://mail.google.com/mail"
end
end
def message(hash)
"#{hash[:title]} => #{hash[:unread_count]}" unless hash[:unread_count] == 0
end
def check(hash)
http = Net::HTTP.new("mail.google.com", 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = nil
result = { :error => "ConnectionError", :count => 0, :messages => [] }
http.start do |http|
req = Net::HTTP::Get.new("/mail/feed/atom")
req.basic_auth(hash[:username], hash[:password])
response = http.request(req)
end
if response
case response.code
when "401" #HTTPUnauthorized
result[:error] = "UserError"
when "200" #HTTPOK
# oops, response.body should be utf-8
xml = response.body
# messages count
result[:count] = /<fullcount>(\d+)<\/fullcount>/.match(xml)[1]
end
end
result
end
gmails = [
{ :title => "Gmail", :username => 'pickdavid', :password => '' },
{ :title => "Groupon", :username => 'dpick@groupon.com', :password => '' }
]
gmails.each_with_index do |gmail_hash, i|
count = check(gmail_hash)[:count].to_i
previous_count = -1
previous_count = File.open(previous_count_location + '/' + gmail_hash[:title], 'r').read.strip.to_i if File.exists?(previous_count_location + '/' + gmail_hash[:title])
if !count.zero? && count > previous_count
File.open(previous_count_location + '/' + gmail_hash[:title], 'w') { |f| f.write(count) }
system "/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -message '#{gmail_hash[:title]} => #{count}' -title 'Gmail Notifier' -group '123456#{i}' -open '#{baseurl_for(gmail_hash[:username])}'"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment