Exemplo n.º 1
0
   def edit(self, id=None, phone_id=None, dptm_id=None, user_id=None, 
         exten=None, **kw):
      ''' Display edit phone form
      '''
      ident = ''
      p = DBSession.query(Phone).get(id) if id else DBSession.query(Phone).get(phone_id)
      log.debug('Edit fax=%s, hide_from_phonebook=%s' % \
         (p.fax, p.hide_from_phonebook))
      v = {'phone_id': p.phone_id,
         'exten': p.exten,
         'dnis': p.dnis,
         'contexts': p.contexts.split(',') if  p.contexts else None,
         'callgroups': p.callgroups.split(',') if  p.callgroups else None,
         'pickupgroups': p.pickupgroups.split(',') if  p.pickupgroups else None,
         'dptm_id': p.department_id,
         'user_id': p.user_id,
         'hide_from_phonebook': p.hide_from_phonebook,
         'fax': p.fax,
         'block_cid_in': p.block_cid_in,
         'block_cid_out': p.block_cid_out,
         'priority': p.priority,
         'phonebook_label': p.phonebook_label,
         'secretary': p.secretary,
         '_method': 'PUT'}
      if p.exten: ident = p.exten
      elif p.mac: ident = p.mac

      tmpl_context.form = edit_phone_form
      return dict(title = u'Modification téléphone ' + ident, debug='', values=v)
Exemplo n.º 2
0
   def create(self, **kw):
      ''' Add new shortcut to DB
      '''

      if DBSession.query(Shortcut).filter(Shortcut.exten==kw['exten']).all() or \
         DBSession.query(Shortcut).filter(Shortcut.number==kw['number']).all():
         flash(u'Erreur : raccourci %s ou numéro %s existe déjà' % (
            kw['exten'], kw['number']), 'error')
         redirect('/shortcuts/')

      s = Shortcut()
      s.exten = kw['exten']
      s.number = kw['number']
      s.comment = kw['comment']
      s.phone = kw['phone']
      DBSession.add(s)
      flash(u'Nouveau raccourci "%s -> %s" créé' % (s.exten, s.number))

      if p.exten is not None:
         # Create new hint (extensions.conf)
         res = Globals.manager.update_config(
            directory_asterisk  + 'extensions.conf', 
            None, [('Append', 'shortcuts', 'exten', 
               '>%s,1,%s/%s' % \
                  (p.exten, 'SIP' if sip_type=='sip' else 'PJSIP', p.sip_id))])
         log.debug('Update hints extensions.conf returns %s' % res)

      redirect('/shortcuts/')
Exemplo n.º 3
0
def check_access():
   '''Check access rights / group: admin=full access, boss=users from same department, user.
   Returns SA Query object for selected CDRs
   '''

   if in_any_group('admin', 'APPELS'):
      cdrs = DBSession.query(CDR)

   elif in_group('CDS'):
      # Find list of phones from the user's list of phones
      # user_phones -> departments -> phones
      phones = []
      for p in request.identity['user'].phone:
         log.info('CDS phone %s -> department %s' % (p, p.department))
      for d in [d.department for d in request.identity['user'].phone]:
         log.info('CDS department <%s>' % (d))
         for p in d.phones:
            phones.append(p)
      src = [prefix_src + p.exten for p in phones]
      dst = [p.exten for p in phones]
      cdrs = DBSession.query(CDR).filter( (CDR.src.in_(src)) | (CDR.dst.in_(dst)) )
      log.info('CDS phone <%s> -> source <%s>, destination <%s>' % (
         request.identity['user'].phone, src, dst))


   elif in_group('utilisateurs'):
      src = [prefix_src + p.exten for p in request.identity['user'].phone]
      dst = [p.exten for p in request.identity['user'].phone]
      cdrs = DBSession.query(CDR).filter( (CDR.src.in_(src)) | (CDR.dst.in_(dst)) )

   else:
      flash(u'Accès interdit')
      redirect('/')

   return cdrs
