#!/usr/bin/python

import os
import pwd
import sys
import string
import smtplib
import socket
import time
import select
import regex
import StringIO
import base64

# config
voiceboxdir = '/var/spool/voicebox/'
datadir = '/usr/local/lib/voicebox/'
cmdpath = '/usr/local/lib/iakic/iakic-cmd'
dtmfpath = '/usr/local/lib/iakic/iakic-dtmf'
lockfile = '/usr/local/lib/iakic/lock'
lockpointfile = '/usr/local/sbin/voicebox'
helpfile = datadir+'help'
adminmail = 'root'
logfile = '/var/log/voicebox'

# how long the radio will stay tuned on one channel; it is so long because of
# the communication latency with radio and trx phase lock speed
scanSpeed           = 0.5  # sec

# how long the asterisk tone should last to stop scanning
asteriskTime        = 1.5  # sec

# how long the radio would wait for any dtmf tone between commands / logins;
# after that, radio starts scanning again
stopTime            = 10.0 # sec

# timeout of space between two dtmf tones
betweenTonesTime    = 3.0  # sec

# how long to wait for user to give a command before he is kicked out
boxCommandTime      = 20.0 # sec

# maximum length of a message
messageLength       = 150  # sec

# time space between ptt and actual sending
pttTime             = 1.0  # sec

# DTMF code which stop scaning
stopChar            = '0'

frequencies = [\
  [ "145.7125", "145.1125", "100" ], \
  [ "145.6750", "145.0750", "0"   ], \
  [ "145.7750", "145.7750", "0"   ], \
  [ "145.2000", "145.2000", "0"   ], \
  [ "145.4750", "145.4750", "0"   ] ]

spellTable = { \
  'a': 'aaa',  'b': 'bee',  'c': 'cee',  'd': 'dee',  'e': 'eee', 'f': 'ef', \
  'g': 'gee',  'h': 'haa',  'i': 'iii',  'j': 'jee',  'k': 'kaa', 'l': 'el', \
  'm': 'em',  'n': 'en',  'o': 'ooo',  'p': 'pee',  'q': 'kvee','r': 'er', \
  's': 'es',  't': 'tee',  'u': 'uuu',  'v': 'vee',  'w': 'dvojvee', 'x': 'ix', \
  'y': 'ypsilon',  'z': 'zet', \
  '1': 'jedna',  '2': 'dva',  '3': 'tri', '4': 'ctyri', '5': 'pet', \
  '6': 'sest', '7': 'sedum', '8': 'osum', '9': 'devet', '0': 'nula' }

def exitError(s):
    sys.stderr.write("voicebox: " + s)
    sys.exit(1)

def spell(co):
    res = ""
    for c in co:
        if spellTable.has_key(c):
	     res = res + spellTable[c] + " "
    return res

# constants
LOG_ERR = 3
LOG_WARNING = 4

TimeoutException = "TimeoutException"
HashException = "HashException"

#global variables

releaseTime = time.time()

code2user = {}
cmdfile = 0
dtmffile = 0

def mluvitko(text):
    os.system('echo "' + text + '" | /usr/bin/mluvitko-ok1iak >/dev/null 2>/dev/null')

###############################################################################

def log(priority,message):

    logf=open(logfile,'a')

    if (priority==LOG_WARNING): logf.write("warning: ")
    else: logf.write("error: ")

    logf.write(message+"\n")

    logf.close


###############################################################################

def iakWriteCmd(cmd):
    print "command  " + cmd
    cmdfile.write(cmd + "\n")
    cmdfile.flush();

def initializeTrx():
  iakWriteCmd('X 0')            # ptt off
  #iakWriteCmd('R 145.2500')     # receive freqency
  #iakWriteCmd('T 145.2500')     # transmit freqency
  iakWriteCmd('R 145.7125')     # receive freqency
  iakWriteCmd('T 145.1125')     # transmit freqency
  #iakWriteCmd('C 100.0')        # subtone
  iakWriteCmd('C 0')            # subtone off
  iakWriteCmd('q 0')

