#!/usr/bin/env python

import feedparser, serial, time, urllib2, subprocess, lxml.html as lh				#to be able to 'import' them, all of the above libraries have to be installed on your RasPi

DEBUG = 1													

USERNAME = "fullnestfullnestfullnest"     					# Here is where you enter YOUR email details: for username - just the part before the @ sign,
PASSWORD = "aishasaulenurzhan"     	  						# and your password 

# And so, 'NEWMAIL_OFFSET' is a first step - in it 'feedparser' will use the above details to get to your email and count (ie."fullcount") the full number of new/unread emails.
NEWMAIL_OFFSET = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
MAIL_CHECK_FREQ = 0.5      									# Here, you set up how frequently you want 'feedparser' to check your mail. Mine is set to every half-a-second (0.5).

port = "/dev/ttyACM0" 										#this identifies the port to which Arduino is connected
serialFromArduino = serial.Serial(port, 9600) 				#this starts serial communication between RasPi and Arduino.


while True:													# Next is the 'actual task', which RasPi will be performing: 

        newmails = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
        # In 'newmails' step it will go to your inbox and count new emails, again. 

        if DEBUG:
            print "You have", newmails, "new emails!"		# then, it will print how much 'newmails' you have

        if newmails > NEWMAIL_OFFSET:						# compare the number of 'newmails' to 'NEWMAIL_OFFSET'(ie.first step/performed earlier) and, if the number of 'newmails'
                serialFromArduino.write('a')				# is greater than 'NEWMAIL_OFFSET' (ie.you have a new email), it will send 'small 'a'' command to Arduino, ordering it
                											# to 'raise the flag'. (note:consult the corresponding Arduino sketch to see what Arduino is doing/waiting to do)

                d = feedparser.parse("http://our-fullnest.tumblr.com/rss")		# Once the flag is raised, the newest 'image' from our Tumblr blog should be fetched.
                e = d['entries'][0]												# These 5 steps do that: 'feedparser' goes to the blog's rss feed, grabs the latest/newest entry (0),
                doc = lh.document_fromstring(e["description"])					# 'lh'(lxml html) grabs that entry's 'description' of 'img src' (image source) - something that looks
                value = doc.xpath('//img/@src')									# like this: <img src="http://37.media.tumblr.com/9f6b24138dbe6bab879012003410d6bf
                value = "".join(value)											# /tumblr_n6q36sFsVq1tcyq2go1_500.jpg"/><br/><br/> and defines it as a 'value'.
                print value														

                subprocess.call(["wget", value])								# Finally,'subprocess' gets ('wget's) this 'value' and passes it on to 'fbi'(framebuffer image)
                subprocess.call(["sudo","fbi","-T","2","-d","/dev/fb1","-noverbose","-a", value[60:]])							# program (also needs to be installed), which,
																				# in turn, takes this 'value' - subtracts '60' symbols in the beginning from it to reach
                NEWMAIL_OFFSET = NEWMAIL_OFFSET + 1								# the 'pure' file name (eg.tumblr_n6q36sFsVq1tcyq2go1_500.jpg) and uses this 'pure file name' to display
                																# the post in question on the RasPi's screen. (note:'60' is true for my Tumblr posts - you should
                																# determine yours by counting how many characters are there from the beginning of " until YOUR 'pure filename')
                																
        		# The last step  'NEWMAIL_OFFSET = NEWMAIL_OFFSET + 1' - adds '1' to the NEWMAIL_OFFSET's fullcount of emails, meaning that the program will no longer need to do
        		# the 'NEWMAIL_OFFSET' check itself. It would simply add '1', each time the 'if' condition is true ie. when there IS a new mail.
    
         #else:				#this are the 'remnants' of the previous script - this would order Arduino to 'lower the flag' if there are no new emails.
             #serialFromArduino.write('A')		#For Fullnest, we don't need it, since the flag is lowered manually with a button, by the receiving party.

        time.sleep(MAIL_CHECK_FREQ)	# program sleeps for half-a-second. Tah-dam! That's it! The script for displaying newest Tumblr posts and notifying you with a raised flag is ready!