Exemplo n.º 4
0
   def delete(self, id, **kw):
      ''' Delete queue from DB
      '''
      log.info(u'delete ' + kw['_id'])
      q = DBSession.query(Queue).get(kw['_id'])
      gn = (u'SV %s' % q.name, u'AG %s' % q.name)
      log.info(u'delete ' + kw['_id'])
      DBSession.delete(q)

      # Delete supervisor and members groups
      for g in DBSession.query(Group).filter(Group.group_name.in_(gn)):
         log.info(u'delete group "%s"' % g)
         DBSession.delete(g)

      # Remove MOH dir
      moh_class = asterisk_string(q.name, no_space=True)
      moh_dir = '/var/lib/asterisk/moh/fr/astportal/%s' % moh_class
      asterisk_shell('rm -rf "%s"' % moh_dir)
      res = Globals.manager.update_config(
         dir_asterisk  + 'musiconhold.conf', None, [('DelCat', moh_class)])

      # Delete Asterisk queue
      res = Globals.manager.update_config(
         dir_asterisk + 'queues.conf', 
         None, [('DelCat', moh_class)])
      log.debug('Delete queue "%s" returns %s' % (moh_class, res))
      Globals.manager.send_action({'Action': 'QueueReload'})
      if q.name in Globals.asterisk.queues.keys():
         # Delete from list of queues
         del(Globals.asterisk.queues[moh_class])
      Globals.manager.send_action({'Action': 'QueueStatus'})

      flash(u'Groupe d\'appels supprimé', 'notice')
      redirect('/queues/')
Exemplo n.º 5
0
def play_or_tts(typ, val, brk=None):
    """ Choose Playback / Background or RealSpeak 
   Return app, param
   """
    if typ == "s":
        # XXX      if val not in application.sounds:
        # XXX         application.sounds.append(DBSession.query(Sound).get(val))
        s = DBSession.query(Sound).get(val)
        name = "astportal/%s" % s.name if s is not None else "beep"
        if brk is not None:
            app = u"Background"
            param = u"%s" % (name)
        else:
            app = u"Playback"
            param = u"%s" % (name)

    elif typ == "t":
        # XXX      if val not in application.texts:
        # XXX         application.texts.append(DBSession.query(Text).get(val))
        app = u"RealSpeak"
        txt = DBSession.query(Text).get(val)
        param = u"%s" % (txt.text.replace(",", "\,"))
        if brk is not None:
            param += u",%s" % (brk)

    return (app, param)
Exemplo n.º 6
0
   def create(self, pwd1, pwd2, **kw):
      ''' Add new user to DB
      '''
      if DBSession.query(User).filter(User.user_name==kw['user_name']).all():
         flash(u'Ce compte existe déjà, utilisateur pas créé', 'error')
         redirect('/users/')

      log.info('new ' + kw['user_name'])
      u = User()
      u.user_name = kw['user_name']
      u.firstname = kw['firstname']
      u.lastname = kw['lastname']
      u.email_address = kw['email_address']
      u.fax = kw['fax']
      u.voicemail = kw['voicemail']
      u.email_voicemail = kw['email_voicemail']
      u.password = pwd1
      u.display_name = u.lastname + ' ' + u.firstname
      u.ascii_name = asterisk_string(u.display_name)
      over = kw.get('over')
      if over is not None:
         Globals.manager.send_action({'Action': 'DBput',
            'Family': 'over', 'Key': over, 'Val': 'context'})

      if 'groups' in kw:
         u.groups = DBSession.query(Group).\
               filter(Group.group_id.in_(kw['groups'])).all()

      DBSession.add(u)
      flash(u'Nouvel utilisateur "%s" créé' % (kw['user_name']))

      redirect('/users/')
Exemplo n.º 7
0
   def create_forward(self, cf_types, to_intern, to_extern=None, **kw):
      ''' Add call forward to Asterisk database
      '''
      log.debug('create_forward: %s %s %s' % (cf_types, to_intern, to_extern))
      dest = to_extern if to_extern else to_intern
      u = DBSession.query(User). \
            filter(User.user_name==request.identity['repoze.who.userid']). \
            one()
      for phone in u.phone:
         man = Globals.manager.command('database put %s %s %s' % (
            cf_types, phone.sip_id, dest))
         log.debug('database put %s %s %s returns %s' % (
            cf_types, phone.sip_id, dest, man))

         # Notify user's phone
         man = Globals.manager.command('sip notify grandstream-idle-screen-refresh %s' % (
            phone.sip_id))
         log.debug('sip notify grandstream-idle-screen-refresh %s returns %s' % (
            phone.sip_id, man))

      if len(dest) < 6:
         # Notify dest phone if not external
         try:
            phone = DBSession.query(Phone).filter(Phone.exten==dest).one()
            man = Globals.manager.command('sip notify grandstream-idle-screen-refresh %s' % (
               phone.sip_id))
            log.debug('sip notify grandstream-idle-screen-refresh %s returns %s' % (
               phone.sip_id, man))
         except:
            log.warning('Phone not found for dest "%s"')

#      flash(u'Une erreur est survenue', 'error')

      redirect('/forwards/')
