Browse Source

transfers

Hal De 2 năm trước cách đây
mục cha
commit
3df0a88e09
2 tập tin đã thay đổi với 46 bổ sung30 xóa
  1. 34 25
      app/app.py
  2. 12 5
      app/cel.py

+ 34 - 25
app/app.py

@@ -193,7 +193,7 @@ async def newchannelCallback(mngr: Manager, msg: Message):
     user = None
     device = None
     uid = None
-    if msg.context in ('from-pstn'):
+    if msg.context.startswith('from-pstn'):
       app.cache['calls'][msg.uniqueid]=msg
     elif ((msg.context in ('from-queue')) and
           (msg.linkedid in app.cache['calls']) and
@@ -203,7 +203,7 @@ async def newchannelCallback(mngr: Manager, msg: Message):
       user = msg.exten
       device = app.cache['devicemap'][user]
       uid = msg.linkedid
-    elif ((msg.context in ('from-internal')) and
+    elif ((msg.context.startswith('from-internal')) and
           (msg.exten in app.cache['devicemap'])):
       user = msg.exten
       device = app.cache['devicemap'][user]
@@ -256,27 +256,11 @@ async def getVariableFromChannel(callid,channel,variable_source,variable_destina
       app.cache['cel_calls'][callid][variable_destination] = value
     else:
       app.logger.warning('can\'t get {} for {} from channel'.format(variable_source,callid))
-
 @manager.register_event('CEL')
 async def celCallback(mngr: Manager, msg: Message):
   #app.logger.warning('CEL {}'.format(msg))
   lid = msg.LinkedID
-  if (msg.EventName == 'ATTENDEDTRANSFER'):
-    #app.logger.warning('CEL {}'.format(msg))
-    extra = json.loads(msg.Extra)
-    if ('transferee_channel_uniqueid' in extra) and ('channel2_uniqueid' in extra):
-      first = extra['transferee_channel_uniqueid']; #unique
-      second = extra['channel2_uniqueid']   #linked
-      firstname = extra['transferee_channel_name']
-      secondname = extra['channel2_name']
-      if (True or msg.CallerIDrdnis == '78124254209'):
-        res = await amiStopMixMonitor(firstname);
-        filename = "transfer-{}-{}-{}".format(msg.Exten, msg.CallerIDnum, msg.LinkedID);
-        res = await amiStartMixMonitor(firstname,filename);#2022/03/11/external-2534-1934-20220311-122726-1647001646.56557.wav
-        res = await amiChannelSetVar(firstname,"CDR(recordingfile)","{}.wav".format(filename))
-        #await amiStopMixMonitor(secondname);
-      app.cache['cel_calls'][lid]['transfers'].append((first,second)) #no cdr in db here
-      #app.logger.warning('first {} {}'.format(first,second))
+
     
   if ((msg.EventName == 'CHAN_START') and (lid == msg.UniqueID)):    #save first msg
     app.cache['cel_calls'][lid] = msg
@@ -315,6 +299,31 @@ async def celCallback(mngr: Manager, msg: Message):
     if firstMessage.CallerIDnum in app.cache['usermap']:
         cid = app.cache['usermap'][firstMessage.CallerIDnum]
     uid = firstMessage.LinkedID
+    
+    if (msg.EventName == 'ATTENDEDTRANSFER'):
+      #app.logger.warning('CEL {}'.format(msg))
+      extra = json.loads(msg.Extra)
+      if ('transferee_channel_uniqueid' in extra) and ('channel2_uniqueid' in extra):
+        first = extra['transferee_channel_uniqueid']; #unique
+        second = extra['channel2_uniqueid']   #linked
+        firstname = extra['transferee_channel_name']
+        secondname = extra['transfer_target_channel_name'].replace(";1",";2")
+        thirdname = extra['channel2_name'].replace(";1",";2")
+        if (True or msg.CallerIDrdnis == '78124254209' or msg.CallerIDani == '10001'):
+          if secondname != firstMessage.channel:
+            await amiStopMixMonitor(secondname)
+          if thirdname != firstMessage.channel: 
+            await amiStopMixMonitor(thirdname)            
+        if (True or msg.CallerIDrdnis == '78124254209'):
+          if firstname != firstMessage.channel:
+            res = await amiStopMixMonitor(firstname)
+          filename = "transfer-{}-{}-{}".format(msg.Exten, msg.CallerIDnum, msg.LinkedID);
+          res = await amiStartMixMonitor(firstname,filename);#2022/03/11/external-2534-1934-20220311-122726-1647001646.56557.wav
+          res = await amiChannelSetVar(firstname,"CDR(recordingfile)","{}.wav".format(filename))
+        ttime = datetime.strptime(msg.EventTime,"%Y-%m-%d %H:%M:%S")
+        app.cache['cel_calls'][lid]['transfers'].append((first,second,ttime)) #no cdr in db here
+        #app.logger.warning('first {} {}'.format(first,second))
+    
     if (msg.EventName == 'CHAN_START') and (lid != msg.UniqueID) and (not msg.Channel.startswith('Local/')):
         if (msg.CallerIDnum!=''): # or (firstMessage.Context == 'from-pstn') or (firstMessage.get('groupCall',False))):#all calls 
            device = msg.CallerIDnum
@@ -336,7 +345,7 @@ async def celCallback(mngr: Manager, msg: Message):
            reply = await doCallback(device, _cb)
     if ((msg.Application == 'Queue') and
         (msg.EventName == 'APP_START') and 
-        (firstMessage.Context == 'from-internal') and 
+        (firstMessage.Context.startswith('from-internal')) and 
         (cid is not None) and (len(cid) < 7)):
       app.cache['cel_calls'][lid]['groupCall'] = True
       app.cache['cel_calls'][lid]['queueName'] = msg.Exten
@@ -420,9 +429,9 @@ async def celCallback(mngr: Manager, msg: Message):
       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})
+        app.logger.warning('transfer {}'.format(t))
+        (f,s,tt) = t
+        await db.execute(query='update cdr set transfer_from=(select distinct linkedid from cdr where uniqueid=:first), transfer_time=:ttime where linkedid=:second;',values={'first': f,'second': s,'ttime':tt})
       if ("c2c_start_time" in app.cache['cel_calls'][lid]):
         call = app.cache['cel_calls'][lid]
         start = datetime.strptime(call["c2c_start_time"],"%Y-%m-%d %H:%M:%S")
@@ -566,7 +575,7 @@ async def getCallInfo(callid):
     if row['recordingfile'] is not None and row['recordingfile']  != '':
       row['recordingfile'] = '/static/records/{d.year}/{d.month:02}/{d.day:02}/{filename}'.format(d=row['calldate'],
                                                                                             filename=row['recordingfile'])
-    #app.logger.warning('event row {}'.format(row))   
+    app.logger.warning('event row {}'.format(row))   
     events.add(row)
   record = events.simple()                                                     
   return record
@@ -601,7 +610,7 @@ async def getUserCDR(user,
   start1 = (start-td(hours=4))
   end1 = (end+td(hours=4))
   _q = f'''SELECT * FROM cdr  WHERE linkedid in (select * from ({_linked_q}) tmp) and calldate BETWEEN "{start1}" AND "{end1}";'''
-  app.logger.warning('SQL: {}'.format(_q))
+  #app.logger.warning('SQL: {}'.format(_q))
   _cdr = {}
   async for row in db.iterate(query=_q):
     if (row['disposition']=='FAILED' and row['lastapp']=='Queue'):

+ 12 - 5
app/cel.py

@@ -52,7 +52,7 @@ class CdrEvents:
       return
     if (event.lastapp == 'Return' and (event.billsec==0 or not event.dstchannel)):
       return
-    if (event.lastapp == 'Dial' and event.lastdata.startswith("Local")):
+    if (event.lastapp == 'Dial' and (event.dcontext.startswith("from-internal-c2c") or event.dcontext == 'followme-check')):
       return
     if (event.lastapp == 'Return'):
       event.lastapp='Dial'
@@ -62,10 +62,17 @@ class CdrEvents:
         self._channels[event.channel.id] = event
     if (event.dstchannel and event.dstchannel.id not in self._dstchannels):
         self._dstchannels[event.dstchannel.id] = event.dst
-    if (self._waitingchannel is not None) and (self._waitingchannel.id == event.channel.id): # if dial event after queue event
+    
+    event.waiting = max(0,event.duration - event.billsec)
+    #when were transfer - count duration till transfer
+    if (event.lastapp=='Dial' and event.disposition=='ANSWERED' and event.transfer_time and event.transfer_time>event.calldate):
+      event.duration = (event.transfer_time - event.calldate).total_seconds()
+      event.billsec = event.duration - event.waiting
+  
+    if (self._waitingchannel is not None) and (self._waitingchannel.id == event.channel.id): # if dial event after queue event - set queue event timing using dial events
         for e in self._events:
           if (e.lastapp == 'Queue') and (e.dstchannel.id == event.channel.id):
-            e.duration = (event.calldate-e.calldate).total_seconds() +  event.duration 
+            e.duration = (event.calldate-e.calldate).total_seconds() +  event.duration  #waiting is dial waiting+difference between queue and dial start
             e.billsec = event.billsec
         self._waitingchannel = None
     if (event.lastapp == 'Queue'):
@@ -82,7 +89,7 @@ class CdrEvents:
           queueevent.duration = (dialevent.calldate-queueevent.calldate).total_seconds() +  dialevent.duration 
           queueevent.billsec = dialevent.billsec
         else:
-          self._waitingchannel = event.dstchannel # wait for dial event
+          self._waitingchannel = event.dstchannel # wait for dial event to fill timing
       else: 
         if queueevent.disposition != 'ANSWERED': #count total queue duration
           queueevent.duration = (event.calldate-queueevent.calldate).total_seconds() +  event.duration
@@ -126,7 +133,7 @@ class CdrEvents:
         simple_event = {'start': event.calldate,
             'answered': event.disposition=='ANSWERED',
             'duration': event.billsec,
-            'waiting': event.duration - event.billsec,
+            'waiting': max(0,event.duration - event.billsec),
             'application': event.lastapp,
             'caller': event.cnum,
             'dst': event.dst,