Wednesday, June 08, 2011

FBNotify.py

#coding=utf-8
#FBNotify.py: Facebook Simple Notifier
#  by Herry Limantoro (mataherry@gmail.com)
#
#NOTE: Don't forget to Add the Mechanize source folder into your SL4A scripts folder (/mnt/sdcard/sl4a/scripts)
#      http://wwwsearch.sourceforge.net/mechanize/download.html


import android
import time
import sys
import traceback
import urllib
import mechanize
import BeautifulSoup
import re

droid = android.Android()

#Setup Browser
br = mechanize.Browser()
br.set_handle_redirect(True)
br.set_handle_robots(False)

#User Agent, can't do without it
br.addheaders = [('User-agent','Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

url = 'http://m.facebook.com/notifications.php'

#Set username password here, leave blank to prompt for username/password
username = ''
password = ''

#Set run interval (in minutes), prompt if 0
interval = 0

def get_interval():
  droid.dialogCreateAlert('Run interval (in minutes)')
  droid.dialogSetItems(['5', '15','30','60'])
  droid.dialogShow()
  response = droid.dialogGetResponse().result['item']
  if response == 0:
    interval = 5
  elif response == 1:
    interval = 15
  elif response == 2:
    interval = 30
  elif response == 3:
    interval = 60
  print "Run every " + str(interval) + " minutes"
  return interval

def run_loop():
  val = True
  errcount = 0

  #keep CPU run, still can't find other workaround
  droid.wakeLockAcquirePartial()

  while val:
    runTime = time.strftime('%Y%m%d %H%M', time.localtime())
    print 'Run at: ' + runTime
    try:
      val = get_notifications()
    except Exception, err:
      print err
      droid.notify('FBNotify Error at ' + runTime, str(err) + '\nCheck SL4A Console for detail')
      traceback.print_exc()
      errcount = errcount + 1

    #last 3 run produce exception
    if errcount > 3:
      val = False
    
    if val:
      time.sleep(interval * 60)

  droid.wakeLockRelease()

def get_notifications():
  print 'Connecting to Facebook...'
  br.open(url)

  if br.viewing_html() is False:
    print 'Viewing HTML Error'
  elif 'Notifications' in br.title(): 
    #Already logged in
    print 'Notification page'
    process()
  else:
    #Redirected to Login Form
    print 'Login ' + username

    #Select Form, Fill in username password, and Submit
    br.select_form(nr=0)
    br.form['email'] = username
    br.form['pass'] = password
    resp = br.submit()

    if br.viewing_html() is False:
      print 'Viewing HTML Error!'
    elif 'Notifications' in br.title():
      print 'Logged In! Notification page'
      process()
    else:
      #if not logged in, most likely wrong username password
      print 'Login Error!'
      #Play some tone
      droid.mediaPlay('/sdcard/media/facebook_ringtone_pop.m4a')
      droid.vibrate(500)
      droid.notify('FB Login Error - Program Exit','Check your username password')
      #logical thing to do is exit program
      return False

  return True

def process():
  soup = BeautifulSoup.BeautifulSoup(br.response().read())

  #Get all classes containing 'acw apm' (Check your FB notifications.php source if different)
  nodes = soup.findAll('div',{'class':re.compile(r'.*\bacw apm')})
  msg = ''
  count = 0
  for node in nodes:
    line = ''
    for content in node.contents:
      try:
        line = line + content.string
      except:
        line = line

    #New notification indicator
    dot = u'•'
    if line != '':
      #print out all notifications
      print line.encode('utf-8')

      #collect the new ones only to notify
      if line[0] == dot:
        if count == 0:
          msg = line
        else:
          msg = msg + '\n' + line
        count = count + 1

  if count > 0:
    print 'New notifications:'
    print msg.encode('utf-8')

    #Play some tone
    droid.mediaPlay('/sdcard/media/facebook_ringtone_pop.m4a')
    droid.vibrate(500)

    #display notification
    droid.notify('You have ' + str(count) + ' FB notifications', msg)

    #uncomment to show toast message
    #droid.makeToast(msg)
  else:
    print 'No new notification'

#Main program
valid = True
try:
  if username == '':
    username = droid.dialogGetInput('Username','Your Facebook username').result

  if password == '':
    password = droid.dialogGetPassword('Password', 'For ' + username).result

  if interval == 0:
    interval = get_interval()
except:
  valid = False

if valid:
  run_loop()

No comments:

Post a Comment