def iakicLock():
    try:
      os.symlink(lockpointfile, lockfile)
      return 1
    except os.error:
      return 0

def iakicUnlock():
    try:
      if os.readlink(lockfile) == lockpointfile:
        os.unlink(lockfile)
        return 1
      return 0
    except os.error:
      return 0

##############################################################################

isPttPressed = 0

def ptt(x):
  global isPttPressed, releaseTime

  if x == 'on':
    if not isPttPressed:
      time.sleep(pttTime)
      iakWriteCmd('x 1')
      isPttPressed = 1
  else:
    if isPttPressed:
      iakWriteCmd('x 0')
      isPttPressed = 0
      releaseTime = time.time()

###############################################################################

def comparestring(first,second):
 if first == second:
     return 0
 elif first < second:
     return -1
 else: return 1

###############################################################################

def getsection(sectionname,lines):

   lineNr = 0
   while (lineNr < len(lines)) and (string.strip(lines[lineNr]) != "["+sectionname+"]"):
     lineNr = lineNr + 1
   lineNr = lineNr + 1

   seclines = []
   while (lineNr < len(lines)) and (regex.search("^\[.*\]$",string.strip(lines[lineNr])) == -1):
        line = string.strip(lines[lineNr])
        lineNr = lineNr + 1
        if line == "" or (len(line) > 0 and line[0] == '#'):
           continue
        seclines[len(seclines):] = [line]

   return seclines

###############################################################################

def speakSound(sound):
      print "############# speaksound: " + sound

      ptt("on")

      try:

        slist = string.split(sound)

        a = os.listdir(datadir)
        dspopen = 0
        mluv=''

        for x in slist:
          if (x+".raw") in a:
             if dspopen:
                 audio.close()
                 dspopen =0

             if mluv != "":
                 mluvitko(mluv)
                 mluv=""

             print "audio: "+x
             snd = open(datadir + x + ".raw")

             if not dspopen:
                 audio = open("/dev/dsp", "w")
                 dspopen=1

             audio.write(snd.read(1000000))
             snd.close()

          else:
            print "mluv: "+x
            if (x[:3]=='ok1') or (x[:3]=='ok2'): x=spell(x)
            mluv = mluv + x
            log(LOG_WARNING,"cannot find sample: "+ x)

        #endfor

        if dspopen:
           audio.close()
           dspopen =0

        if mluv != "":
           mluvitko(mluv)
           mluv=""

      except IOError:
        print "mluvitko-python -- ", IOError
        log(LOG_ERR,"error opening file when speaking" + sound)

#      mluvitko(sound)
      print "konec mluvitka"
      ptt("off")

###############################################################################

def readDTMF(timeoutIn = 0):
  global releaseTime

  nowtime = time.time()
  timeout = nowtime + timeoutIn

  if timeoutIn < 0:
    raise TimeoutException, "readDTMF(<0)"

  while 1:
    (ready, dummy1, dummy2) = select.select([dtmffile.fileno()], [], [], timeout - nowtime)
    if len(ready) > 0:
      line = dtmffile.readline()
      if line[0:4] == 'DTMF':
        if line[5] == '-':
	  releaseTime = time.time()
        else:
	  data = line[5]
	  break
    else:
      raise TimeoutException, "readDTMF"

  while 1:
    line = dtmffile.readline()
    if line == "DTMF -\n":
      break

  releaseTime = time.time()

  print "DTMF: " + data
  return data

###############################################################################

