#!/usr/bin/python -u
# -*- coding: UTF8 -*-
#
# PyRSS         Python based RSS reader for jabber
# Copyright:    2004 Rafal Zawadzki e-mail/jid: <bluszcz@jabberpl.org>
# Licence:      GPL v2
# Requirements: feedparser - http://diveintomark.org/projects/feed_parser/
#               pyxmpp - http://jabberstudio.org/projects/pyxmpp/project/view.php


# Added by St. Hermann <sh@sourcecode.de>

try: 
    import psyco
    psyco.full()
except:
    pass
from optparse import OptionParser
import sys
import logging
import MySQLdb
import feedparser
import md5
import time
import xml.dom.minidom
import thread
import re

import traceback
from pyxmpp.jid import JID
from pyxmpp.all import Iq
from pyxmpp.all import StreamError
from pyxmpp.all import ClientStream
from pyxmpp.all import Presence
from pyxmpp.all import Message

from pyxmpp.jabber.disco import DiscoInfo
from pyxmpp.jabber.disco import DiscoItem
from pyxmpp.jabber.disco import DiscoItems
#import JID fbrom pyxmpp.jid
#from pyxmpp import JID
import pyxmpp.jabberd.all
import pyxmpp.jabber.all
import pyxmpp.all
programmName="pyrss.py"
programmVersion="0.9.9.1"


# Added by St. Hermann <sh@sourcecode.de>
# use OptionParser instead of getopt directly
optParser=OptionParser(usage="%prog [options]",
		       version="%prog "+programmVersion)

optParser.add_option("-c",
		     "--config-file",
		     dest="configFile",
		     help="Specify your configfile for "+programmName,
		     metavar="CONFIGFILE",
		     default="/etc/jabber/pyrss.xml")

(options,args)=optParser.parse_args()

config=options.configFile;


adminjid=[]
dom = xml.dom.minidom.parse(config)
dbhost = dom.getElementsByTagName("dbhost")[0].childNodes[0].data
dbuser =  dom.getElementsByTagName("dbuser")[0].childNodes[0].data
database =  dom.getElementsByTagName("database")[0].childNodes[0].data
dbpassword = dom.getElementsByTagName("dbpassword")[0].childNodes[0].data
name =  dom.getElementsByTagName("name")[0].childNodes[0].data
host =  dom.getElementsByTagName("host")[0].childNodes[0].data
port =  dom.getElementsByTagName("port")[0].childNodes[0].data
password = dom.getElementsByTagName("password")[0].childNodes[0].data
loglevel = dom.getElementsByTagName("loglevel")[0].childNodes[0].data
notpurge = dom.getElementsByTagName("actual")[0].childNodes[0].data
for i in dom.getElementsByTagName("admin"):
        adminjid.append(i.childNodes[0].data)
last_poll=300


def printdebug(debuglog, fromlog=""):
	if loglevel != "False" : 
		print "LOG: " + str(debuglog) +" "+fromlog
	

class Database:
    def __init__(self,stream=None):
    	printdebug("Database __init__")
	global dbhost, dbuser, database, dbpassword
        printdebug(dbhost+" "+dbuser)
        self.stream=stream
	self.connection=MySQLdb.connect(user=dbuser,passwd=dbpassword,db=database,host=dbhost)
	self.connection.threadsafety=1
	self.dbcursor=self.connection.cursor()

    def showoutdatedsentmd5(self, namerss):
    	printdebug("showsentmd5")
	global notpurge
	stringtoexecute="select md5 from sent where namerss='"+namerss+"' order by datetime desc limit "+notpurge+",20000; "
	printdebug(stringtoexecute)
	#stringtoexecute="select md5 from sent where namerss='osnews' order by datetime desc limit "+notpurge+",20000; "
	#select * from sent where namerss='osnews' order by datetime desc limit 25,20000; 
        self.dbcursor.execute(stringtoexecute)
	return self.dbcursor.fetchall()
	
    def deleteoutdatedsents(self, namerss, md5):
    	printdebug("deleteoutdatedsents")
	printdebug(namerss+":::"+md5)
	stringtoexecute="delete from sent where namerss='"+namerss+"' and md5='"+md5+"';"
	printdebug(stringtoexecute)
	self.dbcursor.execute(stringtoexecute)

	

	
    def purgedatabase(self):
    	printdebug("purgedatabase")
	for i in self.showsubsnamerss():
		for j in self.showoutdatedsentmd5(i[0]):
			self.deleteoutdatedsents(i[0], j[0])
			#self.deleteoutdatedsents("osnews", j[0])
		
		
    def addrss(self, name,url,time=None):
    	printdebug("addrss")
	#alobal connection
	if time is None:
            time = 10
        stringtoexecute="INSERT INTO addressess(name,url,time) VALUES('"+name+"','"+url+"','"+str(time)+"');"
        self.dbcursor.execute(stringtoexecute)
        self.commit()

    def deluser(self, stanza, jid):
    	printdebug("deluser")
        global name
        stringtoexecute="SELECT namerss FROM subs WHERE jid='"+jid+"'"
        self.dbcursor.execute(stringtoexecute)
        for ii in self.dbcursor.fetchall():
            jidfrom=ii[0]+"@"+name
            p=Presence(from_jid=str(jidfrom),to_jid=str(jid),stanza_type="unsubscribed")
            self.stream.send(p)
	stringtoexecute="DELETE FROM subs WHERE jid='"+jid+"'"
        self.dbcursor.execute(stringtoexecute)
	
    def checknewadd(self, name, url):
    	printdebug("checknewadd")
        stringtoexecute="SELECT name,url FROM addressess WHERE name='"+name+"' OR url='"+url+"'"
        self.dbcursor.execute(stringtoexecute)
        return self.dbcursor.rowcount==0 and True or False

    def checksubsduplicate(self, name, namerss):
    	printdebug("checksubsduplicate")
        stringtoexecute="SELECT jid,namerss FROM subs WHERE jid='"+name+"' AND namerss='"+namerss+"'"
        self.dbcursor.execute(stringtoexecute)
        if self.dbcursor.rowcount==0:
            return True
        else:
            return False


    def checkname(self, name):
    	printdebug("checkname")
        stringtoexecute="SELECT name,url FROM addressess WHERE name='"+name+"'"
        self.dbcursor.execute(stringtoexecute)
        if self.dbcursor.rowcount==1:
            return True
        else:
            return False
            
    def delrss(self, namerss):
    	printdebug("delrss")
        stringtoexecute="DELETE FROM addressess WHERE name='"+namerss+"'"
        self.dbcursor.execute(stringtoexecute)
        stringtoexecute="DELETE FROM subs WHERE namerss='"+namerss+"'"
        self.dbcursor.execute(stringtoexecute)
        stringtoexecute="DELETE FROM sent WHERE namerss='"+namerss+"'"
        self.dbcursor.execute(stringtoexecute)
	
    def listrss(self, id=None):
    	printdebug("listrss")
        stringtoexecute="SELECT * FROM addressess"
        self.dbcursor.execute(stringtoexecute)
        return self.dbcursor.fetchall()

    def subscriberss(self, name, namerss):
    	printdebug("subscriberss")
    	#global connection
        if self.checksubsduplicate(name, namerss):
            stringtoexecute="INSERT INTO subs(jid,namerss) VALUES('"+name+"','"+namerss+"');"
            self.dbcursor.execute(stringtoexecute)
            self.commit()
        else:
            pass
    def unsubscriberss(self, name, namerss):
    	printdebug("unsubscriberss")
    	#global connection
        stringtoexecute="DELETE FROM subs WHERE jid='"+name+"' AND namerss='"+namerss+"';"
        self.dbcursor.execute(stringtoexecute)
        self.commit()

    def insertnewrss(self,namerss, md5):
    	printdebug("insertnewrss")
    	#global connection
        stringtoexecute="INSERT INTO sent(namerss,md5,datetime) VALUES('"+namerss+"','"+md5+"','"+time.strftime("%Y-%m-%d %H:%M:%S")+"');"
        printdebug(stringtoexecute)
	self.dbcursor.execute(stringtoexecute)
        self.commit()
    
    def setpresence(self, nametoset=None, jidtoset=None):
    	printdebug("setpresence")
    	#connection=MySQLdb.connect(user=dbuser,passwd=dbpassword,db=database,host=dbhost)
	#dbcursor=connection.cursor()
    	global name
	if nametoset==None:
		stringtoexecute="SELECT url,name FROM addressess";
	else:
		stringtoexecute="SELECT url,name FROM addressess WHERE name='"+nametoset+"'"
	self.dbcursor.execute(stringtoexecute)
	lista1=self.dbcursor.fetchall()
	for jj in lista1:
		output=self.parse(jj[0])
		if jidtoset==None:
			stringtoexecute="SELECT jid,namerss FROM subs WHERE namerss='"+jj[1]+"'"
			self.dbcursor.execute(stringtoexecute)
			lista2=self.dbcursor.fetchall()
		else:
			lista2=((jidtoset,nametoset),)
		for ii in lista2:
			fromm = ii[1]+"@"+name
			too = ii[0]
			if output[1]==1 and output[2]==200:
				p=Presence(from_jid=fromm,to_jid=too, show="away", status="Headline isn't well formed :/.")
				self.stream.send(p)
			
			elif output[1]==2:	
				p=Presence(from_jid=fromm,to_jid=too, show="xa", status="Big problem with this shit.")
				self.stream.send(p)
			elif output[1]==0 and output[2]==202:	
				p=Presence(from_jid=fromm,to_jid=too, show="avaiable", status="Strange problem with this RSS.")
				self.stream.send(p)
				
			elif output[1]==0 and output[2]==200:	
				p=Presence(from_jid=fromm,to_jid=too, show="avaiable")
				self.stream.send(p)
			elif output[2]==404:
				p=Presence(from_jid=fromm,to_jid=too, show="xa", status="404 not found")
				self.stream.send(p)
				
				
	self.close(" zamykam setpresence")		
    def showsubs(self):
    	printdebug("showsubs")
    	global name
	stringtoexecute="SELECT jid,namerss FROM subs"
	self.dbcursor.execute(stringtoexecute)
	return self.dbcursor.fetchall()
		
    def showsubsnamerss(self):
    	printdebug("showsubs")
    	global name
	stringtoexecute="SELECT name FROM addressess"
	self.dbcursor.execute(stringtoexecute)
	return self.dbcursor.fetchall()
	   
    def sentrss(self, namerss,item):
    	printdebug("sentrss")
        global name
        stringtoexecute="SELECT jid FROM subs WHERE namerss='"+namerss+"'"
        self.dbcursor.execute(stringtoexecute)
        for ii in self.dbcursor.fetchall():
            if not item.has_key("summary"):
                summary="No description"
            else:
                summary=item["summary"]
		summary=re.sub('<br ??/??>','\n',summary)
		summary=re.sub('\n\n','\n',summary)
		summary=summary.replace("&nbsp;"," ") 
		summary=re.sub('<[^>]*>','',summary)
	    p=Presence(from_jid=namerss+"@"+name,to_jid=ii[0])
	    self.stream.send(p)
            m=Message(
                to_jid=ii[0],
                from_jid=namerss+"@"+name,
                stanza_type="headline",
                subject=item["title"],
                body=summary)
            oob=m.add_new_content("jabber:x:oob","x")
            url=oob.newTextChild(oob.ns(),"url",item["link"])
            #url=oob.newTextChild(oob.ns(),"url",item["link"])
            desc=oob.newTextChild(oob.ns(),"desc",item["title"].encode("utf-8"))
            self.stream.send(m)

    def checkallrss(self):	
    	printdebug("checkallrss")
        stringtoexecute="SELECT name FROM addressess"
	self.dbcursor.execute(stringtoexecute)
        resultdb=self.dbcursor.fetchall()
        for i in resultdb:
            self.fetchrss(i[0])

	self.close("checkallrss")        
	#self.close()
    def fetchrss(self, namerss, force=False):
    	printdebug("fetchrss")
        stringtoexecute="SELECT count(jid) FROM subs where namerss = '"+namerss+"';"
	self.dbcursor.execute(stringtoexecute)
        resultdb=int(self.dbcursor.fetchall()[0][0])
        if not resultdb==0:
            stringtoexecute="SELECT * FROM addressess WHERE name='"+namerss+"'"
            self.dbcursor.execute(stringtoexecute)
            resultdb=self.dbcursor.fetchall()
            urlrss=resultdb[0][2]
            last_time=resultdb[0][3]
            fetch_time=resultdb[0][4]*60
            actual_time = int(time.time())
            subtime = actual_time - last_time


            if subtime>fetch_time or force:
                pass
                #global connection
                
                try:
                    self.feed = feedparser.parse(urlrss)
                    bozotest=self.feed["bozo"]
                    statustest=self.feed["status"]
                except:
                    bozotest=2
                    statustest="404"
                
                stringtoexecute="UPDATE addressess SET last_time='"+str(actual_time)+"' WHERE name='"+namerss+"'"
                self.dbcursor.execute(stringtoexecute)
                self.commit()
                if str(statustest)=="200":
                        for i in self.feed[ "items" ]:
                            md5sum=md5.md5(str(i)).hexdigest()
                            if self.checkifrsswassent(namerss, md5sum):
                                self.insertnewrss(namerss,md5sum)
                                self.sentrss(namerss, i)
                            else:
                                    pass
            
                else:
                    pass
        else:
            printdebug("Nobody subscribed this, forget!")


    def parse(self, url):
    	printdebug("parse")
	try:
		feed=feedparser.parse(url)
    		return feed, feed["bozo"], feed["status"]
	except:
		return None, 2, 404
    	
    def getsubsnames(self,who=""):
    	printdebug("getsubsnames")
	if who=="":
		stringtoexecute="SELECT DISTINCT name FROM addressess ORDER BY name;"
	else:
		stringtoexecute="SELECT DISTINCT namerss FROM subs WHERE jid='"+who+"'ORDER BY namerss;"
        self.dbcursor.execute(stringtoexecute)
        return self.dbcursor.fetchall()
 
    def getjidsnamesppl(self, who=""):
    	printdebug("getjidsnamesppl")
        if who=="":
		stringtoexecute="SELECT DISTINCT jid FROM subs ORDER BY jid;"
	else:
		stringtoexecute="SELECT DISTINCT jid FROM subs WHERE namerss='"+who+"'ORDER BY jid;"
        self.dbcursor.execute(stringtoexecute)
        result=self.dbcursor.fetchall()
	#connection.close()
        return result
    	
	
    
    def checkifrsswassent(self, namerss, md5):
    	printdebug("checkifrsswassent")
        stringtoexecute="SELECT * FROM sent WHERE namerss='"+namerss+"' AND md5='"+md5+"'"
        self.dbcursor.execute(stringtoexecute)
        if self.dbcursor.rowcount==0:
            return True
        else:
            return False

    def close(self,fromlog=""):
    	printdebug("database closed", fromlog)
    	self.connection.close()

    def commit(self):
    	printdebug("connection commited")
	self.connection.commit()

