Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
Nifty GMail Checker Script
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Unsupported Software
View previous topic :: View next topic  
Author Message
Milez
Tux's lil' helper
Tux's lil' helper


Joined: 21 Aug 2002
Posts: 116
Location: Atlanta, GA

PostPosted: Fri Mar 04, 2005 3:59 am    Post subject: Nifty GMail Checker Script Reply with quote

Hey,
So I just wrote a python based GMail checker that uses pyosd (python bindings to xosd - X onscreen display lib) and feedparser (RSS/Atom parser) to grab GMail atom feeds and tell me what's in my inbox. The results are displayed on the overlay on my screen, and the font and color and stuff are customizable.

Anybody want to use it? Give feedback? One thing I couldn't do was figure out a way to send the password securely. At the moment, I just have the program using wget and http authentication to snag the Atom feed before my program parses it. Feedparser is supposed to provide a mechanism that sends passwords, but it either didn't work or else it just didn't work with GMail.

Libs needed:
feedparser - www.feedparser.org (not in portage yet)
pyosd - emerge pyosd
wget - emerge wget

Here's the program - notice how it's templateable:

Code:

#!/usr/bin/python

TODO = \
    """
     - Make authentication secure.
     - Use feedparser for auth.
     - Improve date format options.
     - Enforce width on all lines, including non $$>'ed lines.
    """
   
import pyosd, feedparser, os
from tempfile import *
       
#Settings & Parameters
##########################
parameters = {
'url' : "http://gmail.google.com/gmail/feed/atom/",
'user' : "", #put your username here
'email' : "", #full email address here
'password' : "", #password here
'hoffset' : 142,
'voffset' : 33,
'width' : 38,
}   
       
osd_settings = {
'font' : "-misc-fixed-medium-r-normal-*-12-*-*-*-*-*-*-*",
'colour' : "white",
'timeout' : 15,
'lines' : 100
}       
##########################
           
#Templates     
##########################
##             
#Any parameter name preceded by a $ will
#get replaced.
## 
#Special template vars:
#   $$t (total number of new emails)
#   $$p (an 's' if $$t > 1, '' otherwise)
#   $$> (everything after will be right justified)
#   $[e [enumerate - only works in email_line]
#   $[s [email subject - only works in email_line]
#   $[f [email from - only works in email_line]
#   $[d [email date - only works in email_line]
#           
templates = {   
'no_new_message' : """\
$email     
No New Messages
""",       
'retrieving' : """\
$email
Retrieving info...
""",
'new_header' : """\
$email
$$t New Message$$p

""",
'email_line' : """\
$[e. $[f $$> $[d
$[s

""",
'email_error_line' : """\
$[e. Error retrieving - probably
related to character encoding.

""",                                                                                                                                          'new_footer' : """\
""",
}
#########################

#Functions
##########################

def osd_print(osd, text, hoffset=0, voffset=0):
    text = text.split("\n")
    line_no = voffset
    max_line_no = osd.get_number_lines()
    for line in text:
        if line_no >= max_line_no: break
        osd.display(" "*hoffset + line,line=line_no)
        line_no += 1

def osd_clear(osd):
    max_line_no = osd.get_number_lines()
    osd.hide()
    for i in range(max_line_no):
       osd.scroll()
    osd.show()

def fill_template(template,paramDict):
    paramList = paramDict.keys(); paramList.sort(); paramList.reverse()
    for param in paramList:
        template = template.replace("$" + param,str(paramDict[param]))
    return template

def fill_special(template,specialDict):
    sList = specialDict.keys(); sList.sort(); sList.reverse()
    for s in sList:
        if len(s) < 3: continue
        if s[1] == '[':
            if specialDict[s] != [] and (s in template):
                val = specialDict[s][0]
                specialDict[s] = specialDict[s][1:]
                template = template.replace(s,str(val))
        else:
            template = template.replace(s,str(specialDict[s]))
    #Do the $$> thing
    tlines = template.split("\n")
    w = parameters['width']
    for i in range(len(tlines)):
        line = tlines[i] #Borrow the line for a second..
        if "$$>" in line:
            right = line[line.index("$$>")+3:][:w]
            left = line[:line.index("$$>")]
            #Definitely keep the right justified stuff
            if len(left+right) > w:
                left = left[:w-len(right)]
            #Or else make sure the right justified stuff is all the way over
            elif len(left+right) < w:
                left = left + " "*(w - len(left+right))
            line = left + right
        tlines[i] = line
    template =  reduce((lambda x,y : x + "\n" + y),tlines)

    return template

##########################