def recMessage(Msg):
  print "################# recmsg"
  try:
    f = open(Msg, 'w')
    data = " "
    nowtime = time.time()
    timeout = nowtime + messageLength
    iakWriteCmd('q 1') # close squelch
    end = 0
    while not end and timeout > nowtime:
        # wait for signal
        while 1:
            (ready, dummy1, dummy2) = select.select([dtmffile.fileno()], [], [], timeout - nowtime)
            if len(ready) > 0:
                line = dtmffile.readline()
                if line == 'SIG 1\n':
                    break
            else:
	        end = 1
                break
	if end:
	  break
        faud = open('/dev/dsp','r')
        while timeout > nowtime:
	    f.write(faud.read(1024))
            (ready, dummy1, dummy2) = select.select([dtmffile.fileno()], [], [], 0)
	    nowtime = time.time()
            if len(ready) > 0:
                line = dtmffile.readline()
                if line == 'SIG 0\n':
                    print "Konec signalu"
                    break
                if line == "DTMF #\n" or nowtime > timeout:
                    end = 1
                    break
        faud.close()
    f.close()
    iakWriteCmd('q 0') # open squelch
    speakSound("zprava_byla_ulozena.")

  except IOError:
    log(LOG_ERR,"IOError when recording message, msg: " + Msg)
    if os.path.exists(Msg): os.remove(Msg)

###############################################################################

def playMessage(Msg):
  print "################ playmsg " + Msg
  try:
    ptt("on")
    f = open(Msg,'r')
    faud = open('/dev/dsp','w')
    faud.write(f.read());
    f.close()
    faud.close()
    speakSound('konec')
  except IOError:
    log(LOG_ERR,"IOError when playing message, msg: " + msg)

###############################################################################


def readCommand(prev = ' '):
  print "################### readcommand"
  data = prev

  while 1:
    cmd = ""

    while data != '#':
      data = readDTMF(stopTime - (time.time() - releaseTime))

    try:
      for i in range(0, 3):
        data = readDTMF(betweenTonesTime)
        if ord(data) < ord('0') or ord(data) > ord('9'):
	   break
        cmd = cmd + data
    except TimeoutException:
      data = ""

    if len(cmd) == 3:
      return cmd

###############################################################################

def read2numbers():
# vraci * kdyz se zada neco jinyho nez dve cisla

  print "###################### read2numbers"
  cmd = ""
  for i in range(0, 2):
    data = readDTMF(betweenTonesTime)
    if ord(data) < ord('0') or ord(data) > ord('9'):
      if data == '#':
        raise HashException
      else:
        return "*"
    cmd = cmd + data
  return cmd

###############################################################################

def loadGlobalConfig():
  global voiceboxdir,datadir,cmdpath,dtmfpath,lockfile,helpfile,adminmail


  cfg = open("/etc/voicebox", "r")
  lines = cfg.readlines()
  cfg.close()

  users = getsection('users',lines)

  for lineNr in range(0, len(users)):
    line = string.strip(users[lineNr])
    try:
      (code, user) = string.split(line)
      user = string.lower(user)
      code2user[code] = user
      try:
        os.mkdir(voiceboxdir + "/" + user)
      except os.error:
        1
    except ValueError:
      exitError("/etc/voicebox: error at this line: " + line + "\n")

  config = getsection('config',lines)

  for lineNr in range(0, len(config)):
    line = string.strip(config[lineNr])

    try:
        (key, value) = string.split(line,'=', 1)
        key = string.strip(key)
        value = string.strip(value)

	if key=='voiceboxdir': voiceboxdir = value+'/'
	elif key=='datadir': datadir = value+'/'
	elif key=='cmdpath': cmdpath = value
	elif key=='dtmfpath': dtmfpath = value
	elif key=='lockfile': lockfile = value
	elif key=='helpfile': helpfile = value
	elif key=='adminmail': adminmail = value
	elif key=='log': logfile = value

    except (KeyError,ValueError):
      exitError("/etc/voicebox: error at this line: " + line + "\n")



###############################################################################

def getHOME(user):
  home = ""
  try:
    (x, x, x, x, x, home, x) = pwd.getpwnam(user)
  except KeyError:
    log(LOG_WARNING,"user " + user + " does not exist\n")
  return home

###############################################################################

