Commit 78385c45 authored by Valentin Samir's avatar Valentin Samir

[sip/sms] File d'attente des sms dans la base pgsql

parent 386086a9
......@@ -6,7 +6,7 @@ from asterisk import Sms
if __name__ == '__main__' :
if len(sys.argv)>4:
sms=Sms('/var/spool/asterisk/sms/')
sms=Sms("dbname='django' user='crans' host='pgsql.adm.crans.org'", "voip_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
print >> sys.stderr, "Usage %s {from} {to} {body_base64} {user}" % sys.argv[0]
......@@ -11,6 +11,7 @@ import syslog
import socket
import base64
import psycopg2
import psycopg2.extras
from datetime import datetime
sys.path.append('/usr/scripts/')
......@@ -66,8 +67,9 @@ class Profile(object):
return num
class Sms(object):
def __init__(self,sms_dir):
self.sms_dir=sms_dir
def __init__(self, sql_params=None, database=None):
self.sql_params = sql_params
self.database = database
def sms_daemon(self, server,port,user,password, timeout=360):
manager = Manager(user, password, server=server, event=True, auto_connect=False, timeout=timeout)
......@@ -77,7 +79,7 @@ class Sms(object):
try:
while True:
manager.process_events()
except (socket.error, asterisk.NullRecv):
except (socket.error, NullRecv):
pass
def _mkdirs(self, path):
......@@ -91,43 +93,31 @@ class Sms(object):
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', 'w') as f:
f.write(src)
with open(path + 'to', 'w') as f:
f.write(dst)
with open(path + 'body', 'w') as f:
if body_type=='str':
f.write(base64.encodestring(body).strip())
elif body_type=='base64':
f.write(body)
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor()
cur.execute('INSERT INTO %s (date, "from", "to", body, "user") VALUES (NOW(), %%s, %%s, %%s, %%s)' % self.database, (src, dst, base64.encodestring(body).strip() if body_type=='str' else body, user))
conn.commit()
cur.close()
conn.close()
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']))
conn = psycopg2.connect(self.sql_params)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute('SELECT * FROM %s WHERE "user"=%%s' % self.database, (num,))
for sms in cur.fetchall():
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']))
cur.execute('DELETE FROM %s WHERE id=%%s' % self.database, (sms['id'],))
conn.commit()
elif status == 'Error':
syslog.syslog("Message from %s to %s : %s" % (sms['from'], sms['to'], params['Message']))
cur.close()
conn.close()
class History(object):
def __init__(self, sql_params, database, quota_limit):
......
......@@ -6,6 +6,5 @@ sys.path.insert(0, '/usr/scripts/gestion/secrets')
from secrets import asterisk_sms_passwd
if __name__ == '__main__' :
# TODO ranger ceci dans /usr/scripts/var
sms=Sms('/var/spool/asterisk/sms/')
sms=Sms("dbname='django' user='crans' host='pgsql.adm.crans.org'", "voip_sms")
sms.sms_daemon('localhost', 5038, 'sms', asterisk_sms_passwd)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment