# rbclient_xchat v0.1
__module_name__ = "rb-share"
__module_description__ = "annoy people by telling them what you are listening \
to. Then share it."
__module_version__ = "1"

# turn to False to disable this "feature" 
trigger = "fetch!"
 
 
import xchat 
import commands
import dbus
import string
import gnomevfs

session_bus = dbus.SessionBus()
fetch_is = None


player, player_interface = None, None
def connect_via_dbus():
    # attempts to connect to rhythmbox via dbus
    global player, player_interface
    player = session_bus.get_object('org.gnome.Rhythmbox',
        '/org/gnome/Rhythmbox/Player')
    player_interface = dbus.Interface(player, 
        dbus_interface='org.gnome.Rhythmbox.Player')
    

def get_playing_uri():
    try:
        return player_interface.getPlayingUri()
    except: # TODO: catch the correct exception here
        connect_via_dbus()
        return player_interface.getPlayingUri()


def cmd_np(word, word_eol, userdata):
    global fetch_is 
    fetch_is = None
    
    uri = get_playing_uri()
    if uri and gnomevfs.get_uri_scheme(uri) == 'file':
        fetch_is = gnomevfs.unescape_string_for_display(uri[7:])
        
    xchat.command('me plays: %s%s' %
        (commands.getoutput('rhythmbox-client --print-playing'), 
        fetch_is and ". %s"%trigger or ""))
    return xchat.EAT_ALL


def pm(word, word_eol, userdata):
    if trigger and fetch_is and trigger in word[1:]:
        nick = word[0]
        if xchat.get_prefs("text_color_nicks"):
            nick = nick[3:]
        xchat.prnt("%s said the magic word." % nick)
        xchat.command('dcc send %s "%s"' %(nick, fetch_is))


xchat.hook_command("np", cmd_np)
xchat.hook_print("Channel Message", pm)
xchat.prnt('rb-share.py ready. trigger: %s' % trigger)

