#!/usr/bin/python

# This will monitor dbus and do various useful things on gajim events.
#
# bluegraydragon@gmail.com

import gobject, os
import dbus
if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
    import dbus.glib

OBJ_PATH = '/org/gajim/dbus/RemoteObject'
INTERFACE = 'org.gajim.dbus.RemoteInterface'
SERVICE = 'org.gajim.dbus'

def check_mail(details):
    print '%s has %s new emails' %(details[1][0], details[1][1])
    os.system('/usr/bin/fetchmail')     # fetchmail daemon mode works well here

def print_contact(details):
    print '%s is online' %details[1][0] 
    if details[1][0].startswith('mygirlfriend'):
	os.system('alsaplayer -l 0.2 -i text "oursong.mp3"')     # do something special for someone special ;)

def init(service, arg1, arg2):
    if service == 'org.gajim.dbus':
	bus = dbus.SessionBus()	
	try:
	    bus.add_signal_receiver(check_mail, 'NewGmail', INTERFACE, SERVICE, OBJ_PATH)
	    bus.add_signal_receiver(print_contact, 'ContactPresence', INTERFACE, SERVICE, OBJ_PATH)
	    print 'added gajim signal receivers'
	except:
	    print 'oops, no gajim'


def main():
    bus = dbus.SessionBus()
    bus.add_signal_receiver(init, 'NameOwnerChanged',
	    'org.freedesktop.DBus',
	    'org.freedesktop.DBus',
	    '/org/freedesktop/DBus',
	    arg0='org.gajim.dbus')   # monitor changes in gajim dbus signal

    init('org.gajim.dbus', '', '')
    
    print 'listening to dbus...'
    mainloop = gobject.MainLoop()
    mainloop.run()
		
if __name__ == '__main__':
    import sys
    try:
	main()
    except KeyboardInterrupt:
	sys.exit(0)