Exemplo n.º 8
0
   def create_admin(self, cf_types, exten, to_intern, to_extern):
      ''' Add call forward to Asterisk database
      '''
      try:
         p = DBSession.query(Phone).filter(Phone.exten==exten).one()
      except:
         log.warning('No phone for extension %s' % exten)
         flash(u'Poste %s inexistant, renvoi non créé' % exten, 'error')
         redirect('/forwards/')

      dest = to_extern if to_extern else to_intern
      man = Globals.manager.command('database put %s %s %s' % (
         cf_types, p.sip_id, dest))
      log.debug('database put %s %s %s returns %s' % (
         cf_types, p.sip_id, dest, man))

      # Notify user's phone
      man = Globals.manager.command('sip notify grandstream-idle-screen-refresh %s' % (
         p.sip_id))
      log.debug('sip notify grandstream-idle-screen-refresh %s returns %s' % (
         p.sip_id, man))

      if len(dest) < 6:
         # Notify dest phone if not external
         try:
            p = DBSession.query(Phone).filter(Phone.exten==dest).one()
            man = Globals.manager.command('sip notify grandstream-idle-screen-refresh %s' % (
               p.sip_id))
            log.debug('sip notify grandstream-idle-screen-refresh %s returns %s' % (
               p.sip_id, man))
         except:
            log.warning('Phone not found for dest "%s"')

#      flash(u'Une erreur est survenue', 'error')
      redirect('/forwards/')
Exemplo n.º 9
0
   def delete(self, id, **kw):
      ''' Delete call forward
      '''
      exten, cf, to = kw['_id'].split(':')
      try:
         p = DBSession.query(Phone).filter(Phone.exten==exten).one()
      except:
         log.warning('No phone for extension %s' % exten)
         flash(u'Poste %s inexistant, renvoi non supprimé' % exten, 'error')
         redirect('/forwards/')

      log.info('delete %s %s %s' % (p.sip_id, cf, to))
      if in_any_group('admin', 'CDS'):
         man = Globals.manager.command('database del %s %s' % (
            cf, p.sip_id))
         log.debug('admin: database delete %s %s returns %s' % (
            cf_types, p.sip_id, man))

      else:
         u = DBSession.query(User).get(request.identity['user'].user_id)
         for p in u.phone:
            man = Globals.manager.command('database del %s %s' % (
               cf, p.sip_id))
            log.debug('database delete %s %s returns %s' % (
               cf, p.sip_id, man))
#      flash(u'Une erreur est survenue', 'error')

      redirect('/forwards/')
Exemplo n.º 10
0
   def create(self, **kw):
      ''' Add new pickup to DB
      '''

      if DBSession.query(Pickup).filter(Pickup.name==kw['name']).all():
         flash(u'Ce groupe existe déjà, pas créé', 'error')
         redirect('/pickups/')

      # Find new pickup group (0-63)
      i = 0
      for p in DBSession.query(Pickup).order_by(Pickup.pickup_id):
         if p.pickup_id!=i: break
	 i += 1

      if i>63:
         flash(u'Nombre maximum de groupe d\'interceptions atteint, création impossible',
            'error')

      else:
         p = Pickup()
         p.pickup_id = i
         p.name = kw['name']
         p.comment = kw['comment']
         DBSession.add(p)
         flash(u'Nouveau groupe d\'interception "%s" créé' % (kw['name']))

      redirect('/pickups/')
Exemplo n.º 11
0
   def listen(self, id, **kw):
      ''' Listen record
      '''
      r = DBSession.query(Record).get(id)
      fn = '%s/rec-%s.wav' % (dir_monitor, r.uniqueid)
      try:
         st = stat(fn)
      except:
         flash(u'Enregistrement introuvable: %s' % fn, 'error')
         redirect('/records/')

      phones = DBSession.query(User).filter(User.user_name==request.identity['repoze.who.userid']).one().phone
      if len(phones)<1:
         log.debug('Playback from user %s : no extension' % (
            request.identity['user']))
         flash(u'Poste de l\'utilisateur %s introuvable' % \
               request.identity['user'], 'error')
         redirect('/records/')

      sip = phones[0].sip_id
      res = Globals.manager.originate(
            'SIP/' + sip, # Channel
            sip, # Extension
            application = 'Playback',
            data = fn[:-4],
            )
      log.debug('Playback %s from user %s (%s) returns %s' % (
         fn[:-4], request.identity['user'], sip, res))

      redirect('/records/')
