Bladeren bron

get variable in ami

Hal De 3 jaren geleden
bovenliggende
commit
0c34b8dd73
1 gewijzigde bestanden met toevoegingen van 86 en 40 verwijderingen
  1. 86 40
      app/app.py

+ 86 - 40
app/app.py

@@ -179,7 +179,6 @@ async def hangupCallback(mngr: Manager, msg: Message):
 @manager.register_event('VarSet')
 async def VarSetCallback(mngr: Manager, msg: Message):
   m = re.search(r"(.*savedb_)(.*)", msg.variable)
-  app.logger.warning('set vales {} res {}'.format(msg.variable,m))
   if (m):
     varname = m.group(2)
     value = msg.value
@@ -220,14 +219,42 @@ async def newchannelCallback(mngr: Manager, msg: Message):
              'callerId': cid,
              'did': did,
              'callId': uid}
-      if (msg.linkedid in  app.cache['cel_calls']) and ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
-        _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
-      if (msg.linkedid in  app.cache['cel_calls']) and ('CallerNumber' in app.cache['cel_calls'][msg.linkedid]):
-        _cb['CallerNumber'] = app.cache['cel_calls'][msg.linkedid]['CallerNumber']
-      if (msg.linkedid in  app.cache['cel_calls']) and ('BNumber' in app.cache['cel_calls'][msg.linkedid]):
-        _cb['BNumber'] = app.cache['cel_calls'][msg.linkedid]['BNumber']
+      if (msg.linkedid in  app.cache['cel_calls']):
+        fillCallbackParameters(_cb,app.cache['cel_calls'][msg.linkedid],cid)
       #reply = await doCallback(device, _cb)
 
+def fillCallbackParameters(cb,call,cid):
+    if ('WebCallId' in call):
+      cb['WebCallId'] = call['WebCallId']
+    if ('CallerNumber' in call):
+      cb['CallerNumber'] = call['CallerNumber']
+    elif ('AlertInfo' in call):
+      cb['CallerNumber'] = call['AlertInfo']
+    if  ('BNumber' in call):
+      cb['BNumber'] = call['BNumber']
+    elif ('AlertInfo' in call):
+      cb['BNumber'] = call['AlertInfo']
+    if ('ANumber' in call):
+      cb['ANumber'] = call['ANumber']
+    elif call.Context.startswith('from-pstn'):
+      cb['ANumber'] = cid
+
+async def getVariableFromPJSIP(callid,channel,variable_source,variable_destination=None):
+    if (variable_destination == None):
+      variable_destination = variable_source
+    value = await amiChannelGetVar(channel,"PJSIP_HEADER(read,{})".format(variable_source))
+    if (value):
+      app.logger.warning('set {}={} for {} from header'.format(variable_destination,value,callid))
+      app.cache['cel_calls'][callid][variable_destination] = value
+        
+async def getVariableFromChannel(callid,channel,variable_source,variable_destination=None):
+    if (variable_destination == None):
+      variable_destination = variable_source
+    value = await amiChannelGetVar(channel,variable_source)
+    if (value):
+      app.logger.warning('set {}={} for {} from channel'.format(variable_destination,value,callid))
+      app.cache['cel_calls'][callid][variable_destination] = value
+
 @manager.register_event('CEL')
 async def celCallback(mngr: Manager, msg: Message):
   #app.logger.warning('CEL {}'.format(msg))
@@ -261,10 +288,12 @@ async def celCallback(mngr: Manager, msg: Message):
       #  sip_call_id = await amiChannelGetVar(msg.Channel,"PJSIP_HEADER(read,Call-ID)")
       if (sip_call_id):
         await amiChannelSetVar(msg.Channel,"CDR(userfield)",sip_call_id)
-      webcallid = await amiChannelGetVar(msg.Channel,"PJSIP_HEADER(read,WebCallId)")
-      if (webcallid):
-        app.logger.warning('set webcallid {} for {} from header'.format(webcallid,lid))
-        app.cache['cel_calls'][lid]['WebCallId'] = webcallid
+      await getVariableFromPJSIP(lid,msg.Channel,"WebCallId")
+      await getVariableFromPJSIP(lid,msg.Channel,"CallerNumber","ANumber")
+      #await getVariableFromPJSIP(lid,msg.Channel,"CallerNumber")
+      await getVariableFromPJSIP(lid,msg.Channel,"BNumber")
+    else:
+      await getVariableFromChannel(lid,msg.Channel,"ALERT_INFO","AlertInfo")
     
   if (lid in app.cache['cel_calls']):
     firstMessage = app.cache['cel_calls'][lid]