def popMsg(user,msg):
 print "################ popmsg user: " + user + ", msg: " + msg
 try:
     dir=voiceboxdir+user
     msgs=os.listdir(dir)
     msgs.sort(comparestring)
     if len(msgs) == 0:
        speakSound('nemas_zadne_zpravy')
     else:
	if msg=="All":
	    for i in range(0,len(msgs)):
		playMessage(dir+'/'+msgs[i])
	else:
	    playMessage(dir+'/'+msgs[string.atoi(msg,10)-1])
 except os.error:
    log(LOG_WARNING,'user ' + user + 'does not exist\n')
 except (KeyError, IndexError):
     #log(LOG_WARNING,'user: ' + user + ' msg: '+msg+' does not exist\n')
     speakSound('takovou_zpravu_nemas_ve_schrance')


###############################################################################

def deleteMsg(user,msg):
 print "################ deletemsg"
 try:
     dir=voiceboxdir+user
     msgs=os.listdir(dir)
     msgs.sort(comparestring)
     if len(msgs) != 0:
	if msg=="All":
	    for i in range(0,len(msgs)):
		os.remove(dir+'/'+msgs[i])
            speakSound('vsechny_zpravy_smazany')
        else:
	    os.remove(dir+'/'+msgs[string.atoi(msg,10)-1])
            speakSound('zprava_cislo '+`string.atoi(msg,10)`+' smazana')
	    msgs = os.listdir(dir)
	    if len(msgs) == 0: return
	    msgs.sort(comparestring)
	    for i in range (0,len(msgs)):
		if msgs[i] != 'msg'+string.zfill(i,3):
		    os.rename(dir+'/'+msgs[i],dir+'/'+'msg'+string.zfill(i,3))
     else:
        speakSound('nemas_zadne_zpravy')
 except os.error:
     log(LOG_WARNING,'user: ' + user + ' does not exist\n')
 except (KeyError, IndexError):
     #log(LOG_WARNING,'user: ' + user + ' msg: '+msg+' does not exist\n')
     speakSound('takovou_zpravu_nemas_ve_schrance')

 except (ValueError):
     log(LOG_ERR,'invalid file name in directory: '+ dir +'\n')


###############################################################################

def pushMsg(user,fromUser):
 print "####################### pushmsg"
 try:
     dir=voiceboxdir+user
     msgs=os.listdir(dir)

     msgname='msg000'

     if len(msgs) != 0:
	 for i in range(0,len(msgs)):
    	     if string.atoi(msgs[i][3:],10) >= string.atoi(msgname[3:],10):
        	 msgname='msg'+string.zfill(string.atoi(msgs[i][3:],10)+1,3)

     speakSound('zanech_zpravu_pro ' + user)

     recMessage(dir+'/'+msgname)

     s=''
     if fromUser != 'somebody': s = ' od ' + fromUser

     home = getHOME(user)

     Config = {}
     Config['notify'] = '0'
     Config['sendfile'] = '0'
     Config['email'] = ''
     Config['storemsg'] = '1'

     try:
       userFile = open(home + "/.voicebox", "r")
       lines = userFile.readlines()
       userFile.close()

       lineNr = 0
       while (lineNr < len(lines)) and (string.strip(lines[lineNr]) != "[voicebox]"):
         lineNr = lineNr + 1
       lineNr = lineNr + 1

       while (lineNr < len(lines)) and (regex.search("^\[.*\]$",string.strip(lines[lineNr])) == -1):
        line = string.strip(lines[lineNr])
        lineNr = lineNr + 1
        if line == "" or (len(line) > 0 and line[0] == '#'):
           continue
        try:
           (key, value) = string.split(line,'=', 1)
	   key = string.strip(key)
	   value = string.strip(value)

	   Config[key]=value
        except (KeyError,ValueError):
            log(LOG_WARNING,home + "/.voicebox: error at line " + `lineNr` + "\n")

     except IOError:
         log(LOG_WARNING,"Error when processing with " + home + "/.voicebox")

     if ((Config['notify'] == '1') or (Config['sendfile'] == '1')) and (regex.search("^[^@]+@[^.]+\..+$",Config['email']) == -1):
       log(LOG_WARNING,'bad format of email adress in ' + home + '/.voicebox')
     else:
    	if Config['notify'] == '1': executeSendMail(fromUser,Config['email'],'Mas zpravu ve voiceboxu' + s,'')
	if Config['sendfile'] == '1':
	    try:

                now = time.localtime(time.time())
                filename = fromUser+"_"+time.strftime("%y%m%d_%H%M.wav",now)

		os.system('sox -t raw -r 8000 -b -u '+dir+'/'+msgname+' '+dir+'/'+filename)
                os.system('zip -jq '+dir+'/tmp.zip '+dir+'/'+filename)

    		msgfile = open(dir+'/tmp.zip','r')
		executeSendMimeMail(fromUser,Config['email'],msgfile)
		msgfile.close()

		os.remove(dir+'/tmp.zip')
		os.remove(dir+'/'+filename)

		if not Config['storemsg']: os.remove(dir+'/'+msgname)
	    except IOError:
                log(LOG_ERR,'error when sending or removing '+dir+'/'+msgname)

 except (os.error, KeyError):
     log(LOG_WARNING,'user ' + user + 'does not exist\n')
     speakSound('takovy_uzivatel_neni_registrovan')

 except (ValueError):
     log(LOG_ERR,'invalid file name in directory: '+ dir +'\n')


