Skip to content

Instantly share code, notes, and snippets.

@jchassoul
Last active September 27, 2017 19:39
Show Gist options
  • Save jchassoul/12df04375c9e090af85ef83b75b51dc5 to your computer and use it in GitHub Desktop.
Save jchassoul/12df04375c9e090af85ef83b75b51dc5 to your computer and use it in GitHub Desktop.
# TODO: MAE! please refactor into smaller independent functions (=
@gen.coroutine
def new_sip_account(self, struct):
'''
New sip account for asterisk real-time
'''
# let's still support asterisk 11 for now!
message = 'nothing to see here'
try:
# Get SQL database from system settings
sql = self.settings.get('sql')
# PostgreSQL insert new sip account query
query = '''
insert into sip (
name,
defaultuser,
fromuser,
fromdomain,
host,
sippasswd,
directmedia,
videosupport,
transport,
allow,
context,
nat,
qualify,
avpf,
encryption,
force_avp,
dtlsenable,
dtlsverify,
dtlscertfile,
dtlsprivatekey,
dtlssetup,
directrtpsetup,
icesupport
) values (
'{0}',
'{1}',
'{2}',
'{3}',
'dynamic',
'{4}',
'no',
'no',
'udp,wss',
'opus,ulaw,alaw',
'fun-accounts',
'force_rport,comedia',
'yes',
'yes',
'yes',
'yes',
'yes',
'no',
'/etc/asterisk/keys/asterisk.pem',
'/etc/asterisk/keys/asterisk.pem',
'actpass',
'no',
'yes'
);
'''.format(
struct.get('account'),
struct.get('account'),
struct.get('account'),
struct.get('domain', self.settings.get('domain')),
struct.get('password')
)
result = yield sql.query(query)
if result:
message = {'ack': True}
else:
message = {'ack': False}
result.free()
logging.warning('new sip real-time account for asterisk 11 spawned on postgresql {0}'.format(message))
except Exception, e:
message = str(e)
# let's support asterisk 13 and the beast that pjsip chaims the be!
try:
# Get SQL database from system settings
sql = self.settings.get('sql')
# PostgreSQL insert new sip account
query = '''
insert into ps_aors(id, max_contacts)
values ('{0}', 1);
'''.format(
struct.get('account')
)
result = yield sql.query(query)
if result:
message = {'ack': True}
else:
message = {'ack': False}
result.free()
logging.warning('new pjsip account (1/3)')
query = '''
insert into ps_auths(id, auth_type, password, username)
values ('{0}', 'userpass', '{1}', '{2}');
'''.format(
struct.get('account'),
struct.get('password'),
struct.get('account')
)
result = yield sql.query(query)
if result:
message = {'ack': True}
else:
message = {'ack': False}
result.free()
logging.warning('new pjsip account (2/3)')
query = '''
insert into ps_endpoints (id, transport, aors, auth, context, disallow, allow, direct_media)
values ('{0}', 'transport-udp', '{1}', '{2}', 'fun-accounts', 'all', 'g722,ulaw,alaw,gsm', 'no');
'''.format(
struct.get('account'),
struct.get('account'),
struct.get('account')
)
result = yield sql.query(query)
if result:
message = {'ack': True}
else:
message = {'ack': False}
result.free()
logging.warning('new pjsip account (3/3)')
# additional ack information.
logging.warning('new pjsip real-time account for asterisk 13 spawned on postgresql {0}'.format(message))
except Exception, e:
message = str(e)
raise gen.Return(message)
@gen.coroutine
def new_coturn_account(self, struct):
'''
New coturn account task
'''
try:
task = _tasks.Task(struct)
task.validate()
except Exception, e:
logging.exception(e)
raise e
task = clean_structure(task)
result = yield self.db.tasks.insert(task)
raise gen.Return(task.get('uuid'))
# -*- coding: utf-8 -*-
'''
Mango tools system periodic functions.
'''
# This file is part of mango.
# Distributed under the terms of the last AGPL License.
# The full license is in the file LICENCE, distributed as part of this software.
__author__ = 'Team Machine'
import logging
from tornado import httpclient
import ujson as json
import uuid
import urllib
from tornado import gen
httpclient.AsyncHTTPClient.configure('tornado.curl_httpclient.CurlAsyncHTTPClient')
@gen.coroutine
def get_coturn_tasks(db):
'''
Get coturn label tasks
'''
tasks_list = []
try:
query = db.tasks.find(
{'label':'coturn',
'assigned': False},
{'_id':0} # 'account':1, 'uuid':1,
)
while (yield query.fetch_next):
task = query.next_object()
tasks_list.append(task)
except Exception, e:
logging.exception(e)
raise gen.Return(e)
raise gen.Return(tasks_list)
@gen.coroutine
def get_raw_records(sql, query_limit):
'''
Get RAW records
'''
http_client = httpclient.AsyncHTTPClient()
# handle restuff callback actions
def handle_restuff(response):
'''
Request Handler Restuff
'''
if response.error:
logging.error(response.error)
else:
logging.info(response.body)
# handle request callback actions
def handle_request(response):
'''
Request Handler
'''
if response.error:
logging.error(response.error)
else:
res = json.loads(response.body)
request_id = res.get('uuid', None)
if request_id:
request_id = request_id.get('uuid')
# requests
http_client.fetch(
'http://iofun.io/records/{0}'.format(request_id),
headers={"Content-Type": "application/json"},
method='GET',
#body=json.dumps(record),
callback=handle_restuff
)
# if successful response we need to send ack now to sql
# and mack the flag of that call as checked, otherwise
# we need some other type of validation.
try:
query = '''
SELECT
DISTINCT ON (uniqueid) uniqueid,
src as source,
dst as destination,
dcontext,
channel,
dstchannel,
lastapp,
lastdata,
duration,
billsec,
disposition,
checked
FROM cdr
WHERE checked = false
ORDER BY uniqueid DESC
LIMIT {0};
'''.format(
query_limit
)
result = yield sql.query(query)
if result:
for row in result:
record = dict(row.items())
http_client.fetch(
'http://iofun.io/records/',
headers={"Content-Type": "application/json"},
method='POST',
body=json.dumps(record),
callback=handle_request
)
message = {'ack': True}
else:
message = {'ack': False}
result.free()
except Exception, e:
logging.exception(e)
raise e
raise gen.Return(message)
@gen.coroutine
def checked_flag(sql, uniqueid):
'''
periodic checked flag
'''
message = False
try:
query = '''
UPDATE cdr set checked = true where uniqueid = '{0}'
'''.format(uniqueid)
result = yield sql.query(query)
if len(result) > 0:
message = True
result.free()
except Exception, e:
logging.exception(e)
raise e
raise gen.Return(message)
@gen.coroutine
def get_query_records(sql, query_limit):
'''
periodic query records function
'''
record_list = []
http_client = httpclient.AsyncHTTPClient()
# handle record uuid
def handle_record_uuid(response):
'''
Request Handler Record UUID
'''
if response.error:
logging.error(response.error)
else:
logging.info(response.body)
# handle request
def handle_request(response):
'''
Request Handler
'''
if response.error:
logging.error(response.error)
else:
result = json.loads(response.body)
request_id = result.get('uuid', None)
if request_id:
request_id = request_id.get('uuid')
http_client.fetch(
'http://iofun.io/records/{0}'.format(request_id),
headers={"Content-Type": "application/json"},
method='GET',
callback=handle_record_uuid
)
try:
# Get SQL database from system settings
# PostgreSQL insert new sip account query
query = '''
SELECT
DISTINCT ON (uniqueid) uniqueid,
start,
date(start) as strdate,
clid as callerid,
src as source,
dst as destination,
dcontext as destination_context,
channel,
dstchannel as destination_channel,
duration,
billsec,
billsec as seconds,
disposition,
checked
FROM cdr
WHERE checked = false
ORDER BY uniqueid DESC
LIMIT {0};
'''.format(
query_limit
)
result = yield sql.query(query)
for x in result:
record_list.append(x)
result.free()
except Exception, e:
logging.exception(e)
raise e
raise gen.Return(record_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment