#!/usr/bin/env python
import dbus, urllib2, re, json, hashlib

PHOTO_PATH='/etc/freesmartphone/opim/photos/photodl/'

def getDbusObject (bus, busname , objectpath , interface):
  dbusObject = bus.get_object(busname, objectpath)
  return dbus.Interface(dbusObject, dbus_interface=interface)

def download(type, id, url):
  filename = PHOTO_PATH+type+'/'+id+'.jpg'
  print "downloading "+url+" to "+filename
  file = open(filename, 'w')
  photo = urllib2.urlopen(url)
  file.writelines(photo.readlines())
  file.close()
  return filename

bus = dbus.SystemBus()

contacts = getDbusObject (bus, "org.freesmartphone.opimd", "/org/freesmartphone/PIM/Contacts", "org.freesmartphone.PIM.Contacts")

def facebook():
  x = contacts.Query({'Facebook':'.*'})
  query = getDbusObject (bus, "org.freesmartphone.opimd", x, "org.freesmartphone.PIM.ContactQuery")

  results = query.GetMultipleResults(-1)

  for result in results:
    try:
      fb = urllib2.urlopen("http://facebook.com/people/opimd-fbupdate/"+result['Facebook'])
    except:
      try:
        fb = urllib2.urlopen("http://facebook.com/"+result['Facebook'])
      except:
        print result['Facebook']+' not found!'
        continue
    page = fb.readlines()
    r = re.compile(r"<img class=\"photo img\" src=\"([^ ]+)\" alt=\"")
    text = ''
    for line in page:
      text = text + line
    url = r.findall(text)
    if url:
      filename = download('facebook', result['Facebook'], 'http://facebook.com'+url[0])
      if not 'Photo' in result:
        con = getDbusObject (bus, "org.freesmartphone.opimd", result['Path'], "org.freesmartphone.PIM.Contact")
        con.Update({'Photo':filename})
    else:
      print result['Facebook']+' not found'

def gg():
  x = contacts.Query({'>Gadu-Gadu':'0'})
  query = getDbusObject (bus, "org.freesmartphone.opimd", x, "org.freesmartphone.PIM.ContactQuery")

  results = query.GetMultipleResults(-1)

  for result in results:
    try:
      filename = download('gg', result['Gadu-Gadu'], 'http://avatars.gadu-gadu.pl/200x200/'+result['Gadu-Gadu'])
      if not 'Photo' in result:
        con = getDbusObject (bus, "org.freesmartphone.opimd", result['Path'], "org.freesmartphone.PIM.Contact")
        con.Update({'Photo':filename})
    except:
      print result['Gadu-Gadu']+' not found'

def statusnet():
  print "Not yet implemented"

def blip():
  x = contacts.Query({'Blip':'.*'})
  query = getDbusObject (bus, "org.freesmartphone.opimd", x, "org.freesmartphone.PIM.ContactQuery")

  results = query.GetMultipleResults(-1)

  for result in results:
    try:
      data = json.load(urllib2.urlopen("http://blip.pl/users/"+result['Blip']+"/avatar"))
      filename = download("blip", result['Blip'], data['url'])
      if not 'Photo' in result:
        con = getDbusObject (bus, "org.freesmartphone.opimd", result['Path'], "org.freesmartphone.PIM.Contact")
        con.Update({'Photo':filename})
    except:
      print result['Blip']+' not found'

def twitter():
  x = contacts.Query({'Twitter':'.*'})
  query = getDbusObject (bus, "org.freesmartphone.opimd", x, "org.freesmartphone.PIM.ContactQuery")

  results = query.GetMultipleResults(-1)

  for result in results:
    try:
      data = json.load(urllib2.urlopen("http://api.twitter.com/users/show/"+result['Twitter']+".json"))
      if "default_profile" in data['profile_image_url']:
        raise IOError()
      filename = download("twitter", result['Twitter'], data['profile_image_url'])
      if not 'Photo' in result:
        con = getDbusObject (bus, "org.freesmartphone.opimd", result['Path'], "org.freesmartphone.PIM.Contact")
        con.Update({'Photo':filename})
    except:
      print result['Twitter']+' not found'


def gravatar():
  x = contacts.Query({'E-mail':'.*'})
  query = getDbusObject (bus, "org.freesmartphone.opimd", x, "org.freesmartphone.PIM.ContactQuery")

  results = query.GetMultipleResults(-1)

  for result in results:
    try:
      if isinstance(result['E-mail'], list):
        result['E-mail']=result['E-mail'][0] # FIXME
      hash = hashlib.md5(result['E-mail'].lower()).hexdigest()
      data = json.load(urllib2.urlopen("http://gravatar.com/"+hash+".json"))
      print data
      filename = download("gravatar", hash , data['entry'][0]['thumbnailUrl'])
      if not 'Photo' in result:
        con = getDbusObject (bus, "org.freesmartphone.opimd", result['Path'], "org.freesmartphone.PIM.Contact")
        con.Update({'Photo':filename})
    except ValueError as e:
      print result['E-mail']+' not found ' + str(e)


print "Facebook:"
facebook()

print "Gravatar:"
gravatar()

print "StatusNet:"
statusnet()

print "Blip:"
blip()

print "Twitter:"
twitter()

print "Gadu-Gadu:"
gg()