###############################################################################

def voicebox(user):
  print "##################### voicebox"
  try:
    countmsg = len(os.listdir(voiceboxdir + user))

    if countmsg >= 5: s = ' ve_schrance_mas ' + `countmsg` + ' zprav'
    elif countmsg >= 2: s = ' ve_schrance_mas ' + `countmsg` + ' zpravy'
    elif countmsg == 1: s = ' ve_schrance_mas_jednu_zpravu'
    else: s = ' ve_schrance_nemas_vubec_zadnou_zpravu'

    speakSound('vitej ' + user + s)

    while 1:
      cmd = readDTMF(boxCommandTime)
      try:
        if cmd == '0':
          ###### HELPvoicebox
          os.system("cat " + helpfile + " | /usr/bin/mluvitko-ok1iak >/dev/tty12 2>/dev/tty12")
        elif cmd == '1':
          ###### readAllMsgs
          popMsg(user, "All")
        elif cmd == '2':
          ###### readXXMsg
          msg = read2numbers()
          if msg == '*':
            speakSound('chybne_zadani')
          else:
            popMsg(user, msg)
        elif cmd == '3':
  	  ###### deleteAllMsgs
    	  deleteMsg(user, "All")
        elif cmd == '4':
          ###### deleteXXMsgs
          msg = read2numbers()
          if msg == '*':
            speakSound('chybne_zadani')
          else:
            deleteMsg(user, msg)
        elif cmd == '5':
          ###### pushmsg for XX
          usr = read2numbers()
          try:
            if usr == "*":
              raise KeyError
            else:
              pushMsg(code2user[usr], user)
          except KeyError:
            speakSound ("neznamy_uzivatel")
            log(LOG_WARNING,' user ' + usr + ' does not exist\n')
        elif cmd == '6':
          ###### sendMail for XX
          msg = read2numbers()
          if msg == "*":
            speakSound('chybne_zadani')
          else:
	    sendMail(user, msg)
        elif cmd == '#':
          # end
          raise HashException
        else:
          # error
          pass
      except TimeoutException:
        pass
  except TimeoutException:
    speakSound('sedm_tri')
  except HashException:
    speakSound('sedm_tri')
  except os.error:
    log(LOG_WARNING,'user ' + user + ' does not exist\n')

###############################################################################

def executeSendMail(user, address, subject, text):
#  log(0,"Posilam od uzivatele " + user + " na adresu " + address + ": " + subject + "\n" + text)
  server = smtplib.SMTP("localhost")

  if user == "somebody": user="nobody"

  headers = "Sender: "+adminmail+"\n"
  headers = headers + "Subject: "+subject+"\n"

  server.sendmail(user, (address, ), headers+"\n"+text)
  server.quit()
  return

