You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
7.6 KiB

  1. #! /usr/bin/python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. CallerID name lookup in OpenERP for Asterisk IPBX
  5. When executed from the dialplan on an incoming phone call, it will lookup in
  6. OpenERP's partner addresses, and, if it finds the phone number, it will get the
  7. corresponding name of the person and use this name as CallerID name for the incoming call.
  8. Requires the "asterisk_click2dial" module (available in the extra-addons)
  9. on OpenERP version >= 5
  10. This script is designed to be used as an AGI on an Asterisk IPBX...
  11. BUT I advise you to use a wrapper around this script to control the
  12. execution time. Why ? Because if the script takes too much time to
  13. execute or get stucks (in the XML-RPC request for example), then the
  14. incoming phone call will also get stucks and you will miss a call !
  15. The most simple solution I found is to use the "timeout" shell command to
  16. call this script, for example :
  17. # timeout 1s get_cid_name.py <OPTIONS>
  18. See my sample wrapper "get_cid_name_timeout.sh"
  19. Asterisk dialplan example :
  20. [from-extern]
  21. exten => _0141981242,1,AGI(/usr/local/bin/get_cid_name_timeout.sh)
  22. exten => _0141981242,n,Dial(SIP/10, 30)
  23. exten => _0141981242,n,Answer()
  24. exten => _0141981242,n,Voicemail(10@default,u)
  25. exten => _0141981242,n,Hangup()
  26. It's probably a good idea to create a user in OpenERP dedicated to this task.
  27. This user only needs to be part of the group "Asterisk CallerID", which has
  28. read access on the 'res.partner.address' object, nothing more.
  29. """
  30. __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>"
  31. __date__ = "December 2010"
  32. __version__ = "0.1"
  33. # Copyright (C) 2010 Alexis de Lattre <alexis.delattre@akretion.com>
  34. #
  35. # This program is free software: you can redistribute it and/or modify
  36. # it under the terms of the GNU Affero General Public License as
  37. # published by the Free Software Foundation, either version 3 of the
  38. # License, or (at your option) any later version.
  39. #
  40. # This program is distributed in the hope that it will be useful,
  41. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  42. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  43. # GNU Affero General Public License for more details.
  44. #
  45. # You should have received a copy of the GNU Affero General Public License
  46. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  47. import xmlrpclib
  48. import sys
  49. from optparse import OptionParser
  50. # CID Name that will be displayed if there is no match in res.partner.address
  51. default_cid_name = "Not in OpenERP"
  52. # Define command line options
  53. option_server = {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string', 'help': 'DNS or IP address of the OpenERP server. Default = localhost', 'action': 'store', 'default':'localhost'}
  54. option_port = {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'help': "Port of OpenERP's XML-RPC interface. Default = 8069", 'action': 'store', 'default': 8069}
  55. option_database = {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'help': "OpenERP database name. Default = openerp", 'action': 'store', 'default': 'openerp'}
  56. option_user = {'names': ('-u', '--user-id'), 'dest': 'user', 'type': 'int', 'help': "OpenERP user ID to use when connecting to OpenERP. Default = 2", 'action': 'store', 'default': 2}
  57. option_password = {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'help': "Password of the OpenERP user. Default = demo", 'action': 'store', 'default': 'demo'}
  58. option_ascii = {'names': ('-a', '--ascii'), 'dest': 'ascii', 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8", 'action': 'store_true', 'default': False}
  59. options = [option_server, option_port, option_database, option_user, option_password, option_ascii]
  60. def stdout_write(string):
  61. '''Wrapper on sys.stdout.write'''
  62. sys.stdout.write(string.encode(sys.stdout.encoding, 'replace'))
  63. sys.stdout.flush()
  64. def stderr_write(string):
  65. '''Wrapper on sys.stderr.write'''
  66. sys.stderr.write(string.encode(sys.stdout.encoding, 'replace'))
  67. sys.stdout.flush()
  68. def reformat_phone_number_before_query_openerp(number):
  69. '''We match only on the end of the phone number'''
  70. if len(number) >= 9:
  71. return number[-9:len(number)] # Take 9 last numbers
  72. else:
  73. return number
  74. def convert_to_ascii(my_unicode):
  75. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  76. import unicodedata
  77. if isinstance(my_unicode, unicode):
  78. my_unicode_with_ascii_chars_only = ''.join((char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn'))
  79. return str(my_unicode_with_ascii_chars_only)
  80. # If the argument is already of string type, we return it with the same value
  81. elif isinstance(my_unicode, str):
  82. return my_unicode
  83. else:
  84. return False
  85. def main(options, arguments):
  86. #print 'options = %s' % options
  87. #print 'arguments = %s' % arguments
  88. # AGI passes parameters to the script on standard input
  89. stdinput = {}
  90. while 1:
  91. input_line = sys.stdin.readline().strip()
  92. if input_line == '':
  93. break
  94. variable, value = input_line.split(':') # TODO à protéger !
  95. if variable[:4] != 'agi_': # All AGI parameters start with 'agi_'
  96. stderr_write("bad stdin variable : %s\n" % variable)
  97. continue
  98. variable = variable.strip()
  99. value = value.strip()
  100. if variable != '':
  101. stdinput[variable] = value
  102. stderr_write("full AGI environnement :\n")
  103. for variable in stdinput.keys():
  104. stderr_write("%s = %s\n" % (variable, stdinput[variable]))
  105. input_cid_number = stdinput.get('agi_callerid', False)
  106. stderr_write('stdout encoding = %s\n' % sys.stdout.encoding)
  107. if not isinstance(input_cid_number, str):
  108. exit(0)
  109. # Match for particular cases and anonymous phone calls
  110. # To test anonymous call in France, dial 3651 + number
  111. if not input_cid_number.isdigit():
  112. stdout_write('VERBOSE "CallerID number (%s) is not a digit"\n' % input_cid_number)
  113. exit(0)
  114. stdout_write('VERBOSE "CallerID number = %s"\n' % input_cid_number)
  115. query_number = reformat_phone_number_before_query_openerp(input_cid_number)
  116. stderr_write("phone number sent to OpenERP = %s\n" % query_number)
  117. stdout_write('VERBOSE "Starting XML-RPC request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  118. sock = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/object' % (options.server, str(options.port)))
  119. res = sock.execute(options.database, options.user, options.password, 'res.partner.address', 'get_name_from_phone_number', query_number)
  120. # To simulate a long execution of the XML-RPC request
  121. #import time
  122. #time.sleep(5)
  123. stdout_write('VERBOSE "End of XML-RPC request on OpenERP"\n')
  124. # Function to limit the size of the CID name to 40 chars
  125. if res:
  126. if len(res) > 40:
  127. res = res[0:40]
  128. else:
  129. # if the number is not found in OpenERP, we put 'default_cid_name' as CID Name
  130. res = default_cid_name
  131. # All SIP phones should support UTF-8... but in case you have analog phones over TDM
  132. # or buggy phones, you should use the command line option --ascii
  133. if options.ascii:
  134. res = convert_to_ascii(res)
  135. stdout_write('VERBOSE "CallerID Name = %s"\n' % res)
  136. stdout_write('SET CALLERID "%s"<%s>\n' % (res, input_cid_number))
  137. if __name__ == '__main__':
  138. parser = OptionParser()
  139. for option in options:
  140. param = option['names']
  141. del option['names']
  142. parser.add_option(*param, **option)
  143. options, arguments = parser.parse_args()
  144. sys.argv[:] = arguments
  145. main(options, arguments)