Exemplo n.º 12
0
    def fetch_scenario(self, id, page=1, rp=25, sortname="name", sortorder="asc", qtype=None, query=None):
        """ Function called on AJAX request made by FlexGrid
      Fetch data from DB, return the list of rows + total + current page
      """

        actions = [
            {"action_id": x.action_id, "action_name": x.name, "action_comment": x.comment}
            for x in DBSession.query(Action).order_by(Action.name)
        ]

        owner = ""  # DBSession.query(Application.owner_id).get(id)[0]

        sounds = [
            {"sound_id": x.sound_id, "sound_name": x.name, "sound_comment": x.comment}
            for x in DBSession.query(Sound).filter(Sound.type == 1).order_by(Sound.name)
        ]

        texts = []

        queues = [
            {"queue_id": x.queue_id, "queue_name": x.name, "queue_comment": x.comment}
            for x in DBSession.query(Queue).order_by(Queue.name)
        ]

        qevents = [
            {"qe_id": x.qe_id, "event": x.event} for x in DBSession.query(Queue_event).order_by(Queue_event.event)
        ]

        scenario = []
        positions = {}
        for x in (
            DBSession.query(Scenario).filter(Scenario.app_id == id).order_by(Scenario.context).order_by(Scenario.step)
        ):
            scenario.append(
                {
                    "sce_id": x.sce_id,
                    "context": x.context,
                    "extension": x.extension,
                    "priority": x.step,
                    "application": x.action,
                    "parameters": x.parameters,
                    "comments": x.comments,
                    "target": 0,
                }
            )
            if x.top and x.left:
                context = "context_" + x.context
                positions[context] = {"top": x.top, "left": x.left}

        return dict(
            scenario=scenario,
            sounds=sounds,
            texts=texts,
            actions=actions,
            queues=queues,
            qevents=qevents,
            positions=positions,
        )
Exemplo n.º 13
0
   def record(self, name, channel, queue, custom1=None, custom2=None):
      '''Record a queue member
         Called from call center monitor web page

Action: Monitor
Mix: 1
File: test
Channel: SIP/pEpSNlcv-000001b9
   '''
      log.debug('Record request "%s" (%s) on "%s"' % (name, channel, queue))

      # Check channel exists, else abort
      for cha in Globals.asterisk.channels.keys():
         if cha.startswith(channel):
            unique_id = Globals.asterisk.channels[cha]['Uniqueid']
            break
      else:
         log.warning('No active channel for %s ?' % channel)
         return dict(status=0)

      # XXX Authentification

      # Gather data from database
      user_id = DBSession.query(User).filter(
         User.user_name==request.identity['repoze.who.userid']).one().user_id
      member_id = DBSession.query(Phone).filter(
         Phone.sip_id==channel[-8:]).one().user_id
      queue_id = DBSession.query(Queue).filter(
            Queue.name==queue).one().queue_id

      # Create filename and send record action to Asterisk via manager
      f = 'rec-%s' % unique_id
      res = Globals.manager.send_action(
            {  'Action': 'Monitor',
               'Mix': 1,
               'Channel': cha,
               'File': f})
      log.info('Record request from userid "%s" to channel %s returns "%s"' % ( 
         user_id, cha, res))

      if res.get_header('Response')=='Success':
         status = 0
         # Set "recorded" flag on member
         Globals.asterisk.members[name]['Recorded'] = True
         # Insert record info into database
         r = Record()
         r.uniqueid = unique_id
         r.queue_id = queue_id
         r.member_id = member_id
         r.user_id = user_id
         r.custom1 = custom1
         r.custom2 = custom2
         DBSession.add(r)

      else:
         status = 1

      return dict(status=status)
Exemplo n.º 14
0
   def update_params(self,d):
      opt_ext = [(p.exten, p.exten) for p in DBSession.query(Phone).order_by(Phone.exten)]
      if in_group('admin'):
#         help_text = u'Sélectionnez le poste interne ou le SVI destination du renvoi'
         opt_ivr = [(a.exten, a.name) for a in DBSession.query(Application).order_by(Application.name)]
         d['options'] = [(u'Postes', opt_ext), (u'SVI', opt_ivr)]
      else:
         d['options'] = opt_ext
      SingleSelectField.update_params(self, d)
      return d
Exemplo n.º 15
0
def members_options():
   ''' Returns distinct members from queue log
   '''
   # queue_event_id==24 => AddMember
   uids = [a.user for a in DBSession.query(Queue_log.user).distinct(). \
         filter(Queue_log.queue_event_id==24)]
   log.debug(u'Queue members uids=%s' % uids)

   return [(a.user_id, a.display_name) for a in DBSession.query(User). \
         filter(User.user_id.in_(uids)).order_by(User.display_name)]