###############################################################################

def executeSendMimeMail(user, address, file):
#  log(0,"Posilam od uzivatele " + user + " na adresu " + address + ": soubor \n")
 try:

  server = smtplib.SMTP("localhost")

  message = StringIO.StringIO()
  message.write("Sender: "+adminmail+"\n")
  message.write("To: "+address+"\n")
  message.write("Subject: Zprava z voiceboxu\n")
  message.write("MIME-Version: 1.0\n")
  message.write("Content-Type: multipart/mixed;\n")
  message.write(" boundary=Message-Boundary-12345\n")
  message.write("\n")
  message.write("This is a multi-part message in MIME format.\n")
  message.write("\n")
  message.write("--Message-Boundary-12345\n")
  message.write("Content-Type: text/plain; charset=us-ascii\n")
  message.write("Content-Transfer-Encoding: 7bit\n")
  message.write("\n")
  now = time.localtime(time.time())
  message.write("Zprava z voiceboxu " + time.strftime("%a %d.%m.%Y %H:%M",now)+"\n")
  message.write("\n")
  message.write("--Message-Boundary-12345\n")
  message.write("Content-Type: application/octet-stream\n")
  message.write("Content-Transfer-Encoding: base64\n")
  filename = user+"_"+time.strftime("%y%m%d_%H%M.zip",now)
  message.write("Content-Disposition: attachment; filename=\""+filename+"\"\n")
  message.write("\n")
  base64.encode(file,message)
  message.write("--Message-Boundary-12345--\n")
  message.flush()
  message.seek(0)

  if user == "somebody": user="nobody"

  server.sendmail(user, (address, ), message.read())
  server.quit()
 except IOError:
    log(LOG_ERR,'IO error when sending MIME message by user ' + user)
 return

###############################################################################

def sendMail(user, code):
#  print"##################### sendmail"
  home = getHOME(user)

  try:
    userFile = open(home + "/.voicebox", "r")
    lines = userFile.readlines()
    userFile.close()

    lineNr = 0
    while (lineNr < len(lines)) and (string.strip(lines[lineNr]) != "[emails]"): lineNr = lineNr + 1

    lineNr = lineNr + 1

    while (lineNr < len(lines)) and (regex.search("^\[.*\]$",string.strip(lines[lineNr])) == -1):
      line = string.strip(lines[lineNr])
      lineNr = lineNr + 1
      if line == "" or (len(line) > 0 and line[0] == '#'):
        continue
      (acode, email, subject) = string.split(line, None, 2)
      text = ""
      if len(subject) > 0 and subject[-1] == "<":
        subject = subject[0:-1]
        while lineNr < len(lines):
          line = string.rstrip(lines[lineNr])
          lineNr = lineNr + 1
          if len(line) > 0 and string.rstrip(line) == ".":
            break
          else:
            text = text + line + "\n"
      if code == acode:
        text = text + "\n odeslano systemem voicebox - viz http://www.kufr.cz/systemy/voicebox.php3 \n"
        executeSendMail(user, email, subject, text)
        speakSound("email_cislo "+ `string.atoi(code,10)` +" odeslan")

        return
    speakSound("email_cislo "+ `string.atoi(code,10)` +" neni_definovan")
  except ValueError:
    log(LOG_WARNING,home + "/.voicebox: error at line " + `lineNr` + "\n")
    speakSound("chyba_v_definici_emailu")
    return
  except IOError:
    speakSound("chyba_v_definici_emailu")
    return

###############################################################################

def telltime():
  now = time.localtime(time.time())
  if (now[3] >= 2) and (now[3] <= 4):
    a = "prave_jsou "
  else:
    a = "prave_je "
  a = a + `now[3]`
  if now[3] == 1:
    a = a + " hodina "
  elif (now[3] >= 2) and (now[3] <= 4):
    a = a + " hodiny "
  else:
    a = a + " hodin "
  a = a + `now[4]`
  if now[4] == 1:
    a = a + " minuta"
  elif (now[4] >= 2) and (now[4] <= 4):
    a = a + " minuty"
  else:
    a = a + " minut"
  speakSound(a)

