瀏覽代碼

refactoring

Hal De 3 年之前
父節點
當前提交
4d51317604
共有 1 個文件被更改,包括 79 次插入93 次删除
  1. 79 93
      app/app.py

+ 79 - 93
app/app.py

@@ -199,102 +199,76 @@ async def newchannelCallback(mngr: Manager, msg: Message):
         cid = msg.calleridnum
         cid = msg.calleridnum
       uid = msg.uniqueid
       uid = msg.uniqueid
     if device is not None:
     if device is not None:
-      row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
-                               values={'device': device})
-      if (row is not None) and (row['url'].startswith('http')):
-        reply = await app.config['HTTP_CLIENT'].post(row['url'],
-                                                     json={'user': user,
-                                                           'device': device,
-                                                           'state': 'ringing',
-                                                           'callerId': cid,
-                                                           'did': did,
-                                                           'callId': uid})
+      _cb = {'user': user,
+             'device': device,
+             'state': 'ringing',
+             'callerId': cid,
+             'did': did,
+             'callId': uid}
+      reply = await doCallback(device, _cb)
 
 
 @manager.register_event('CEL')
 @manager.register_event('CEL')
 async def celCallback(mngr: Manager, msg: Message):
 async def celCallback(mngr: Manager, msg: Message):
-    #app.logger.warning('CEL {}'.format(msg));
-    if (msg.EventName == 'CHAN_START')  and (msg.LinkedID == msg.UniqueID): #save first msg
-        app.cache['cel_calls'][msg.LinkedID] = msg
-        app.cache['cel_calls'][msg.LinkedID]['channels'] = {}
-    if (msg.LinkedID in app.cache['cel_calls']):
-        first_message = app.cache['cel_calls'][msg.LinkedID]
-        cid = first_message.CallerIDnum
-        uid = first_message.LinkedID
-        if (cid is not None) and (len(cid)<7): #for local calls only
-            if (msg.EventName == 'CHAN_START') and   (msg.Context in ('from-queue')) and ('HTTP_CLIENT' in app.config): #start dial
-                app.cache['cel_calls'][msg.LinkedID]['channels'][msg.Exten] = msg.Channel
-                app.logger.warning('NEW CALLING LIST {}'.format(','.join(app.cache['cel_calls'][uid]['channels'].keys())))
-                row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
-                                       values={'device': cid})
-                if (row is not None) and (row['url'].startswith('http')):
-                    values = {'users': list(app.cache['cel_calls'][uid]['channels'].keys()),
-                          'state': 'group_ringing',
-                          'callId': uid}
-                    app.logger.warning('call usrl {} values {}'.format(row['url'],values))
-                    reply = await app.config['HTTP_CLIENT'].post(row['url'],
-                                            json=values)
-                else:
-                    app.logger.warning('no url for {}'.format(cid))
-            if (msg.EventName == 'CHAN_END')  and  msg.Context in ('from-queue') and ('HTTP_CLIENT' in app.config) and ('answered' not in  first_message):#end dial
-                called = msg.CallerIDname
-                app.cache['cel_calls'][uid]['channels'].pop(called, False)
-                app.logger.warning('NEW CALLING LIST {}'.format(','.join(app.cache['cel_calls'][uid]['channels'].keys())))
-                row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
-                                           values={'device': cid})
-                if (row is not None) and (row['url'].startswith('http')):
-                    values = {'users': list(app.cache['cel_calls'][uid]['channels'].keys()),
-                              'state': 'group_ringing',
-                              'callId': uid}
-                    app.logger.warning('call usrl {} values {}'.format(row['url'],values))
-                    reply = await app.config['HTTP_CLIENT'].post(row['url'],
-                                        json=values)
-            if (msg.EventName == 'ANSWER') and (msg.Application == 'AppDial') and (msg.LinkedID in app.cache['cel_calls']) and ('HTTP_CLIENT' in app.config):
-                called = msg.Exten
-                app.cache['cel_calls'][msg.LinkedID]['answered']=1;
-                app.logger.warning('answered {}'.format(called))
-                row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
-                                           values={'device': cid})
-                if (row is not None) and (row['url'].startswith('http')):
-                    values = {'user': called, 'state': 'group_answer', 'callId': uid}
-                    app.logger.warning('call usrl {} values {}'.format(row['url'],values))
-                    reply = await app.config['HTTP_CLIENT'].post(row['url'],
-                                        json=values)
-
-        if (msg.Application == 'Queue') and (msg.Exten in ('1','2200')):
-           queue_changed=False;
-           if (msg.EventName == 'APP_START'):
-                app.cache['cel_queue_calls'][msg.LinkedID] = {'caller': msg.CallerIDnum, 'start': msg.EventTime};
-                queue_changed = 1;
-           if (msg.EventName == 'APP_END'):
-                call = app.cache['cel_queue_calls'].pop(msg.LinkedID,False);
-                queue_changed = (call != None);
-           if (msg.EventName == 'BRIDGE_ENTER'):
-                call = app.cache['cel_queue_calls'].pop(msg.LinkedID,False);
-                queue_changed = (call != None);
-           app.logger.warning('EVENT:{} changed:{}'.format(msg,queue_changed));
-           if queue_changed :
-               if (msg.EventName == 'APP_START'):
-                  row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :entity', values={'entity': 'queueEnter'});
-               else:
-                  row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :entity', values={'entity': 'queueLeave'});
-
-               if (row is not None) and (row['url'].startswith('http')):
-                    all_callers = app.cache['cel_queue_calls'] ;
-                    values = {'caller': msg.CallerIDnum, 'all': all_callers, 'callId': msg.LinkedID}
-                    app.logger.warning('call usrl {} values {}'.format(row['url'],values))
-                    reply = await app.config['HTTP_CLIENT'].post(row['url'],
-                                        json=values)
-        if (msg.EventName == 'LINKEDID_END'):
-           app.cache['cel_calls'].pop(msg.LinkedID,False);
-           app.cache['cel_queue_calls'].pop(msg.LinkedID,False);
-           app.logger.warning('Left Calls {}'.format(','.join(app.cache['cel_calls'].keys())))
-        if (msg.EventName == 'USER_DEFINED') and (msg.UserDefType == 'SETVARIABLE') :
-            app.logger.warning('SETVARIABLE({})'.format(msg))
-            extra = msg.AppData.split(',')[1];
-            varname =  extra.split('=')[0]
-            value = extra.split('=')[1]
-            app.logger.warning('SETVARIABLE({} is {})'.format(varname,value))
-            app.cache['cel_calls'][msg.linkedid][varname]=value
+  #app.logger.warning('CEL {}'.format(msg))
+  lid = msg.LinkedID
+  if ((msg.EventName == 'CHAN_START') and (lid == msg.UniqueID)):    #save first msg
+    app.cache['cel_calls'][lid] = msg
+    app.cache['cel_calls'][lid]['channels'] = {}
+  if (lid in app.cache['cel_calls']):
+    firstMessage = app.cache['cel_calls'][lid]
+    cid = firstMessage.CallerIDnum
+    uid = firstMessage.LinkedID
+    if (cid is not None) and (len(cid) < 7):                         #for local calls only
+      if msg.Context in ('from-queue'):
+        if ((msg.EventName == 'CHAN_START') or
+            ((msg.EventName == 'CHAN_END') and
+             ('answered' not in firstMessage))):
+          if msg.EventName == 'CHAN_START':                          #start dial
+            app.cache['cel_calls'][lid]['channels'][msg.Exten] = msg.Channel
+          else:                                                      #end dial
+            app.cache['cel_calls'][uid]['channels'].pop(msg.CallerIDname, False)
+          app.logger.warning(f'''NEW CALLING LIST: {','.join(app.cache['cel_calls'][uid]['channels'].keys())}''')
+          _cb = {'users': list(app.cache['cel_calls'][uid]['channels'].keys()),
+                 'state': 'group_ringing',
+                 'callId': uid}
+          reply = await doCallback(cid, _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
+        app.logger.warning(f'''answered {called}''')
+        _cb = {'user': called,
+               'state': 'group_answer',
+               'callId': uid}
+        reply = await doCallback(cid, _cb)
+    if ((msg.Application == 'Queue') and
+        (msg.Exten in ('1','2200'))):                                 #shouldn't be hardcoded!
+      queue_changed=False
+      if (msg.EventName == 'APP_START'):
+        app.cache['cel_queue_calls'][lid] = {'caller': msg.CallerIDnum, 'start': msg.EventTime}
+        queue_changed = True
+      if (msg.EventName in ('APP_END', 'BRIDGE_ENTER')):
+        call = app.cache['cel_queue_calls'].pop(lid,False)
+        queue_changed = (call != None)
+      app.logger.warning(f'''EVENT:{msg} changed:{queue_changed}''')
+      if queue_changed :
+        _cb = {'caller': msg.CallerIDnum,
+               'all': app.cache['cel_queue_calls'],
+               'callId': lid}
+        if (msg.EventName == 'APP_START'):
+          reply = await doCallback('queueEnter', _cb)
+        else:
+          reply = await doCallback('queueLeave', _cb)
+    if (msg.EventName == 'LINKEDID_END'):
+      app.cache['cel_calls'].pop(lid, False)
+      app.cache['cel_queue_calls'].pop(lid, False)
+      app.logger.warning(f'''Left Calls {','.join(app.cache['cel_calls'].keys())}''')
+    if (msg.EventName == 'USER_DEFINED') and (msg.UserDefType == 'SETVARIABLE'):
+      app.logger.warning(f'''SETVARIABLE({str(msg)})''')
+      varname, value = msg.AppData.split(',')[1].split('=')[0:2]
+      app.logger.warning(f'''SETVARIABLE({varname} is {value})''')
+      app.cache['cel_calls'][msg.linkedid][varname]=value
 
 
 async def getCDR(start=None,
 async def getCDR(start=None,
                  end=None,
                  end=None,
@@ -377,6 +351,18 @@ async def getUserCDR(user,
 async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
 async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
   return await getCDR(start, end, table, field, sort)
   return await getCDR(start, end, table, field, sort)
 
 
+async def doCallback(entity, msg):
+  row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device', values={'device': entity})
+  if (row is not None) and (row['url'].startswith('http')):
+    app.logger.warning(f'''POST {row['url']} data: {str(msg)}''')
+    if not 'HTTP_CLIENT' in app.config:
+      await initHttpClient()
+    reply = await app.config['HTTP_CLIENT'].post(row['url'], json=msg)
+    return reply
+  else:
+    app.logger.warning('No callback url defined for {}'.format(entity))
+  return None
+
 @app.before_first_request
 @app.before_first_request
 async def initHttpClient():
 async def initHttpClient():
   app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
   app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)