#!/usr/bin/python
# -*- coding: utf-8 -*-

#codded by Petrkr
#if you need help / suggestions fell free to write me
#at IRC as petrkr @ SynIRC @ #strazci-vesmiru
#at E-Mail or MSN or Jabber: petrkr <at> petrkr <dot> net
#at ICQ 146 530 439

#COMMANDS
#========
#/amarok			#show ad about now playing song
#/amarok-bw			#same but black/white
#/amarok-reply %nick		#as first one, but its used notice to some user (used by CTCP Reply)
#/amarok-send %nick		#send song over DCC (used by CTCP Reply)
#/amarok-psend %nick		#send song over Passive DCC (used by CTCP Reply)

#Instalation
#===========
#in Xchat you must add CTCP replies for send and play trigger to works
#Settings --> Advanced --> CTCP Replies
#add new ones, there are a format>>>
#NAME - COMMAND
#amarok - amarok-send %s
#amarok-play - amarok-reply %s
#for passive sends (if you're firewalled) use amarok-psend instead amarok-send
#put file into ~/.xchat2/ folder for auto-load
#or load it using Window --> Plugins and Scripts --> Load --> Browse to this file

#for different notice, colors etc. edit marked lines below...

#changelog
#1.2
# - changed default encoding to utf-8

#1.1
# - supports for " in filename / path

#1.0
# - finally Unicode should work
# - sending over TDCC works now too


import xchat, time, urllib
import dbus,sys

__module_name__ = "Amarok 2.x"
__module_version__ = "1.2"
__module_description__ = "Now Playing song in Amarok 2.x"

#site.setencoding()



#to work this line comment 
#these lines in /usr/lib/python2.6/site.py
#lines about 512
#    if hasattr(sys, "setdefaultencoding"):
#            del sys.setdefaultencoding

#if you know how else override default ascii encoding 
#or prevent this error UnicodeEncodeError: 'ascii' codec can't encode characters in position 28-31: ordinal not in range(128) in Xchat.Command(SAY...) line... let me know please

sys.setdefaultencoding('utf-8')

def amarokGet():
	am = dbus.SessionBus().get_object('org.kde.amarok','/Player')
	data = am.GetMetadata()
	if len(data) == 0:
		playing=0
		return {'playing': playing}
	else:
		playing=1
		title = unicode(data['title'])
		artist = unicode(data['artist'])
		#tady to vycte taky OK, printem to taky vypise OK,
		album = unicode(data['album'])
		bitrate = data['audio-bitrate']
		sample = data['audio-samplerate']
		total_time = time.strftime('%H:%M:%S', time.gmtime(data['time']))
		current_time = time.strftime('%H:%M:%S', time.gmtime(am.PositionGet()/1000))
		umisteni = data['location']

		return {'playing': playing, 'artist': artist, 'title': title, 'album': album, 'total_time': total_time, 'current_time': current_time, 'location': str(umisteni), 'bitrate': bitrate, 'samplerate': sample}


def nowPlayingREPLY(word, word_eol, userdata):
    snick = word[1]

    return xchat.EAT_ALL


def nowPlaying(word, word_eol, userdata):
	nick = xchat.get_info("nick")
	data = amarokGet()
	if not data['playing']:
        	xchat.command("ME 's Amarok didn't play anything at this moment!")
	else:
		if data['title'] == "" :
        		song = song2
		else:
	        	song = unicode("%s - \00303%s - \00311%s" % (data['artist'],data['title'],data['album']))

#edit this for another Ad format
		out = unicode("\00308%s \017(\00302%s\017/\00304%s\017) - \00306%s \017kbit \00306%s \017Hz\017" % (song, data['current_time'], data['total_time'],  data['bitrate'], data['samplerate']))
#and this
		xchat.command("ME 's Amarok now playing %s - \037TDCC Trigger\017 [ \00304/ctcp %s amarok\017 ] - \037Playback Trigger\017 [ \00304/ctcp %s amarok-play\017 ]" % (out,nick,nick))

	return xchat.EAT_ALL

def nowPlayingBW(word, word_eol, userdata):

	nick = xchat.get_info("nick")
	data = amarokGet()
	if not data['playing']:
        	xchat.command("ME 's Amarok didn't play anything at this moment!")
	else:
		if data['title'] == "" :
        		song = song2
		else:
	        	song = "%s - %s - %s" % (data['artist'],data['title'],data['album'])
#edit this for another Ad format
		out = u"%s (%s/%s) - %s kbit %s Hz" % (song, data['current_time'], data['total_time'],  data['bitrate'], data['samplerate'])
#and this
	        xchat.command("SAY *75**240* Amarok now playing %s - TDCC Trigger [ /ctcp %s amarok ] *240**75*" % (out,nick))
	return xchat.EAT_ALL

def amarokSend(word, word_eol, userdata):
    nick = word[1]
    data = amarokGet();
    if not data['playing']:
        xchat.command("NOTICE %s Amarok didn't play anything at this moment!" % (nick))
    else:
        if data['location'].find("file:///") == 0:
		file=urllib.unquote(data['location'].split("file://")[1]).replace('"','""')
	        xchat.command("DCC SEND %s \"%s\"" % (nick, file))
	else:
		xchat.command("NOTICE %s Amarok now playing unsendable file: %s" % (nick,data['location']) )

    return xchat.EAT_ALL

def amarokSendP(word, word_eol, userdata):
    nick = word[1]
    data = amarokGet();
    if not data['playing']:
        xchat.command("NOTICE %s Amarok didn't play anything at this moment!" % (nick))
    else:
        if data['location'].find("file:///") == 0:
		file=urllib.unquote(data['location'].split("file://")[1]).replace('"','""')
	        xchat.command("DCC PSEND %s \"%s\"" % (nick, file))
	else:
		xchat.command("NOTICE %s Amarok now playing unsendable file: %s" % (nick,data['location']) )

    return xchat.EAT_ALL


xchat.hook_command("AMAROK-SEND", amarokSend, help="/AMAROK-SEND Send actually played song")
xchat.hook_command("AMAROK-PSEND", amarokSendP, help="/AMAROK-PSEND Send actually played song using reverse connection")
xchat.hook_command("AMAROK-REPLY", nowPlayingREPLY, help="/AMAROK-REPLY This is for /ctcp AMAROK trigger")
xchat.hook_command("AMAROK-BW", nowPlayingBW, help="/AMAROK-BW Black and White modification")
xchat.hook_command("AMAROK", nowPlaying, help="/AMAROK Regular script")

