#!/usr/local/bin/python

# By Phillip Bogle  http://www.thebogles.com

# Copyright 2004  Phillip Bogle
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.

# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, distributed
# under the License is distributed on an "AS IS" WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or See the License for the
# specific language governing permissions limitations under the License.

                           


from pybloglines import BloglinesWebServices
import Cookie
import urllib2
import cgi
import os
import time
from random import *
seed()

def build_http_date (when):
    return time.strftime ('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(when))
    

def writeLoginCookies(email, password):
    cookie = Cookie.SmartCookie()
    cookie["email"] = form["email"].value
    cookie["email"]['expires'] = 864000000
    cookie["password"] = form["password"].value
    cookie["password"]['expires'] = 864000000

    print cookie
    

form = cgi.FieldStorage()

loggedIn = False

email = None
password = None

if form.has_key("submit"):
    try:
        email = form.getfirst("email", "")
        password = form.getfirst("password", "")
        writeLoginCookies(email, password)
        loggedIn = True
    except:
        pass
else:
    try:
        cookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", ""))
        email = cookie.get("email", None).value
        password = cookie.get("password", None).value
        loggedIn = email and password
    except:
        pass

if not loggedIn:
    print "Location:/login.py\n\n"
elif not email or not password:
    print "Location:/login.py?err=Password%20Required\n\n"    
else:
    try:
        bws = BloglinesWebServices(email, password)
        if form.has_key('mr'):
            bws.getitems(form['mr'].value, True)

        feeds = bws.listsubs()
    except urllib2.HTTPError:
        print "Location:/login.py\n\n"
        loggedIn = False
    except:
        print "Content-Type: text/html\n\n"
        print """
        <html><h3>Berry Bloglines Error</h3>Unable to parse your list of subscriptions.  Do you have a folder name with an '&' in it?  Please try renaming it on your PC.</html>"""
        loggedIn = False


if loggedIn:
    print "Content-Type: text/html\n\n"
    print """
    <META HTTP-EQUIV="Expires" CONTENT="%s">  
    """ % (build_http_date(time.time() + 60*60*24*2))
    if len(feeds)==0:
        print "You currently have no feeds"
    print '<title>Berry Bloglines</title><br><form method="post"><input type="submit" value="Refresh"></form>'  
    print '<ol>'
#    print '<li><a href="/cgi-bin/news.py">Google News</a>'
    for feed in feeds:
        try:
            if (feed.bloglinesUnread > 0):
                print '<li><a href="showfeed.py?id=%s">%s</a>&nbsp;&nbsp;(%d)<br>' % (feed.bloglinesSubId, feed.title, feed.bloglinesUnread)
            else:
                print '<li><font color="gray">%s</font>&nbsp;&nbsp;(%d)<br>' % (feed.title, feed.bloglinesUnread)                
        except:
            pass
    print '</ol><br><br><hr><br><a href="/logout.py">Log out </a><hr><a href="/berry411.jad">Try Berry411 Mobile Search</a> (FREE)</html>'
    