@@ -279,7 +308,8 @@ async def celCallback(mngr: Manager, msg: Message):
            if device in app.cache['usermap']:
              user = app.cache['usermap'][device]
            did = firstMessage.Exten
-           _cb = {'user': user,
+           _cb = {'webhook_name': 'user_calling',
+             'user': user,
              'device': device,
              'state': 'ringing',
              'callerId': cid,
@@ -287,12 +317,8 @@ async def celCallback(mngr: Manager, msg: Message):
              'callId': uid} 
            if ('queueName' in app.cache['cel_calls'][msg.linkedid]):
              _cb['queue'] = app.cache['cel_calls'][msg.linkedid]['queueName']  
-           if ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
-           if ('CallerNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['CallerNumber'] = app.cache['cel_calls'][msg.linkedid]['CallerNumber']
-           if ('BNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['BNumber'] = app.cache['cel_calls'][msg.linkedid]['BNumber']
+           if (msg.linkedid in  app.cache['cel_calls']):
+             fillCallbackParameters(_cb,app.cache['cel_calls'][msg.linkedid],cid)
            reply = await doCallback(device, _cb)
     if ((msg.Application == 'Queue') and
         (msg.EventName == 'APP_START') and 
@@ -317,48 +343,44 @@ async def celCallback(mngr: Manager, msg: Message):
           if msg.EventName == 'CHAN_START':                          #start dial
             app.cache['cel_calls'][lid]['current_channels'][channel] = called
             app.cache['cel_calls'][lid]['all_channels'][channel] = called
-            _cb = {'user': called,
+            _cb = {'webhook_name':'group_user_start_calling',
+                 'user': called,
                  'state': 'group_start_ringing',
                  'callerId': cid,
                  'callId': msg.UniqueID}
           else:                                                      #end dial
             app.cache['cel_calls'][uid]['current_channels'].pop(channel, False)
-            _cb = {'user': called,
+            _cb = {'webhook_name':'group_user_stop_calling',
+                 'user': called,
                  'state': 'group_end_ringing',
                  'callerId': cid,
                  'callId': msg.UniqueID}
 
-          if ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
-              _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
-          if ('CallerNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['CallerNumber'] = app.cache['cel_calls'][msg.linkedid]['CallerNumber']
-          if ('BNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['BNumber'] = app.cache['cel_calls'][msg.linkedid]['BNumber']
+          if (msg.linkedid in  app.cache['cel_calls']):
+            fillCallbackParameters(_cb,app.cache['cel_calls'][msg.linkedid],cid)
           reply = await doCallback('groupRinging', _cb)
         if ((msg.EventName == 'ANSWER') and
           (msg.Application == 'AppDial') and
           (lid in app.cache['cel_calls'])):
           #called = msg.Exten
           app.cache['cel_calls'][lid]['answered'] = True
-          _cb = {'user': called,
+          _cb = {'webhook_name':'group_user_answered',
+               'user': called,
                'users': list(app.cache['cel_calls'][uid]['all_channels'].values()),
                'state': 'group_answer',
                'callerId': cid,
                'callId': msg.UniqueID}
-          if ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
-            _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
-          if ('CallerNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['CallerNumber'] = app.cache['cel_calls'][msg.linkedid]['CallerNumber']
-          if ('BNumber' in app.cache['cel_calls'][msg.linkedid]):
-             _cb['BNumber'] = app.cache['cel_calls'][msg.linkedid]['BNumber']
+          if (msg.linkedid in  app.cache['cel_calls']):
+            fillCallbackParameters(_cb,app.cache['cel_calls'][msg.linkedid],cid)
           reply = await doCallback('groupAnswered', _cb)
           
     if ((msg.Application == 'Queue') and
-        (firstMessage.Context == 'from-pstn')):
+        firstMessage.Context.startswith('from-pstn')):
       if (msg.EventName == 'APP_START'):
         app.cache['cel_queue_calls'][lid] = {'caller': msg.CallerIDnum, 'start': parseDatetime(msg.EventTime).isoformat()}
         app.cache['cel_calls'][lid]['queueName'] = msg.Exten
-        _cb = {'callid': lid, 
+        _cb = {'webhook_name':'queue_enter',
+            'callid': lid, 
             'caller': msg.CallerIDnum, 
             'start': parseDatetime(msg.EventTime).isoformat(),
             'callerfrom': firstMessage.Exten,
@@ -370,7 +392,8 @@ async def celCallback(mngr: Manager, msg: Message):
         app.cache['cel_calls'][lid]['queueName'] = False
         queue_changed = (call != None)
         if queue_changed :
-          _cb = {'callid': lid, 
+          _cb = {'webhook_name':'queue_leave',
+              'callid': lid, 
               'queue': msg.Exten,
               'agents': [q.user for q in app.cache['queues'][msg.Exten]]}
           reply = await doCallback('queueLeave', _cb)
@@ -379,12 +402,24 @@ async def celCallback(mngr: Manager, msg: Message):
     #  app.cache['cel_calls'][lid]['mix_monitors'].append(msg.Channel)
     #if ((msg.EventName == 'APP_END')  and (msg.Application == 'MixMonitor')):
     #  app.cache['cel_calls'][lid]['mix_monitors'].remove(msg.Channel)
-    
+    if (msg.EventName == "ANSWER" and msg.Application == 'AppDial' and not "answer_time" in app.cache['cel_calls'][lid]):
+      app.cache['cel_calls'][lid]["answer_time"]=msg.EventTime
     if (msg.EventName == 'LINKEDID_END'):
       for t in firstMessage['transfers']:
         #app.logger.warning('first {}'.format(t))
         (f,s) = t
         await db.execute(query='update cdr set transfer_from=(select distinct linkedid from cdr where uniqueid=:first) where linkedid=:second;',values={'first': f,'second': s})
+      if ("c2c_start_time" in app.cache['cel_calls'][lid]):
+        call = app.cache['cel_calls'][lid]
+        _cb = {'webhook_name': "c2c_end",
+               'asteriskCallId':msg.LinkedID,
+               'start_time': call["c2c_start_time"],
+               'end_time': msg.EventTime,
+               'ANumber': call["c2c_user"],
+               'BNumber': call["c2c_phone"]}
+        if "answer_time" in call:
+         _cb["answer_time"]=call["answer_time"]
+        app.logger.warning('c2c cb {}'.format(_cb))
       app.cache['cel_calls'].pop(lid, False)
       app.cache['cel_queue_calls'].pop(lid, False)
       
@@ -404,7 +439,17 @@ async def celCallback(mngr: Manager, msg: Message):
         vn,vv = value.split('=')
         _cb[vn] = vv
       reply = await doCallbackPostfix(callback_type,postfix, _cb)
-      
+    if (msg.EventName == 'USER_DEFINED') and (msg.UserDefType == 'START_C2C'):
+        app.logger.warning('c2c event {}'.format(msg))
+        app.cache['cel_calls'][lid]["c2c_start_time"]=msg.EventTime
+        app.cache['cel_calls'][lid]["c2c_user"] = msg.CallerIDnum
+        app.cache['cel_calls'][lid]["c2c_phone"] = msg.Exten
+        _cb = {'webhook_name': "c2c_start",
+             'asteriskCallId':msg.LinkedID,
+             'start_time': msg.EventTime,
+             'ANumber': msg.CallerIDnum,
+             'BNumber': msg.Exten}
+        app.logger.warning('c2c cb {}'.format(_cb))
 
 async def getCDR(start=None,
                  end=None,
@@ -1097,10 +1142,11 @@ async def rebindLostDevices():
 async def userStateChangeCallback(user, state, prevState = None):
   reply = None
   device = None
-  if ('HTTP_CLIENT' in app.config) and (user in app.cache['devicemap']):
+  if (user in app.cache['devicemap']):
     device = app.cache['devicemap'][user]
     if device is not None:
-      _cb = {'user': user,
+      _cb = {'webhook_name': 'user_status',
+             'user': user,
              'state': state,
              'prev_state':prevState}
       reply = await doCallback(device, _cb)