class Component(pyxmpp.jabberd.Component):
    def stream_state_changed(self,state,arg):
    	printdebug("stream_state_changed")
    	pass

    def connected(self):
    	printdebug("connected")
        self.orig_stream_idle=self.stream._idle
        self.stream._idle=self.idle

    def setpyrssdiscoitems(self,iq=None,node=None):
    	printdebug("setpyrssdiscoitems",str(iq.get_to()))
	global name, adminjid
	itemname=name
	authorized=False
	if iq:
		jidfrom=unicode(str(iq.get_from()).split("/")[0],"utf-8")
		#print iq.get_from().split("/")[0]
		#jidfrom=iq.get_from().split("/")[0]
		#print jidfrom
		print type(jidfrom)
		print type(adminjid)
		jidto=str(iq.get_to()).split("/")[0]
		
		#if jidfrom.encode('utf-16') in adminjid: authorized=True
		if jidfrom in adminjid: authorized=True
		   
	baza=Database()
	names=baza.getsubsnames()
	jids=baza.getjidsnamesppl()
	pyrss_disco_items=DiscoItems()
	printdebug("node is: "+str(node))
	
	if node == None and iq.get_to().node == None:
	
		newjid = JID(domain=itemname)
		if authorized: 
			item=DiscoItem(pyrss_disco_items,newjid,name="Registered Users", node="subscribers")
		item=DiscoItem(pyrss_disco_items,newjid,name="Registered Feeds", node="feeds")

	printdebug("JIDTO: "+jidto+" NODE:"+str(node)+" "+str(authorized))
	#try:
	#	nodesplit=str(node.split("/")[1])
	#	printdebug("nodesplit:::: "+nodesplit)
	#except:
	if node and node.startswith("subscribers/"):
		nodesplit=str(node.split("/")[2])
	else:
		nodesplit=("","","")
	if authorized and (nodesplit,) in jids:
		printdebug("CHECKING SUBSNAMES FOR: "+nodesplit+ " NODE: "+str(node))
		newnames=baza.getsubsnames(nodesplit)
		for i in newnames:
			newjid = JID(i[0], itemname)
			item=DiscoItem(pyrss_disco_items,newjid,name=i[0], node="subscribed")
	


	if authorized and (jidto.split("@")[0],) in names and node==None: 
		printdebug("JIDTO2: "+jidto.split("@")[0]+" NODE2: "+str(node))
		jids=baza.getjidsnamesppl(jidto.split("@")[0])
		for i in jids:
			newjid = JID(i[0], itemname)
			item=DiscoItem(pyrss_disco_items,newjid,name=i[0], node=jidto.split("@")[0])
	if authorized and node=="subscribers":
		printdebug(jids)
		limitss=245
		limits=0
		string=""
		printdebug("DEBUG WARNING, PROBLEM!")
		for i in jids:
				printdebug("NEWJID: "+i[0])
				newjid = JID(itemname)
				if string.count(i[0][0])==0:
					string += i[0][0]
					
				#item=DiscoItem(pyrss_disco_items,newjid,name=i[0],node="subscribers/"+i[0])
				#item=DiscoItem(pyrss_disco_items,newjid,name=i[0], node="subscribers/"+i[0][0]+"/"+i[0]
					item=DiscoItem(pyrss_disco_items,newjid,name=i[0][0], node="subscribers/"+i[0][0]+"/"
				)
	if node:
		if authorized and node.endswith("/") and node.startswith("subscribers"):
			zmienna=node.split("/")
			printdebug(zmienna[1])
			for i in jids:
				if i[0].startswith(zmienna[1]):
					newjid = JID(itemname)
					item=DiscoItem(pyrss_disco_items,newjid,name=i[0],node="subscribers/"+i[0][0]+"/"+i[0])

	if node=="feeds":
		printdebug(names)
		for i in names:
			newjid = JID(i[0], itemname)
			item=DiscoItem(pyrss_disco_items,newjid,name=i[0], node=None)
	return pyrss_disco_items
    	
	baza.close()
    def disco_get_items(self,node,iq):
    	printdebug("disco_get_items")
	return self.setpyrssdiscoitems(iq,node)
        #if node == None and iq.get_to().node == None:
           


    def disco_get_info(self,node,iq):
    	discoinfo=DiscoInfo()
	discoinfo.add_feature("jabber:iq:register")
	discoinfo.add_feature("jabber:iq:gateway")
    	printdebug("disco_get_info")
	printdebug("iq info: "+str(iq.get_to()))
	printdebug("node info: " + str(node) )
	#printdebug(self.disco_info)
        if node == None and iq.get_to().node == None:
		return self.disco_info
	#return self.setpyrssdiscoitems(iq,node)
	printdebug("EHLO")

    def authenticated(self):
    	printdebug("authenticated")
        pyxmpp.jabberd.Component.authenticated(self)
        self.stream.set_iq_get_handler("query","jabber:iq:version",self.get_version)
        self.stream.set_iq_get_handler("query","jabber:iq:register",self.get_register)
        self.stream.set_iq_set_handler("query","jabber:iq:register",self.set_register)
        self.stream.set_iq_get_handler("query","jabber:iq:gateway",self.get_serviceid) # handler. OKON
        self.stream.set_iq_set_handler("query","jabber:iq:gateway",self.set_serviceid) # handler. OKON
        self.disco_info.add_feature("jabber:iq:version")
        self.disco_info.add_feature("jabber:iq:version")
        self.disco_info.add_feature("jabber:iq:register")
        self.disco_info.add_feature("jabber:iq:gateway") # Nie wiem czy wiem o co chodzi. ;) OKON
        self.disco_identity.set_name("PyRSS - rss reader for Jabber")
        self.stream.set_presence_handler("available",self.presence)
        self.stream.set_presence_handler("subscribe",self.presence_control)
        self.stream.set_presence_handler("subscribed",self.presence_control)
        self.stream.set_presence_handler("unsubscribe",self.presence_control)
        self.stream.set_presence_handler("unsubscribed",self.presence_control)
        self.stream.set_message_handler("normal",self.message)
	baza=Database(self.stream)
	thread.start_new_thread(baza.setpresence,())
    def idle(self):
    	printdebug("idle")
        global last_poll
        self.orig_stream_idle()
        last_poll += 1
        if last_poll>299:
            baza=Database(self.stream)
            thread.start_new_thread(baza.checkallrss,())
            
	    baza=Database()
	    baza.purgedatabase()   
	    baza.close()
	    last_poll=0
	    
	    
        

    def get_version(self,iq):
    	global programmVersion
    	printdebug("get_version")
        iq=iq.make_result_response()
        q=iq.new_query("jabber:iq:version")
        q.newTextChild(q.ns(),"name","RSS component")
        q.newTextChild(q.ns(),"version",programmVersion)
        self.stream.send(iq)
        return 1

    def notauthorized(self,stanza,function):
    	printdebug("notauthorized")
        m=Message(
            to_jid=stanza.get_from(),
            from_jid=stanza.get_to(),
            stanza_type="error",
            subject="Error!",
            body="You are not authorized to "+function+" command!!!")
        self.stream.send(m)
    
    
    def sendmessage(self,stanza,message):
    	printdebug("sendmessage")
        m=Message(
            to_jid=stanza.get_from(),
            from_jid=stanza.get_to(),
            stanza_type=stanza.get_type(),
            subject="",
            body=message)
        self.stream.send(m)
    def senderror(self,stanza,message):
    	printdebug("senderror")
        m=Message(
            to_jid=stanza.get_from(),
            from_jid=stanza.get_to(),
            stanza_type="error",
            subject="Oppps...",
            body=message)
        self.stream.send(m)
 
 
    def get_register(self,iq):
    	printdebug("get_register")
        to=iq.get_to()
        if to and to!=self.jid:
            iq=iq.make_error_response("feature-not-implemented")
            self.stream.send(iq)
            return 1
        iq=iq.make_result_response()
        #q=iq.new_query("jabber:iq:register")
        #q.newTextChild(q.ns(),"instructions","Enter anything below.")
        #q.newChild(q.ns(),"username",None)
        #q.newChild(q.ns(),"password",None)
        self.stream.send(iq)
        return 1


    def set_register(self,iq):
    	printdebug("set_register")
        to=iq.get_to()
        if to and to!=self.jid:
            iq=iq.make_error_response("feature-not-implemented")
            self.stream.send(iq)
            return 1
        remove=iq.xpath_eval("r:query/r:remove",{"r":"jabber:iq:register"})
        if remove:
            m=Message(from_jid=iq.get_to(),to_jid=iq.get_from(),stanza_type="chat",
                    body=u"Unregistered")
            self.stream.send(m)
            p=Presence(from_jid=iq.get_to(),to_jid=iq.get_from(),stanza_type="unsubscribe")
            self.stream.send(p)
            p=Presence(from_jid=iq.get_to(),to_jid=iq.get_from(),stanza_type="unsubscribed")
            self.stream.send(p)

            return 1
        username=iq.xpath_eval("r:query/r:username",{"r":"jabber:iq:register"})
        if username:
            username=username[0].getContent()
        else:
            username=u""
        password=iq.xpath_eval("r:query/r:password",{"r":"jabber:iq:register"})
        if password:
            password=password[0].getContent()
        else:
            password=u""
        #m=Message(from_jid=iq.get_to(),to_jid=iq.get_from(),stanza_type="chat",
        #       body=u"Registered with username '%s' and password '%s'"
        #        " (both ignored)" % (username,password))
        #self.stream.send(m)
        p=Presence(from_jid=iq.get_to(),to_jid=iq.get_from(),stanza_type="subscribe")
        self.stream.send(p)
        iq=iq.make_result_response()
        self.stream.send(iq)
        return 1

    def get_serviceid(self,iq): # handler. OKON
    	printdebug("get_serviceid")
        to=iq.get_to()
        if to and to!=self.jid:
            iq=iq.make_error_response("feature-not-implemented")
            self.stream.send(iq)
            return 1
        iq=iq.make_result_response()
        q=iq.new_query("jabber:iq:gateway")
        q.newTextChild(q.ns(),"desc","Enter rss name below.")
        q.newTextChild(q.ns(),"prompt","RSS name")
        self.stream.send(iq)
        return 1

    def set_serviceid(self,iq): # handler. OKON
    	printdebug("set_serviceid")
	global name
        to=iq.get_to()
        if to and to!=self.jid:
            iq=iq.make_error_response("feature-not-implemented")
            self.stream.send(iq)
            return 1
        prompt=iq.xpath_eval("r:query/r:prompt",{"r":"jabber:iq:gateway"})
        if prompt:
            prompt=prompt[0].getContent()
            if type(prompt)!="unicode":
            	prompt=prompt.decode("utf-8")
        else:
            prompt=u"" #FIXME: powinien lezc error 406. OKON
        iq=iq.make_result_response()
        q=iq.new_query("jabber:iq:gateway")
	resultjid=prompt+u"@"+name
	resultjid=resultjid.encode('utf-8')
        q.newTextChild(q.ns(),"prompt",resultjid)
        q.newTextChild(q.ns(),"jid",resultjid)
        self.stream.send(iq)
        return 1
	    

    def message(self,stanza):
    	printdebug("message")
        global adminjid
        subject=stanza.get_subject()
        body=stanza.get_body()
        jidfrom=str(stanza.get_from()).split("/")[0]
        authorized=False
        if jidfrom in adminjid: authorized=True
                
        
        
	if body and body.strip():
		bodyar = body.split()
	else:
		bodyar=["error",]
	

        if bodyar[0]=="subs":
		if authorized:
	        	baza=Database(self.stream)
			messagefull = ""
			for ii in baza.showsubs():
				messagetext = ii[0]+" subscribe "+ii[1]
				messagefull = messagefull + messagetext + "\n"
				#fromm = ii[1]+"@"+name
				#too = ii[0]
			self.sendmessage(stanza,messagefull)
			#self.sendmessage(stanza,ii[0]+" subscribe "+ii[1])
			baza.close()
        if bodyar[0]=="update":
            baza=Database(self.stream)
	    # Added by St. Hermann <sh@sourcecode.de>
	    # Prevent "index out of range" error
	    if len(bodyar)>1:
		    if baza.checkname(bodyar[1]):	
			baza.fetchrss(bodyar[1], True)
			self.sendmessage(stanza,bodyar[1]+" updated")
	    	    else:
			self.sendmessage(stanza,"There is no such rss "+bodyar[1])
	    else:
		    self.sendmessage(stanza,"You have to provide a RSS Feed Name")

	    baza.close()
        if bodyar[0]=="list":
            baza=Database()
	    results=baza.listrss()
            if not len(results)==0:
                    self.sendmessage(stanza,"Available rss:")
		    messagefull = ""
                    for i in results:
		    	messagetext = str(i[0])+" "+str(i[1])+" "+str(i[2])+" "+str(i[4])
			messagefull = messagefull + messagetext + "\n"
		    self.sendmessage(stanza,messagefull)
            else:
                self.sendmessage(stanza,"There is no any rss.")
	    baza.close()
	if bodyar[0]=="del":
		if authorized:
			if len(bodyar)==2:
				baza=Database()
				baza.delrss(bodyar[1])
				self.sendmessage(stanza,bodyar[1]+" deleted, oh my good!")
				baza.close()
		
        if bodyar[0]=="add":
            if authorized:
                if len(bodyar)==3:
                    baza=Database()
                    if not baza.checknewadd(bodyar[1],bodyar[2]):
                        self.sendmessage(stanza,"There is already given name or url.")       
		    else:
                        baza.addrss(bodyar[1], bodyar[2])
                        baza.fetchrss(bodyar[1])
                        self.sendmessage(stanza,"Yeahh, addedd.")       
		    baza.close()
		elif len(bodyar)==4:
			baza=Database()
			if not baza.checknewadd(bodyar[1],bodyar[2]):
                        	self.sendmessage(stanza,"There is already given name or url.")       
                    	else:
	                        baza.addrss(bodyar[1], bodyar[2], bodyar[3])
	                        baza.fetchrss(bodyar[1])
	                        self.sendmessage(stanza,"Yeahh, addedd.")
			baza.close()
            else:
                self.notauthorized(stanza,bodyar[0])
        if bodyar[0]=="help" and len(bodyar)==1 :
            if authorized:
	    	
                self.sendmessage(stanza,"""List of avaiable administration commands:
add name url [time]       
update name       
subs       
del""")
            
            self.sendmessage(stanza,"List of avaiable common commands:")       
            self.sendmessage(stanza,"list")       
            
            self.sendmessage(stanza,"help [command]")       

       
        if bodyar[0]=="help" and len(bodyar)>=2 :
            if authorized:
                if bodyar[1]=="add":
                    self.sendmessage(stanza,"Syntax add command:")       
                    self.sendmessage(stanza,"add name url [time]\n")       
                    self.sendmessage(stanza,"name is the name of your rss (for example 7thguard)")       
                    self.sendmessage(stanza,"url is the rss address (for example http://7thguard.net/index-rss.php)")
                    self.sendmessage(stanza,"time is optional and tell the component how often rss should be updated")
                if bodyar[1]=="update":
                    self.sendmessage(stanza,"update your rss feed")
		if bodyar[1]=="subs":
                    self.sendmessage(stanza,"show subscribers")
		if bodyar[1]=="del":
                    self.sendmessage(stanza,"delete feed")
			

                   
            if bodyar[1]=="list":
                    self.sendmessage(stanza,"list command shows avaiable rss...")       

        return 1


    def presence(self,stanza):
    	printdebug("presence")
        global name
	if stanza.get_to()==name:
		p=Presence(
	            stanza_type=stanza.get_type(),
	            to_jid=stanza.get_from(),
	            from_jid=stanza.get_to(),
	            show=stanza.get_show(),
	            status=stanza.get_status()
	            );
	        self.stream.send(p)
	else:
		baza=Database(self.stream)
		baza.setpresence(str(stanza.get_to()).split("@")[0], str(stanza.get_from()).split("/")[0])
		#baza.close()

	return 1

    def presence_control(self,stanza):
    	printdebug("presence_control")
    	global name
        jidfrom=str(stanza.get_from())
        namerss=str(stanza.get_to()).split("@")[0]
	
        if stanza.get_type()=="subscribe" and stanza.get_to()!=name:
            #ajidfrom=str(stanza.get_from()).split("/")[0]
            baza=Database()
            if baza.checkname(namerss):
                baza.subscriberss(jidfrom,namerss)
                p=stanza.make_accept_response()
		self.stream.send(p)
                p=Presence(stanza_type="subscribe",
                    to_jid=stanza.get_from(),
                    from_jid=stanza.get_to(),
                    show=stanza.get_show(),
                    status=stanza.get_status())
                self.stream.send(p)
            else:
                self.senderror(stanza,"There is no rss with given name "+namerss+", please write list command.")       
                p=stanza.make_deny_response()
            baza.close()
	if stanza.get_type()=="subscribe" and stanza.get_to()==name:
                p=stanza.make_accept_response()
		self.stream.send(p)

        if stanza.get_type()=="unsubscribe" or stanza.get_type()=="unsubscribed":
		baza=Database(self.stream)
		if stanza.get_to()==name:
			baza.deluser(stanza, str(stanza.get_from()))
		elif not baza.checksubsduplicate(str(stanza.get_from()),namerss):
			baza=Database()
			baza.unsubscriberss(jidfrom,namerss)
			p=Presence(stanza_type="unsubscribe",
				to_jid=stanza.get_from(),
				from_jid=stanza.get_to(),
				show=stanza.get_show(),
				status=stanza.get_status())
			self.stream.send(p)
			#baza.close()
		baza.close()
        #self.stream.send(p)
        return 1

#logger=logging.getLogger()
#logger.addHandler(logging.StreamHandler())
#logger.setLevel(logging.DEBUG)

#c=Component(JID(sys.argv[1]),sys.argv[2],sys.argv[3],int(sys.argv[4]),disco_type="x-echo")

try:
	c=Component(JID(name),password,host,int(port),disco_type="x-rss")
	c.connect()
	c.loop(1)
except KeyboardInterrupt:
	sys.exit()
	c.disconnect()
#		pass
except:
	printdebug("everything lost :/"+str(sys.exc_info()[0]))
	printdebug(traceback.print_exc())
	sys.exit(1)


# vi: sts=4 et sw=4
