iro/anbieter/sipgate.py
author Sandro Knauß <knauss@netzguerilla.net>
Mon, 30 Jan 2012 21:36:12 +0100
branchdevel
changeset 128 1a3ebdd3bdaf
parent 64 7d4ddab659ad
child 129 d6704178a18f
permissions -rw-r--r--
telnumber test in own file

# -*- coding: utf-8 -*-
#Copyright (C) 2009  Sandro Knauß <bugs@sandroknauss.de>

#This program is free software; you can redistribute it and/or modify it under the terms
#of the GNU General Public License as published by the Free Software Foundation;
#either version 3 of the License, or any later version.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#See the GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, see <http://www.gnu.org/licenses/>.


from anbieter import anbieter
from telnumber import telnumber, NotATelNumber
import ConfigParser
import xmlrpclib
import logging
logger=logging.getLogger("sipgate")

class NoValidStatusCode(Exception):
     def __init__(self, value):
         self.value = value
     
     def __str__(self):
         return repr(self.value)

class sipgate(anbieter):
    """
        s. auch http://www.tuxad.com/sipgate.html
        und http://lists.sipgate.net/pipermail/sipgate-developers/2007-September/000016.html
    """
    section="sipgate"
    url="https://%s:%s@samurai.sipgate.net/RPC2"
    def __init__(self,user="",password=""):
        self.user=user
        self.password=password

    def read_basic_config(self,filenames):
        """Read basic options from the config file"""
        cp = ConfigParser.ConfigParser()
        cp.read(filenames)
        self.user=cp.get(self.section, 'user')
        self.password=cp.get(self.section, 'password')

    def sendSMS(self,sms,recipients):
        """send SMS with $sms to $recipients"""
        logger.debug('sipgate.sendSMS(%s,%s)'%(sms.getContent(),  str(recipients)))
        args={
                "TOS" : "text",
                "Content" : sms.getContent()
                }
        self.__send(args,recipients)

    def sendFAX(self,fax,recipients):
        """send the PDF file $fax  to $recipients"""
        logger.debug('sipgate.sendFAX(%s,%s)'%(fax,  str(recipients)))
        args={
                "TOS" : "fax",
                "Content" : xmlrpclib.Binary(fax.getAttachment(0)),
                }
        self.__send(args,recipients)

    def __connect(self):
        """connect to sipgate XMLRPC Server"""
        logger.debug("sipgate.__connect()-"+self.url%(self.user,"XXXXXXXX"))
        
        self.serv=xmlrpclib.ServerProxy(self.url%(self.user,self.password)) 
        self.samurai=self.serv.samurai

        args_identify = {
                "ClientName"    : "anbieter.py",
                "ClientVersion" : "V1.0",
                "ClientVendor"  : "Sandro Knauss"
                }
        self.__send_method(self.samurai.ClientIdentify, args_identify)
        return self.serv

    def __send_method(self, func, args=None):
        """execute $func and test weather if the func  ran successfully or not"""
        logger.debug("sipgate.__send_method(func,%s)"%( args))

        if args==None:
            xmlrpc_result = func()
        else:
            xmlrpc_result = func(args)
        if xmlrpc_result['StatusCode'] != 200:
            raise NoValidStatusCode("There was an error during identification to the server! %d %s"% (xmlrpc_result['StatusCode'], xmlrpc_result['StatusString']))
        logger.debug("sipgate.__send_method(..):ok"); 
        return xmlrpc_result

    def __send(self,args,recipients):
        """main sending method - sending the args to $recipients"""
        sended=[]

        serv=self.__connect()
        logger.debug('sipgate.__send(%s,%s)'%(args,  recipients))
        for recipient in recipients:
            try:
                tel = telnumber(recipient)

                if tel in sended:                                                                           #only send message once per recipient
                    continue
                sended.append(tel)
				
                args["RemoteUri"]="sip:%s%s@sipgate.net"%(tel.land,tel.number)
                self.__send_method(serv.samurai.SessionInitiate, args)
                self.updateStatus(arranged=recipient)
            
            except (NotATelNumber, NoValidStatusCode):
                self.updateStatus(failed=recipient)

        self.__disconnect()

    def updateStatus(self, arranged=None, failed=None):
        """is a function that is called, if a new SMS/FAX was send
        -arranged is non None, if SMS/FAX was sended successfully
        -failed is non None, if SMS/FAX sending failed
        the content will be the recipent"""
        pass

    def BalanceGet(self):
        """get the balance of sipgate"""
        self.__connect()
        ret = self.__send_method(self.samurai.BalanceGet )
        self.__disconnect()
        return ret['CurrentBalance']

    def getNewMessages(self):
        """get new messages from inbox"""
        self.__connect()
        tmp = self.__send_method(self.samurai.UmSummaryGet)
        self.__disconnect()
        tmp=tmp['UmSummary']
        ret={}
        for entry in tmp:
            ret[entry['TOS']]={'read':entry["Read"],'unread':entry["Unread"]}
        return ret

    def getRecommendedInterval(self,methods):
        """how often you can call one $methods"""
        self.__connect()
        args = {"MethodList" : methods }
        tmp = self.__send_method(self.samurai.RecommendedIntervalGet, args)
        self. __disconnect()
        ret={}
        for entry in tmp['IntervalList']:
            ret[entry['MethodName']]=entry['RecommendedInterval']
        return ret

    def __disconnect(self):
        """disconnect xmlrpc client"""
        logger.debug('sipgate.__disconnect()')
        self.samurai=None
        self.serv=None
        self.xmlrpc=None