###############################################################################

def scanLoop():
  freqIndex = 0
  while 1:
    while 1:
      try:
        os.readlink(lockfile)
      except os.error:
        break
      time.sleep(1) 
    freq = frequencies[freqIndex]
    iakWriteCmd("R" + freq[0])
    nowtime = time.time()
    timeout = nowtime + scanSpeed
    while (timeout > nowtime):
      (ready, dummy1, dummy2) = select.select([dtmffile.fileno()],\
                                              [], [], timeout - nowtime)
      if len(ready) > 0:
        line = dtmffile.readline()
        print "#### dtmffile.readline()", line
        if line[0:6] == "DTMF " + stopChar:
          (ready, dummy1, dummy2) = select.select([dtmffile.fileno()],\
                                                  [], [], asteriskTime)
          if len(ready) > 0:
	    dtmffile.readline()
	  else:
            rcvd = stopChar
            while rcvd != '-':
              line = dtmffile.readline()
              if line[0:4] == 'DTMF':
                rcvd = line[5]
            iakWriteCmd("T" + freq[1])
            iakWriteCmd("C" + freq[2])
            speakSound("jsem_zde")
	    return
      nowtime = time.time()
    freqIndex = (freqIndex + 1) % len(frequencies)

###############################################################################

def commandLoop():
  dtmfkey = ' '
  while 1:
    try:
      str = readCommand(dtmfkey)
      dtmfkey = ' '
      print "prijato: " + str
      if str[0:3] == "951":
        ########## DTMF mail ########
        try:
          usr = read2numbers()
          if usr == "*":
	    raise KeyError
          else:
    	    msg = read2numbers()
            if msg =='*':
	      raise KeyError
            else:
	      sendMail(code2user[usr], msg)
        except KeyError:
          speakSound("neznamy_uzivatel")
      elif str[0:3] == "789":
        ######### voicebox ##########
        try:
          usr = read2numbers()
          if usr == '*':
	    raise KeyError
          else:
	    voicebox(code2user[usr])
        except KeyError:
          speakSound("neznamy_uzivatel")
          log(LOG_WARNING,'user ' + usr + ' does not exist\n')
      elif str[0:3] == "788":
        ######## voicebox - pushmsg #########
        try:
          usr = read2numbers()
          if usr == "*":
	    raise KeyError
          else:
	    pushMsg(code2user[usr], 'somebody')
        except KeyError:
          speakSound("neznamy_uzivatel")
          log(LOG_WARNING,'user ' + usr + ' does not exist\n')
      elif str[0:3] == "222":
        telltime()
      elif str[0:3] == "700":
        ######## voicebox - usernumber to call #########
        try:
          usr = read2numbers()
	  speakSound('toto_cislo_patri_uzivateli ' + code2user[usr])
        except KeyError:
          speakSound("neznamy_uzivatel")
    except HashException:
      dtmfkey = '#'

###############################################################################

def main():
  global cmdfile, dtmffile

  loadGlobalConfig()

  try:
    cmdfile = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    cmdfile.connect(cmdpath)
    cmdfile = cmdfile.makefile("a")
  except socket.error, s:
    print s
    exitError("Cannot open unix socket " + cmdpath + "\n")

  try:
    dtmffile = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    dtmffile.connect(dtmfpath)
    dtmffile = dtmffile.makefile("r")
  except socket.error:
    exitError("Cannot open unix socket " + dtmfpath + "\n")

  try:
    os.unlink(lockfile)
  except os.error:
    pass

  initializeTrx()

  while 1:
    scanLoop()
    iakicLock()
    try:
      commandLoop()
    except TimeoutException, e:
      print "TimeoutException ", e
      pass
    iakicUnlock()

main()

