Commit 399bf75d authored by Valentin Samir's avatar Valentin Samir

[sip] Factorisation et mise au propre des scripts pour asterisk

parent 9b5c5eb9
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/usr/scripts/sip/')
from asterisk import History
if __name__ == '__main__' :
if len(sys.argv)>1:
history = History("dbname='django' user='crans' host='pgsql.adm.crans.org'", "voip_history", 99)
if sys.argv[1] == "add":
if len(sys.argv)>4:history.add(sys.argv[2], sys.argv[3], sys.argv[4])
else:print >> sys.stderr, "Usage %s %s {id} {src} {dst}" % (sys.argv[0], sys.argv[1])
elif sys.argv[1] =="delete":
if len(sys.argv)>2:history.delete(sys.argv[2])
else:print >> sys.stderr, "Usage %s %s {id}" % (sys.argv[0], sys.argv[1])
elif sys.argv[1] =="update":
if len(sys.argv)>3:history.update(sys.argv[2], sys.argv[3])
else:print >> sys.stderr, "Usage %s %s {id} {duration}" % (sys.argv[0], sys.argv[1])
elif sys.argv[1] =="quota":
if len(sys.argv)>2:history.quota(sys.argv[2])
else:print >> sys.stderr, "Usage %s %s {number}" % (sys.argv[0], sys.argv[1])
else:
print >> sys.stderr, "Usage %s {add | delete | update } ..." % sys.argv[0]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/usr/scripts/sip/')
from asterisk import Sms
if __name__ == '__main__' :
if len(sys.argv)>4:
sms=Sms('/var/spool/asterisk/sms/')
sms.sms_delay(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], body_type='base64')
else:
print >> sys.stderr, "Usage %s {from} {to} {body_base64} {user}" % sys.argv[0]
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -
# liste d'event http://www.voip-info.org/wiki/view/asterisk+manager+events
# liste d'action http://www.voip-info.org/wiki/view/Asterisk+manager+API
import os
import sys
import time
import errno
import shutil
import syslog
import socket
import base64
import psycopg2
from datetime import datetime
sys.path.append('/usr/scripts/')
import lc_ldap.shortcuts
class NullRecv(EnvironmentError):
pass
class Profile(object):
def __init__(self, sql_params, database):
self.sql_params = sql_params
self.database =database
def update_pin(self, num, pin):
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("UPDATE %s SET voicemail_password=%%s WHERE num=%%s" % self.database, (pin, num))
conn.commit()
cur.close()
conn.close()
def num_to_callerid(self, num):
try:
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("SELECT caller_id from %s WHERE num=%%s" % self.database, (num,))
caller_id = cur.fetchall()[0][0]
cur.close()
conn.close()
if caller_id == 'full_name' or caller_id == 'both':
conn=lc_ldap.shortcuts.lc_ldap_admin()
aid=int(num[1:])
adh=conn.search(u'aid=%s' % aid)[0]
return '%s %s' % (adh['prenom'][0],adh['nom'][0])
else:
return num
except:
return num
class Sms(object):
def __init__(self,sms_dir):
self.sms_dir=sms_dir
def sms_daemon(self, server,port,user,password, timeout=360):
manager = Manager(user, password, server=server, event=True, auto_connect=False, timeout=timeout)
manager.register_events_callback('PeerStatus', self._send_sms)
while True:
manager.connect()
try:
while True:
manager.process_events()
except (socket.error, asterisk.NullRecv):
pass
def _mkdirs(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
def sms_delay(self, src, dst, body, user, body_type='str'):
if not body_type in ["str", "base64"]:
raise EnvironmentError("body_type sould be 'str' ou 'base64' not %r" % body_type)
date = datetime.now().strftime('%Y%m%d%H%M%S.%f')
path = self.sms_dir + user + '/' + date + '/'
self._mkdirs(path)
with open(path + 'from') as f:
f.write(src)
with open(path + 'to') as f:
f.write(dst)
with open(path + 'body') as f:
if body_type=='str':
f.write(body)
elif body_type=='base64':
f.write(base64.encodestring(body).strip())
def _send_sms(self, manager, params):
if params['PeerStatus'] in ['Reachable','Registered']:
num = params['Peer'].split('/')[1]
if os.path.isdir(self.sms_dir + '/' + num + '/'):
dir=os.listdir(self.sms_dir + '/' + num + '/')
dir.sort()
for sms in dir:
sms_path=self.sms_dir + '/' + num + '/' + sms + '/'
if os.path.isfile(sms_path + 'from') and os.path.isfile(sms_path + 'to') and os.path.isfile(sms_path + 'body'):
sms_from=open(sms_path + 'from').read()
sms_to=open(sms_path + 'to').read()
sms_body=open(sms_path + 'body').read()
status, params = manager.messageSend(sms_from, sms_to, sms_body, body_type='base64')
if status == 'Success':
syslog.syslog("Message from %s successfully delivered to %s" % (sms_from, sms_to))
shutil.rmtree(sms_path)
try:
os.rmdir(self.sms_dir + '/' + num + '/')
except OSError:
pass
elif status == 'Error':
syslog.syslog("Message from %s to %s : %s" % (sms_from, sms_to, params['Message']))
class History(object):
def __init__(self, sql_params, database, quota_limit):
self.sql_params = sql_params
self.database =database
self.quota_limit = quota_limit
def add(self, id, src, dst):
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("INSERT INTO %s (uniq_id,src,dst) VALUES (%%s, %%s, %%s)" % self.database, (id, src, dst))
conn.commit()
cur.close()
conn.close()
def delete(self, id):
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("DELETE FROM %s WHERE uniq_id=%%s" % self.database, (id,))
conn.commit()
cur.close()
conn.close()
def update(self, id, duration):
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("UPDATE %s SET duration=%%s WHERE uniq_id=%%s" % self.database, (int(duration), id))
conn.commit()
cur.close()
conn.close()
def quota(self, number):
allowed = False
try:
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute("SELECT count(DISTINCT dst) FROM %s WHERE date>='%s' AND dst LIKE '+%%'" % (self.database, time.strftime('%Y-%m-01')))
outgoing_call_num = cur.fetchall()[0][0]
if outgoing_call_num >= self.quota_limit:
cur.execute("SELECT count(dst)>0 FROM %s WHERE date>'%s' AND dst=%%s" % (self.database, time.strftime('%Y-%m-01')), (number,))
allowed = cur.fetchall()[0][0]
else:
allowed = True
cur.close()
conn.close()
except:
pass
sys.stdout.write('ALLOWED' if allowed else 'DENY')
class Manager(object):
def __init__(self, username, password, timeout=10, server='asterisk.adm.crans.org', port=5038, debug=False, event=False, auto_connect=True):
self.timeout = timeout
self.server = server
self.port = port
self.socket = None
self.debug = debug
self.event = event
self._pending_action=[]
self._response={}
self._event=[]
self._event_callback = {}
self._toread = ""
self.privilege = []
self.username = username
self.password = password
self.register_events_callback('FullyBooted', self._FullyBooted)
if auto_connect:
self.connect()
def _FullyBooted(self, manager, params):
manager.privilege = params['Privilege'].split(',')
def _recv(self):
data = self.socket.recv(1024)
if len(data) == 0:
raise NullRecv("Got null response")
self._toread += data
self._toread = self._toread.split('\r\n\r\n')
for msg in self._toread[:-1]:
if self.debug:
print msg + "\n"
self._parse_msg(msg)
self._toread=self._toread[-1]
def _send(self, str):
if self.debug:
print str
self.socket.send ('%s\r\n' % (str))
def _parse_msg(self, msg):
msg = msg.strip().split('\r\n')
type, value = msg[0].split(': ', 1)
params = dict([line.split(': ', 1) for line in msg[1:]])
handler = getattr(self, "_do_"+type, None)
handler(value, params)
def _do_Response(self, status, params):
id = params['ActionID']
del(params['ActionID'])
self._response[id] = (status, params)
def _do_Event(self, type, params):
self._event.append((type, params))
def _gen_actionID(self):
id=time.time()
while id in self._pending_action:
id=id+1
return str(id)
def _action(self, name, params):
self._send ('ACTION: %s' % name.upper())
for (key, value) in params.items():
self._send ('%s: %s' % (key.upper(), value))
id=self._gen_actionID()
self._send ('ActionID: %s' % id)
self._pending_action.append(id)
self._send ('')
while not id in self._response.keys():
self._recv()
response = self._response[id]
del(self._response[id])
self._pending_action.remove(id)
if response[0] == 'Error':
raise ValueError(response)
return response
def action(self, name, **params):
return self._action(name, params)
def connect(self):
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
sock.settimeout(self.timeout)
sock.connect ( ( self.server, self.port ) )
self.socket=sock
msg = self.socket.recv(1024).strip().split('\r\n', 1)
self.version = msg[0]
if len(msg)>1:
self._toread += msg[1]
self.login()
self.process_events()
self.events(self.event)
def register_events_callback(self, event, func):
self._event_callback[event] = self._event_callback.get(event, []) + [func]
def process_events(self):
if not self._event:
try: self._recv()
except socket.timeout: pass
for event in self._event:
(type, params) = event
for func in self._event_callback.get(type, []):
func(self, params)
self._event=[]
def login(self, username=None, secret=None):
"""Login Manager"""
if username is None: username = self.username
if secret is None: secret = self.password
return self.action('login', username=username, secret=secret)
def logoff(self):
""" Logoff Manager"""
self.action('logoff')
def events(self, param):
"""Control Event Flow
params should be a boolean or a list among system,call,log,verbose,command,agent,user to select
which flags events should have to be sent."""
if isinstance(param, list):
eventmask = ','.join(param)
elif isinstance(param, bool):
eventmask = 'on' if param else 'off'
else:
raise EnvironmentError("%r should be a list or a bool" % param)
return self.action('events', eventmask=eventmask)
def reload(self, module):
"""Synopsis: Send a reload event
Privilege: system,config,all"""
privilege = ['system', 'config', 'all']
return self.action('reload', module=module)
def messageSend(self, src, dst, body, body_type="str"):
if not body_type in ["str", "base64"]:
raise EnvironmentError("body_type sould be 'str' ou 'base64' not %r" % body_type)
if body_type == "str":
body = base64.encodestring(body).strip()
return self._action('messageSend', {'to':dst, 'from':src, 'base64body':body})
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import asterisk
import time
import sys
......@@ -18,38 +18,16 @@ reload_srv={
'all':['chan_sip','app_voicemail','pbx_config'],
}
manager = asterisk.Manager(user, password, server=server, auto_connect=False, timeout=timeout)
def reload_config(config):
if not config in reload_srv.keys():
print >> sys.stderr, "Reload config from : \n * %s" % ('\n * '.join( reload_srv.keys()))
print >> sys.stderr, "Usage %s [%s]" %(sys.argv[0],'|'.join(reload_srv.keys()))
return
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
def send(str):
msg='%s\r\n' % (str)
sock.send (msg)
sock.settimeout(timeout)
sock.connect ( ( server, port ) )
send ( 'ACTION: LOGIN')
send ( 'USERNAME: %s' % user)
send ( 'SECRET: %s' % password)
send ( '')
manager.connect()
for module in reload_srv[config]:
send ( 'ACTION: RELOAD')
send ( 'MODULE: %s' % module)
send ( 'ActionID: %s' % time.time())
send ( '')
send ( 'ACTION: LOGOFF')
send ( '')
data=[]
while True:
data.extend(sock.recv( 4096 ).split('\r\n'))
if data==['']:
sock.close()
return
while len(data)>0:
del data[0]
sock.close()
try:manager.reload(module)
except ValueError: pass
manager.logoff()
if __name__ == '__main__' :
if len(sys.argv)<2:
......
......@@ -2,9 +2,7 @@
# -*- coding: utf-8 -*-
import sys
from sh import grep,ErrorReturnCode_1
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/')
sys.path.append('/etc/crans/secrets/')
import lc_ldap.shortcuts
......@@ -15,7 +13,7 @@ try:
except ValueError:
sys.stdout.write('NONE')
exit(0)
login=conn.search("aid=%s" % aid)[0]['uid'][0]
login=conn.search(u"aid=%s" % aid)[0]['uid'][0]
try:
sys.stdout.write(grep('-r',login,'/usr/scripts/var/digicode/').split('/')[-1].split(':')[0])
except ErrorReturnCode_1: sys.stdout.write('NONE')
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from asterisk import History
if __name__ == '__main__' :
if len(sys.argv)>1:
history = History("dbname='django' user='crans' host='pgsql.adm.crans.org'", "voip_history")
if sys.argv[1] == "add":
if len(sys.argv)>4:history.add(sys.argv[2], sys.argv[3], sys.argv[4])
else:print >> sys.stderr, "Usage %s %s {id} {src} {dst}" % (sys.argv[0], sys.argv[1])
elif sys.argv[1] =="delete":
if len(sys.argv)>2:history.delete(sys.argv[2])
else:print >> sys.stderr, "Usage %s %s {id}" % (sys.argv[0], sys.argv[1])
elif sys.argv[1] =="update":
if len(sys.argv)>3:history.update(sys.argv[2], sys.argv[3])
else:print >> sys.stderr, "Usage %s %s {id} {duration}" % (sys.argv[0], sys.argv[1])
else:
print >> sys.stderr, "Usage {add | delete | update } ..."
\ No newline at end of file
#!/bin/bash
printf -v id "%q" "$1"
printf -v src "%q" "$2"
printf -v dst "%q" "$3"
psql -h pgsql.adm.crans.org -U crans django -c "INSERT INTO voip_history (uniq_id,src,dst) VALUES ('$id','$src','$dst')" >> /tmp/history
#!/bin/bash
printf -v id "%q" "$1"
psql -h pgsql.adm.crans.org -U crans django -c "DELETE FROM voip_history WHERE uniq_id='$id'" >> /tmp/history
#!/bin/bash
printf -v id "%q" "$1"
printf -v duration "%q" "$2"
psql -h pgsql.adm.crans.org -U crans django -c "UPDATE voip_history SET duration='$duration' WHERE uniq_id='$id'" >> /tmp/history
#!/bin/bash
printf -v limit "%q" "$1"
printf -v num "%q" "$2"
date=`date +"%Y-%m-01"`
num_call=`psql -h pgsql.adm.crans.org -U crans django --no-align -c "SELECT count(DISTINCT dst) FROM voip_history WHERE date>'$date' AND dst LIKE '+%'" | tail -n 2 | head -n 1`
if [[ $num_call = "" ]]; then
echo -n DENY
exit -1
fi
if [[ $num_call -ge $limit ]]; then
result=$((`psql -h pgsql.adm.crans.org -U crans django --no-align -c "SELECT dst FROM voip_history WHERE date>'$date' AND dst='$num'" | wc -l` -2))
if [[ $result -ge 1 ]]; then
echo -n ALLOWED
else
echo -n DENY
fi
else
echo -n ALLOWED
fi
exit 0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from asterisk import Profile
if __name__ == '__main__' :
if len(sys.argv)>1:
profile = Profile("dbname='django' user='crans' host='pgsql.adm.crans.org'", "voip_profile")
sys.stdout.write(profile.num_to_callerid(sys.argv[1]))
else:
print >> sys.stderr, "Usage %s {user}" % sys.argv[0]
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import psycopg2
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/')
sys.path.append('/etc/crans/secrets/')
import lc_ldap.shortcuts
try:
conn = psycopg2.connect("dbname='django' user='crans' host='pgsql.adm.crans.org'")
cur = conn.cursor()
cur.execute("""SELECT caller_id from voip_profile WHERE num='%s'""" % sys.argv[1])
caller_id = cur.fetchall()[0][0]
if caller_id == 'full_name' or caller_id == 'both':
conn=lc_ldap.shortcuts.lc_ldap_admin()
aid=int(sys.argv[1][1:])
adh=conn.search('aid=%s' % aid)[0]
sys.stdout.write('%s %s' % (adh['prenom'][0],adh['nom'][0]))
else:
sys.stdout.write(sys.argv[1])
except:
sys.stdout.write(sys.argv[1])
......@@ -12,19 +12,30 @@ from sh import asterisk
conn=lc_ldap.shortcuts.lc_ldap_admin()
def gen_multidial(droit):
dial="exten => %(droit)s,1,Ringing\nexten => %(droit)s,n,Wait(4)\nexten => %(droit)s,n,Answer\nexten => %(droit)s,n,Dial(" % {'droit':droit}
adhs=conn.search(u'(&(droits=%s)(!(chbre=EXT)))' % droit)
for nounou in adhs:
dial+="SIP/1%04d&" % nounou['aid'][0].value
return dial[:-1]+",30)\nexten => %(droit)s,n,Wait(3)\nexten => %(droit)s,n,VoiceMail(%(droit)s@666)\nexten => %(droit)s,n,Hangup()\n" % {'droit':droit}
def gen_multidial(name, entensions):
dial="""
exten => %(name)s,1,Ringing
exten => %(name)s,n,Wait(4)
exten => %(name)s,n,Answer
exten => %(name)s,n,Dial(%(entensions)s,30)
exten => %(name)s,n,Wait(3)
exten => %(name)s,n,VoiceMail(%(name)s@666)
exten => %(name)s,n,Hangup()
""" % {'name':name, 'entensions': '&'.join('SIP/1%04d' % num for num in entensions)}
return dial
multidial=gen_multidial('nounou') + gen_multidial('bureau') + gen_multidial('cableur') + gen_multidial('imprimeur')
multidial_md5=hashlib.md5(multidial).hexdigest()
multidial_old_md5=hashlib.md5(open('/usr/scripts/var/sip/sip_multidial','r').read()).hexdigest()
if multidial_md5 !=multidial_old_md5:
file=open('/usr/scripts/var/sip/sip_multidial.new','w')
file.write(multidial)
file.close()
os.rename('/usr/scripts/var/sip/sip_multidial.new','/usr/scripts/var/sip/sip_multidial')
print asterisk('-x','dialplan reload')
if __name__ == '__main__' :
multidial=""
for droit in ['nounou', 'bureau', 'cableur', 'imprimeur']:
multidial+=gen_multidial(droit, (adh['aid'][0].value for adh in conn.search(u'(&(droits=%s)(!(chbre=EXT)))' % droit)))
multidial_md5=hashlib.md5(multidial).hexdigest()
try:
multidial_old_md5=hashlib.md5(open('/usr/scripts/var/sip/sip_multidial','r').read()).hexdigest()
except IOError:
multidial_old_md5=""
if multidial_md5 !=multidial_old_md5:
file=open('/usr/scripts/var/sip/sip_multidial.new','w')
file.write(multidial)
file.close()
os.rename('/usr/scripts/var/sip/sip_multidial.new','/usr/scripts/var/sip/sip_multidial')
print asterisk('-x','dialplan reload')
#!/bin/bash
from="$1"
to="$2"
body="$3"
user="$4"
SMS_DIR="/var/spool/asterisk/sms/"
date=`date +%Y%m%d%H%M%S`
mkdir -p "${SMS_DIR}${user}/${date}"
echo -n "$from" > "${SMS_DIR}${user}/${date}/from"
echo -n "$to" > "${SMS_DIR}${user}/${date}/to"
echo -n "$body" > "${SMS_DIR}${user}/${date}/body"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from asterisk import Sms
if __name__ == '__main__' :
sms=Sms('/var/spool/asterisk/sms/')
sms.sms_daemon('localhost',5038,'sms','6m6lTaEOTMsyM')
#!/bin/bash
DAEMON="/usr/bin/python"
ARGS="/usr/scripts/sip/sms_queuing"
PIDFILE="/var/run/sms_queuing.pid"
USER="asterisk"
case "$1" in
start)
echo "Starting server"
/sbin/start-stop-daemon --start --pidfile $PIDFILE \
--user $USER --group $USER \
-b --make-pidfile \
--chuid $USER \
--exec $DAEMON $ARGS
;;
stop)
echo "Stopping server"