Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count the number of read messages in your gmail inbox
require 'util'
require 'lib/imap_patch'
## gmail zero game (from Gemfile)
# gem 'gmail', '= 0.4.0',
# :git => 'https://github.com/nu7hatch/gmail.git',
# :branch => 'master'
class GmailCount
def self.perform(user,goal)
msg_count = nil
msgids = nil
begin
Timeout::timeout(60*11) {
Gmail.connect(:xoauth, user.uid,
:token => user.token,
:secret => user.secret,
:consumer_key => CLIENT_KEY,
:consumer_secret => CLIENT_SECRET
) do |gmail|
# gmail zero only counts read messages:
msgids = gmail.inbox.emails(:read).map { |msg| msg.uid }
if msgids.empty? || msgids.count > 1000
# we found that counting up the read threads took forever if they've
# got somewhere upwards of 1000 total messages, so in this case
# we use bare msg count, but it seems to be preferable to use
# the thread count, as below, since that is what gmail natively
# shows to the user.
msg_count = msgids.count
else
msg_count = gmail.conn.uid_fetch(msgids, '(X-GM-THRID)').map{|msg|
msg.attr['X-GM-THRID'].to_s(16)
}.uniq.size
end
end
}
rescue Exception => e
if e.class.to_s == "Net::IMAP::BadResponseError"
# then user revoked access, so do stuff to remove their
# auth info and stop polling
else
# other logging
end
# ... and then quit
return
end
# then i do some things to reduce amount of data added. maybe
# it would be best to explicitly over-write today's datapoint
# if existing, unless you actually wanted to collect info
# about your email reading and answering habits, in which case
# i guess you'd want to add data every time. anyway, you
# may want to do more data processing at this point
goal.add_datapoint(Time.now.to_i, msg_count, "auto-entered by gmailzero")
# finally, i check if the user is off track for today, and if it is past
# noon, send them a reminder about it.
end
end
end # class GmailCount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.