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.

196 lines
8.4 KiB

13 years ago
  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-2012 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_ssl = {'names': ('-e', '--ssl'), 'dest': 'ssl', 'help': "Use XML-RPC secure i.e. with SSL instead of clear XML-RPC. Default = no, use clear XML-RPC.", 'action': 'store_true', 'default': False}
  56. option_database = {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'help': "OpenERP database name. Default = openerp", 'action': 'store', 'default': 'openerp'}
  57. 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}
  58. option_password = {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'help': "Password of the OpenERP user. Default = demo", 'action': 'store', 'default': 'demo'}
  59. 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}
  60. options = [option_server, option_port, option_ssl, option_database, option_user, option_password, option_ascii]
  61. def stdout_write(string):
  62. '''Wrapper on sys.stdout.write'''
  63. sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  64. sys.stdout.flush()
  65. # When we output a command, we get an answer "200 result=1" on stdin
  66. # Purge stdin to avoid these Asterisk error messages :
  67. # utils.c ast_carefulwrite: write() returned error: Broken pipe
  68. input_line = sys.stdin.readline()
  69. return True
  70. def stderr_write(string):
  71. '''Wrapper on sys.stderr.write'''
  72. sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  73. sys.stdout.flush()
  74. return True
  75. def reformat_phone_number_before_query_openerp(number):
  76. '''We match only on the end of the phone number'''
  77. if len(number) >= 9:
  78. return number[-9:len(number)] # Take 9 last numbers
  79. else:
  80. return number
  81. def convert_to_ascii(my_unicode):
  82. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  83. import unicodedata
  84. if isinstance(my_unicode, unicode):
  85. my_unicode_with_ascii_chars_only = ''.join((char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn'))
  86. return str(my_unicode_with_ascii_chars_only)
  87. # If the argument is already of string type, we return it with the same value
  88. elif isinstance(my_unicode, str):
  89. return my_unicode
  90. else:
  91. return False
  92. def main(options, arguments):
  93. #print 'options = %s' % options
  94. #print 'arguments = %s' % arguments
  95. # AGI passes parameters to the script on standard input
  96. stdinput = {}
  97. while 1:
  98. input_line = sys.stdin.readline()
  99. if not input_line:
  100. break
  101. line = input_line.strip()
  102. try:
  103. variable, value = line.split(':')
  104. except:
  105. break
  106. if variable[:4] != 'agi_': # All AGI parameters start with 'agi_'
  107. stderr_write("bad stdin variable : %s\n" % variable)
  108. continue
  109. variable = variable.strip()
  110. value = value.strip()
  111. if variable and value:
  112. stdinput[variable] = value
  113. stderr_write("full AGI environnement :\n")
  114. for variable in stdinput.keys():
  115. stderr_write("%s = %s\n" % (variable, stdinput.get(variable)))
  116. input_cid_number = stdinput.get('agi_callerid')
  117. stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8')
  118. if not isinstance(input_cid_number, str):
  119. stdout_write('VERBOSE "CallerID number is empty"\n')
  120. exit(0)
  121. # Match for particular cases and anonymous phone calls
  122. # To test anonymous call in France, dial 3651 + number
  123. if not input_cid_number.isdigit():
  124. stdout_write('VERBOSE "CallerID number (%s) is not a digit"\n' % input_cid_number)
  125. exit(0)
  126. stdout_write('VERBOSE "CallerID number = %s"\n' % input_cid_number)
  127. query_number = reformat_phone_number_before_query_openerp(input_cid_number)
  128. stderr_write("phone number sent to OpenERP = %s\n" % query_number)
  129. if options.ssl:
  130. stdout_write('VERBOSE "Starting XML-RPC secure request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  131. protocol = 'https'
  132. else:
  133. stdout_write('VERBOSE "Starting clear XML-RPC request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  134. protocol = 'http'
  135. sock = xmlrpclib.ServerProxy('%s://%s:%s/xmlrpc/object' % (protocol, options.server, str(options.port)))
  136. res = sock.execute(options.database, options.user, options.password, 'res.partner.address', 'get_name_from_phone_number', query_number)
  137. # To simulate a long execution of the XML-RPC request
  138. #import time
  139. #time.sleep(5)
  140. stdout_write('VERBOSE "End of XML-RPC request on OpenERP"\n')
  141. # Function to limit the size of the CID name to 40 chars
  142. if res:
  143. if len(res) > 40:
  144. res = res[0:40]
  145. else:
  146. # if the number is not found in OpenERP, we put 'default_cid_name' as CID Name
  147. res = default_cid_name
  148. # All SIP phones should support UTF-8... but in case you have analog phones over TDM
  149. # or buggy phones, you should use the command line option --ascii
  150. if options.ascii:
  151. res = convert_to_ascii(res)
  152. stdout_write('VERBOSE "CallerID Name = %s"\n' % res)
  153. stdout_write('SET CALLERID "%s"<%s>\n' % (res, input_cid_number))
  154. return True
  155. if __name__ == '__main__':
  156. parser = OptionParser()
  157. for option in options:
  158. param = option['names']
  159. del option['names']
  160. parser.add_option(*param, **option)
  161. options, arguments = parser.parse_args()
  162. sys.argv[:] = arguments
  163. main(options, arguments)