Exemplo n.º 16
0
   def fetch(self, page, rows, sidx='user_name', sord='asc', _search='false',
          searchOper=None, searchField=None, searchString=None, **kw):
      ''' Function called on AJAX request made by Grid JS component
      Fetch data from DB, return the list of rows + total + current page
      '''

      # Try and use grid preference
      grid_rows = session.get('grid_rows', None)
      if rows=='-1': # Default value
         rows = grid_rows if grid_rows is not None else 25

      # Save grid preference
      session['grid_rows'] = rows
      session.save()
      rows = int(rows)

      try:
         page = int(page)
         rows = int(rows)
         offset = (page-1) * rows
      except:
         offset = 0
         page = 1
         rows = 25

      pickup = DBSession.query(Pickup)
      total = pickup.count()/rows + 1
      column = getattr(Pickup, sidx)
      pickup = pickup.order_by(getattr(column,sord)()).offset(offset).limit(rows)

      # Find phones belonging to call / pickup groups
      callgroups  = [[] for x in xrange(64)]
      pickupgroups  = [[] for x in xrange(64)]
      for f in DBSession.query(Phone):
         if f.callgroups:
            try:
               for g in f.callgroups.split(','):
                  callgroups[int(g)].append(f.exten)
            except:
               callgroups[int(g)].append(f.exten)
         if f.pickupgroups:
            try:
              for g in f.pickupgroups.split(','):
                  pickupgroups[int(g)].append(f.exten)
            except:
               pickupgroups[int(g)].append(f.exten)

      data = [ { 'id'  : p.pickup_id, \
            'cell': row(p, callgroups[p.pickup_id], pickupgroups[p.pickup_id]) 
            } for p in pickup ]

      return dict(page=page, total=total, rows=data)
Exemplo n.º 17
0
def campaign_row(c):
   '''Displays a formatted row of the campaigns list
   Parameter: Campaign object
   '''
   row = []
   now = datetime.now()
   active = False
   if c.active:
      if c.begin and c.end:
         if c.begin<now<c.end: 
            active = True
      elif c.begin:
         if c.begin<now:
            active = True
      elif c.end:
         if now<c.end:
            active = True
      else: 
         active = True
   if active:
      row.append(
         u'<a href="#" onclick="postdata(\'list\',{cmp_id:%d, cmp_name:\'%s\'})" title="Utiliser">%s</a>' % (
         c.cmp_id, c.name, c.name))
   else:
      row.append(c.name)

   if c.active:
      if c.begin and c.end:
         row.append(u'Du %s au %s' %(
            c.begin.strftime('%d/%m/%y %H:%M'),
            c.end.strftime('%d/%m/%y %H:%M') ))
      elif c.begin:
         row.append(u'\u00C0 partir du %s' % c.begin.strftime('%d/%m/%y %H:%M'))
      elif c.end:
         row.append(u"Jusqu'au %s" % c.end.strftime('%d/%m/%y %H:%M'))
      else:
         row.append(u'Oui')
   else:
      row.append(u'Non')

   row.append(cmp_types[1+c.type][1])
   row.append(u'%d / %d' % (DBSession.query(Customer). \
         filter(Customer.cmp_id==c.cmp_id). \
         filter(Customer.active==True).count(),
      DBSession.query(Customer). \
         filter(Customer.cmp_id==c.cmp_id). \
         count()))

   return row
Exemplo n.º 18
0
    def save_scenario(self, id, **kw):

        if kw.has_key("scenario[]"):
            scenario = kw["scenario[]"]
        else:
            log.error(u"No scenario to save ???")
            scenario = None
            return dict(result=0)  # XXX ?

        positions = {}
        if type(kw["positions[]"]) != type([]):
            kw["positions[]"] = (kw["positions[]"],)
        for p in kw["positions[]"]:
            log.debug(p)
            (context, top, left) = p.split("::")
            positions[context] = (int(float(top)), int(float(left)))

        log.info("save_scenario %s, type %s" % (id, type(scenario)))
        application = DBSession.query(Application).get(int(id))

        # 1. Delete old entries
        DBSession.query(Scenario).filter(Scenario.app_id == int(id)).delete()

        # 2. Create new ones
        if scenario:
            if type(scenario) != type([]):
                scenario = (scenario,)
            for s in scenario:
                sc = Scenario()
                (c, i, e, p, a, m) = s.split("::", 5)
                p = 1 + int(p)
                (sc.comments, sc.app_id, sc.context, sc.extension, sc.step, sc.action, sc.parameters) = (
                    c,
                    id,
                    i,
                    e,
                    p,
                    a,
                    m,
                )
                if p == 1:
                    i = "context_%s" % i
                    log.debug(u"position %s" % i)
                    if i in positions.keys():
                        sc.top = positions[i][0]
                        sc.left = positions[i][1]
                DBSession.add(sc)

        return dict(result=generate_dialplan())