#Set up the on screen display
osd = pyosd.osd(font=osd_settings["font"],colour=osd_settings["colour"], timeout=osd_settings["timeout"],lines=osd_settings["lines"])

#Make a tempfile
feedFile = NamedTemporaryFile('w+b',-1,'.xml','pox')

text = ""
text += fill_template(templates['retrieving'],parameters)
osd_print(osd,text, hoffset=parameters['hoffset'], voffset=parameters['voffset'])

#Grab the feed
os.system("wget -q -O " + feedFile.name + " --http-user=" + parameters['user'] + " --http-passwd=" + parameters['password'] + " " + parameters['url'])

#Parse the feed
feed = feedparser.parse(feedFile.name)

#Begin building output text
text = ""

specialDict = {}

#GMail Specific Code:
#########################
messages = len(feed.entries)
specialDict['$$t'] = messages
specialDict['$$p'] = ''
if messages > 1:
    specialDict['$$p'] = 's'
specialDict['$[s'] = [entry.title for entry in feed.entries]
specialDict['$[f'] = [entry.author_detail.name for entry in feed.entries]
specialDict['$[d'] = ["%d-%d" % entry.issued_parsed[1:3] for entry in feed.entries]
specialDict['$[e'] = [r+1 for r in range(len(feed.entries))]
#########################

if messages > 0:
    text += fill_special(fill_template(templates['new_header'],parameters),specialDict)
    for i in range(messages):
        try:
            text += fill_special(fill_template(templates['email_line'],parameters),specialDict)
        except UnicodeError:
            text += fill_special(fill_template(templates['email_error_line'],parameters),specialDict)
            for key in specialDict.keys():
                if isinstance(specialDict[key],type([])) and key not in templates['email_error_line']: #i.e. if the value is a list that won't get advanced otherwise
                    specialDict[key] = specialDict[key][1:] #advance the list
        else:
            pass
    text += fill_special(fill_template(templates['new_footer'],parameters),specialDict)
else:
    text += fill_special(fill_template(templates['no_new_message'],parameters),specialDict)

#osd_clear(osd)
osd_print(osd,text, hoffset=parameters['hoffset'], voffset=parameters['voffset'])

import time
time.sleep(osd_settings['timeout'])

_________________
-=Miles Stoudenmire=-

Adopt a post initiative


Last edited by Milez on Wed Mar 09, 2005 7:14 am; edited 1 time in total
Back to top
View user's profile Send private message
blaksaga
Guru
Guru


Joined: 19 May 2003
Posts: 461
Location: Omaha, NE, USA

PostPosted: Tue Mar 08, 2005 9:26 pm    Post subject: Reply with quote

That's a pretty cool script. Mind if I use it? I cut it down to a single function that simply returns how many unread emails you have.

Code:

#!/usr/bin/python

import feedparser, os
from tempfile import *

def checkmail ( user, password ) :

   parameters = {
      'url' : "http://gmail.google.com/gmail/feed/atom/",
      'user' : user,
      'password' : password
   }

   #Make a tempfile
   feedFile = NamedTemporaryFile('w+b',-1,'.xml','pox')

   #Grab the feed
   os.system("wget -q -O " + feedFile.name + " --http-user=" + parameters['user'] + " --http-passwd=" + parameters['password'] + " " + parameters['url'])

   #Parse the feed
   feed = feedparser.parse(feedFile.name)

   messages = len(feed.entries)

   return messages

_________________
[ blaksaga.com ]
Back to top
View user's profile Send private message
Milez
Tux's lil' helper
Tux's lil' helper


Joined: 21 Aug 2002
Posts: 116
Location: Atlanta, GA

PostPosted: Tue Mar 08, 2005 9:32 pm    Post subject: Reply with quote

Thanks. Yeah, no problem, go for it.
_________________
-=Miles Stoudenmire=-

Adopt a post initiative
Back to top
View user's profile Send private message
blaksaga
Guru
Guru


Joined: 19 May 2003
Posts: 461
Location: Omaha, NE, USA

PostPosted: Wed Mar 09, 2005 6:34 am    Post subject: Reply with quote

I turned your script into a nice gdesklet control and currently have it running on my desktop.

http://gdesklets.gnomedesktop.org/categories.php?func=gd_show_app&gd_app_id=240

I've been meaning to do something like this for a long while and you made my job a hell of a lot easier. :)
_________________
[ blaksaga.com ]
Back to top
View user's profile Send private message
Milez
Tux's lil' helper
Tux's lil' helper


Joined: 21 Aug 2002
Posts: 116
Location: Atlanta, GA

PostPosted: Wed Mar 09, 2005 7:13 am    Post subject: Reply with quote