Exemplo n.º 19
0
   def download(self, id, **kw):
      ''' Download sound
      '''
      s = DBSession.query(Sound).get(id)
      dir = (dir_moh if s.type==0 else dir_sounds) % s.language
      fn = '%s/%s.' % (dir, re.sub(r'\W', '_', s.name))
      import os
      for form in ( 'wav', 'sln16', 'sln' ):
         try:
            st = os.stat(fn + form)
            f = open(fn + form)
            fn += form
            break
         except:
            log.debug(u'Sound file not found %s' % (fn+form))
            pass
      else:
         flash(u'Fichier sonore introuvable: %s' % fn, 'error')
         redirect('/moh/')

      rh = response.headers
      rh['Pragma'] = 'public' # for IE
      rh['Expires'] = '0'
      rh['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0' #for IE
      rh['Cache-Control'] = 'max-age=0' #for IE
      rh['Content-Type'] = 'audio/wav'
      rh['Content-Disposition'] = str( (u'attachment; filename="%s.%s"; size=%d;' % (
         s.name, form, st.st_size)).encode('utf-8') )
      rh['Content-Transfer-Encoding'] = 'binary'
      return f.read()
Exemplo n.º 20
0
   def put(self, **kw):
      ''' Update sound in DB
      '''
      id = int(kw['id'])
      s = DBSession.query(Sound).get(id)
      if kw.has_key('owner_id'):
         s.owner_id = kw['owner_id']
      s.comment = kw['comment']

      wav = kw['file']
      filetype = wav.type
      filedata = wav.file
      filename = '%s/%d_%s' % (dir_tmp, s.sound_id, wav.filename)
      # Temporarily save uploaded audio file
      out = open(filename, 'w')
      out.write(filedata.read())
      out.close()

      ret = process_file(filename, filetype, s.sound_id, filetype, s.name, s.language)

      if ret:
         flash(ret,'error')
         DBSession.delete(s)
         redirect('/moh/')

      flash(u'Son modifié')
      redirect('/moh/%d/edit' % id)
Exemplo n.º 21
0
   def fetch(self, page, rows, sidx='user_name', sord='asc', _search='false',
          searchOper=None, searchField=None, searchString=None, **kw):
      ''' Function called on AJAX request made by FlexGrid
      Fetch data from DB, return the list of rows + total + current page
      '''

      # Try and use grid preference
      grid_rows = session.get('grid_rows', None)
      if rows=='-1': # Default value
         rows = grid_rows if grid_rows is not None else 25

      # Save grid preference
      session['grid_rows'] = rows
      session.save()
      rows = int(rows)

      try:
         page = int(page)
         rows = int(rows)
         offset = (page-1) * rows
      except:
         offset = 0
         page = 1
         rows = 25

      sounds = DBSession.query(Sound)

      total = sounds.count()/rows + 1
      column = getattr(Sound, sidx)
      sounds = sounds.order_by(getattr(column,sord)()).offset(offset).limit(rows)
      rows = [ { 'id'  : s.sound_id, 'cell': row(s) } for s in sounds ]

      return dict(page=page, total=total, rows=rows)
Exemplo n.º 22
0
   def outcall_fetch(self, page, rows, sidx, sord, cust_id, **kw):
      ''' Function called on AJAX request made by FlexGrid
      Fetch data from DB, return the list of rows + total + current page
      '''

      # Try and use grid preference
      grid_rows = session.get('grid_rows', None)
      if rows=='-1': # Default value
         rows = grid_rows if grid_rows is not None else 25

      # Save grid preference
      session['grid_rows'] = rows
      session.save()
      rows = int(rows)

      try:
         page = int(page)
         rows = int(rows)
         offset = (page-1) * int(rp)
      except:
         offset = 0
         page = 1
         rows = 25

      data = DBSession.query(Outcall, CDR) \
         .outerjoin(CDR, Outcall.uniqueid==CDR.uniqueid) \
         .filter(Outcall.cust_id==cust_id)

      total = 1 + data.count() / rows
      column = getattr(Outcall, sidx)
      data = data.order_by(getattr(column,sord)()).offset(offset).limit(rows)
      rows = [ 
         { 'id'  : a.Outcall.out_id, 'cell': outcall_row(a) } for a in data ]

      return dict(page=page, total=total, rows=rows)
Exemplo n.º 23
0
    def fetch(self, page, rows, sidx, sord, **kw):
        """ Function called on AJAX request made by FlexGrid
      Fetch data from DB, return the list of rows + total + current page
      """

        # Try and use grid preference
        grid_rows = session.get("grid_rows", None)
        if rows == "-1":  # Default value
            rows = grid_rows if grid_rows is not None else 25

        # Save grid preference
        session["grid_rows"] = rows
        session.save()
        rows = int(rows)

        try:
            page = int(page)
            rows = int(rows)
            offset = (page - 1) * int(rp)
        except:
            offset = 0
            page = 1
            rows = 25

        apps = DBSession.query(Application)
        total = apps.count()
        column = getattr(Application, sidx)
        apps = apps.order_by(getattr(column, sord)()).offset(offset).limit(rows)
        rows = [{"id": a.app_id, "cell": row(a)} for a in apps]

        return dict(page=page, total=total, rows=rows)
Exemplo n.º 24
0
   def get_all(self):
      ''' List all users
      '''
      if not in_group('admin'):
         redirect( str(request.identity['user'].user_id) + '/edit')

      grid = MyJqGrid( id='grid', url='fetch', caption=u'Utilisateurs',
            colNames = [u'Action', u'Compte', u'Nom', u'email', u'Poste', u'Groupes'],
            colModel = [
               { 'sortable': False, 'search': False, 'width': 80, 'align': 'center' },
               { 'name': 'user_name', 'width': 80 },
               { 'name': 'display_name', 'width': 120 },
               { 'name': 'email_address', 'width': 180 },
               { 'name': 'phone', 'width': 60, 'sortable': False, 'search': False },
               { 'name': 'groups', 'width': 160, 'sortable': False, 'search': False } ],
            sortname = 'user_name',
            navbuttons_options = {'view': False, 'edit': False, 'add': True,
               'del': False, 'search': True, 'refresh': True, 
               'addfunc': js_callback('add'),
               }
            )
      tmpl_context.grid = grid
      tmpl_context.form = None
      tmpl_context.count = u'Total : %d utilisateurs' % DBSession.query(User).count()
      return dict( title=u'Liste des utilisateurs', debug='')
Exemplo n.º 25
0
   def put(self, queue_id, **kw):
      ''' Update queue in DB
      '''
      log.info('update %d, monitor=%s' % (queue_id, kw['monitor']))
      q = DBSession.query(Queue).get(queue_id)
      q.comment = kw['comment']
      q.music_id = int(kw['music']) if kw['music']!='-1' else None
      q.announce_id = int(kw['announce']) if kw['announce']!='-1' else None
      q.strategy = kw['strategy']
      q.wrapuptime = int(kw['wrapuptime'])
      q.connectdelay = int(kw['connectdelay'])
      q.connecturl = kw['connecturl']
      q.hangupurl = kw['hangupurl']
      q.timeout = kw['timeout']
      q.announce_frequency = int(kw['announce_frequency'])
      q.min_announce_frequency = int(kw['min_announce_frequency'])
      q.announce_holdtime = 1 if kw['announce_holdtime']=='yes' else 0
      q.announce_position = 1 if kw['announce_position']=='yes' else 0
      q.priority = kw['priority']
      q.monitor = kw['monitor']
      flash(u'Groupe d\'appel modifié')

      # Update Asterisk queue
      asterisk_update_queue(q)
      Globals.manager.send_action({'Action': 'QueueStatus'})

      redirect('/queues/%d/edit' % queue_id)
Exemplo n.º 26
0
   def fetch(self, page, rows, sidx='name', sord='desc', _search='false',
          searchOper=None, searchField=None, searchString=None, **kw):
      ''' Function called on AJAX request made by Grid JS component
      Fetch data from DB, return the list of rows + total + current page
      '''

      # Try and use grid preference
      grid_rows = session.get('grid_rows', None)
      if rows=='-1': # Default value
         rows = grid_rows if grid_rows is not None else 25

      # Save grid preference
      session['grid_rows'] = rows
      session.save()
      rows = int(rows)

      try:
         page = int(page)
         rows = int(rows)
         offset = (page-1) * rows
      except:
         offset = 0
         page = 1
         rows = 25

      queue = DBSession.query(Queue)
      total = queue.count()/rows + 1
      column = getattr(Queue, sidx)
      queue = queue.order_by(getattr(column,sord)()).offset(offset).limit(rows)
      data = [ { 'id'  : q.queue_id, 'cell': row(q) } for q in queue ]

      return dict(page=page, total=total, rows=data)
Exemplo n.º 27
0
   def listen(self,  mb, folder, id, to):
      ''' Listen sound
      '''
      log.debug('listen %s %s %s %s' % (mb, folder, id, to))
      name = 'msg%04d.wav' % int(id)
      fn = '%s/%s/%s/%s' % (dir_vm, mb, folder, name)
      try:
         st = stat(fn)
         f = open(fn)
      except:
         flash(u'Message introuvable: %s' % fn, 'error')

      phones = DBSession.query(User).filter(User.user_name==request.identity['repoze.who.userid']).one().phone
      if len(phones)<1:
         log.debug('Playback from user %s : no extension' % (
            request.identity['user']))
         flash(u'Poste de l\'utilisateur %s introuvable' % \
               request.identity['user'], 'error')
         redirect('/voicemail/?folder=%s' % folder)

      sip = phones[0].sip_id
      res = Globals.manager.originate(
            'SIP/' + sip, # Channel
            sip, # Extension
            application = 'Playback',
            data = fn[:-4],
            )
      log.debug('Playback %s from user %s (%s) returns %s' % (
         fn[:-4], request.identity['user'], sip, res))

      redirect('/voicemail/?folder=%s' % folder)
Exemplo n.º 28
0
   def check_phone(self, ip, pwd=None, mac=None):
      # Check phone is connected,  get hardware address
      log.debug('%s %s &> /dev/null' % (command_fping, ip))
      ret = system('%s %s &> /dev/null' % (command_fping, ip))
      if ret:
         return dict(status=1, msg=u"Téléphone injoignable, vérifiez l'adresse")
      if not mac:
         ret = popen('%s %s' % (command_arp, ip)).readlines()
         log.debug('arp -> ' + str(ret))
         if len(ret)!=2:
            return dict(status=2, msg=u"Téléphone injoignable, vérifiez l'adresse")
         mac = ret[1]
      match = re.search('(\w\w:\w\w:\w\w):(\w\w:\w\w:\w\w)', mac.lower())
      if not match:
         return dict(status=3, msg=u"Téléphone injoignable, vérifiez l'adresse")
      vendor, device = match.groups()
      log.debug('vendor=%s, device=%s' % (vendor,device))
      if vendor not in _vendors.keys():
         return dict(status=4, msg=u"Type de téléphone inconnu")

      mac = '%s:%s' % (vendor,device)
      p = DBSession.query(Phone).filter(Phone.mac==mac).all()
      if len(p):
         return dict(status=5, 
               msg = u'Téléphone existant, voulez-vous le \
                     <a href="/phones/%s/edit">modifier</a>.' % p[0].phone_id)

      if _vendors[vendor]=='Grandstream':
         new_phone = Grandstream(ip, mac)
         msg = u"Trouvé téléphone Grandstream : "
         if not new_phone.login(pwd):
            return dict(status=6, msg=msg+u'erreur login')
         infos = new_phone.infos()
         if not infos:
            return dict(status=6, msg=msg+u'erreur login')

         session['new_phone'] = new_phone
         session.save()

         return dict(status = 0, ip = ip, mac = mac, conf = 'grandstream_configure',
               msg = msg + infos['model'] + ', ' + infos['version'])

      elif _vendors[vendor]=='Cisco':
         new_phone = Cisco(ip, mac)
         msg = u"Trouvé téléphone Cisco : "
         if not new_phone.login(pwd):
            return dict(status=6, msg=msg+u'erreur login')
         infos = new_phone.infos()
         if not infos:
            return dict(status=6, msg=msg+u'erreur login')

         session['new_phone'] = new_phone
         session.save()

         return dict(status=0, ip=ip, mac=mac, conf='cisco_configure',
            msg = msg + infos['model'] + ', ' + infos['version'])

      elif _vendors[vendor]=='Polycom':
         return dict(status=0, ip=ip, mac=mac, conf='polycom_configure',
               msg=u"Trouvé téléphone Polycom")
Exemplo n.º 29
0
 def delete(self, id, **kw):
    ''' Delete department from DB
    '''
    log.info('delete ' + kw['_id'])
    DBSession.delete(DBSession.query(Department).get(kw['_id']))
    flash(u'Service supprimé', 'notice')
    redirect('/departments/')
Exemplo n.º 30
0
def queues_options():
   ''' Returns distinct queues from queue log
   '''
   # queue_event_id==24 => AddMember
   queues = [q[0] for q in DBSession.query(Queue_log.queue).distinct().\
         filter(Queue_log.queue_event_id==24).order_by(Queue_log.queue)]
   return check_access(queues)