Excellent - I need to give gdesklets a try again. I installed it once, and it looked cool, but ran really slowly. However, my computer's been running a lot more quickly since I installed 2.6.10 kernel.

Also, something I need to do with this code (and maybe you can help me) is use feedparser's built in support for grabbing password protected xml feeds from the web. The wget thing is just a workaround, even if everyone and their brother has wget. Like I said in the first post, I tried using feedparser to do all of the work, but after I followed the instructions in the feedparser docs explicitly, things still didn't work. I probably just need to contact the feedparser guy.
_________________
-=Miles Stoudenmire=-

Adopt a post initiative
Back to top
View user's profile Send private message
srlinuxx
l33t
l33t


Joined: 22 Nov 2003
Posts: 627

PostPosted: Wed Mar 09, 2005 3:54 pm    Post subject: Reply with quote

I'm sure you gents are aware that you can pop gmail right?
_________________
--You talk the talk, but do you waddle the waddle?
-Gentoo Monthly Screenshots
Back to top
View user's profile Send private message
blaksaga
Guru
Guru


Joined: 19 May 2003
Posts: 461
Location: Omaha, NE, USA

PostPosted: Wed Mar 09, 2005 5:52 pm    Post subject: Reply with quote

srlinuxx wrote:
I'm sure you gents are aware that you can pop gmail right?


Ya but I've never had any luck using pop notification applets. This way of checking by xml is quick and works without a hitch.
_________________
[ blaksaga.com ]
Back to top
View user's profile Send private message
timseal
n00b
n00b


Joined: 29 Apr 2002
Posts: 40
Location: Philadelphia

PostPosted: Fri Mar 18, 2005 8:41 pm    Post subject: Reply with quote

pop is also not an option for those of us behind company firewalls. rdf=freedom :)
Back to top
View user's profile Send private message
Gherald
Veteran
Veteran


Joined: 23 Aug 2004
Posts: 1399
Location: CLUAConsole

PostPosted: Thu Mar 24, 2005 1:52 am    Post subject: Reply with quote

Milez wrote:
One thing I couldn't do was figure out a way to send the password securely. At the moment, I just have the program using wget and http authentication to snag the Atom feed before my program parses it. Feedparser is supposed to provide a mechanism that sends passwords, but it either didn't work or else it just didn't work with GMail.

FWIW, the much simpler notifier I wrote a couple months ago uses libgmail and is probably more secure.

But this atom feed and pyosd stuff is pretty nifty.
Back to top
View user's profile Send private message
xsong
n00b
n00b


Joined: 26 Nov 2004
Posts: 27

PostPosted: Tue Sep 13, 2005 10:50 pm    Post subject: Reply with quote

Excellent work!!!!
_________________
----------------------------------------------------
You should work really hard to earn a decent life!!
Do I? Don't I?
---------------------------------------------------
Back to top
View user's profile Send private message
emrys404
n00b
n00b


Joined: 18 Oct 2004
Posts: 50

PostPosted: Sat Dec 30, 2006 4:02 am    Post subject: Reply with quote

Okay i redid this script in php for the fun of it, plus this thread was a bit dated when i found it and didnt work for me:

Code:

#!/usr/local/bin/php -q
<?php
$username = ""; //username goes here no @gmail.com needed
$password = ""; // pasword goes here obviously

$data = exec("wget -O - --http-user=$username --http-passwd=$password https://mail.google.com/mail/feed/atom/ 2> /dev/null");
preg_match('#<fullcount[^>]*>(.*?)<\/fullcount>#i',$data,$matches);
echo $matches[1];
?>

All it does is tell me how many unread messages i have, i use it in conky
_________________
-blar
Back to top
View user's profile Send private message
Dralnu
Veteran
Veteran


Joined: 24 May 2006
Posts: 1919

PostPosted: Sun Dec 31, 2006 6:43 am    Post subject: Reply with quote

emrys404 wrote:
Okay i redid this script in php for the fun of it, plus this thread was a bit dated when i found it and didnt work for me:

Code:

#!/usr/local/bin/php -q
<?php
$username = ""; //username goes here no @gmail.com needed
$password = ""; // pasword goes here obviously

$data = exec("wget -O - --http-user=$username --http-passwd=$password https://mail.google.com/mail/feed/atom/ 2> /dev/null");
preg_match('#<fullcount[^>]*>(.*?)<\/fullcount>#i',$data,$matches);
echo $matches[1];
?>

All it does is tell me how many unread messages i have, i use it in conky


Love how to redirect the errors into nothingness. Maybe that should go to a log or something?
_________________
The day Microsoft makes a product that doesn't suck, is the day they make a vacuum cleaner.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Unsupported Software All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum