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.

235 lines
11 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 partners, 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
  9. available from https://code.launchpad.net/openerp-asterisk-connector
  10. for OpenERP version >= 5.0
  11. This script is designed to be used as an AGI on an Asterisk IPBX...
  12. BUT I advise you to use a wrapper around this script to control the
  13. execution time. Why ? Because if the script takes too much time to
  14. execute or get stucks (in the XML-RPC request for example), then the
  15. incoming phone call will also get stucks and you will miss a call !
  16. The simplest solution I found is to use the "timeout" shell command to
  17. call this script, for example :
  18. # timeout 1s get_cid_name.py <OPTIONS>
  19. See my sample wrapper "get_cid_name_timeout.sh"
  20. Asterisk dialplan example :
  21. [from-extern]
  22. exten => _0141981242,1,AGI(/usr/local/bin/get_cid_name_timeout.sh)
  23. exten => _0141981242,n,Dial(SIP/10, 30)
  24. exten => _0141981242,n,Answer()
  25. exten => _0141981242,n,Voicemail(10@default,u)
  26. exten => _0141981242,n,Hangup()
  27. It's probably a good idea to create a user in OpenERP dedicated to this task.
  28. This user only needs to be part of the group "Asterisk CallerID", which has
  29. read access on the 'res.partner' object, nothing more.
  30. Note that this script can be used without OpenERP, with just the geolocalisation
  31. feature : for that, don't use option --server ; only use --geoloc
  32. """
  33. __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>"
  34. __date__ = "December 2010"
  35. __version__ = "0.3"
  36. # Copyright (C) 2010-2012 Alexis de Lattre <alexis.delattre@akretion.com>
  37. #
  38. # This program is free software: you can redistribute it and/or modify
  39. # it under the terms of the GNU Affero General Public License as
  40. # published by the Free Software Foundation, either version 3 of the
  41. # License, or (at your option) any later version.
  42. #
  43. # This program is distributed in the hope that it will be useful,
  44. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  45. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  46. # GNU Affero General Public License for more details.
  47. #
  48. # You should have received a copy of the GNU Affero General Public License
  49. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  50. import xmlrpclib
  51. import sys
  52. from optparse import OptionParser
  53. # CID Name that will be displayed if there is no match in res.partner
  54. # and no geolocalisation
  55. default_cid_name = "Not in OpenERP"
  56. # Define command line options
  57. option_server = {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string', 'help': 'DNS or IP address of the OpenERP server. Default = none (will not try to connect to OpenERP)', 'action': 'store', 'default': False}
  58. option_port = {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'help': "Port of OpenERP's XML-RPC interface. Default = 8069", 'action': 'store', 'default': 8069}
  59. 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}
  60. option_database = {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'help': "OpenERP database name. Default = 'openerp'", 'action': 'store', 'default': 'openerp'}
  61. 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}
  62. option_password = {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'help': "Password of the OpenERP user. Default = 'demo'", 'action': 'store', 'default': 'demo'}
  63. 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}
  64. option_geoloc = {'names': ('-g', '--geoloc'), 'dest': 'geoloc', 'help': "Try to geolocate phone numbers unknown to OpenERP. This features requires the 'phonenumbers' Python lib. To install it, run 'sudo pip install phonenumbers' Default = no", 'action': 'store_true', 'default': False}
  65. option_geoloc_lang = {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'help': "Language in which the name of the country and city name will be displayed by the geolocalisation database. Use the 2 letters ISO code of the language. Default = 'en'", 'action': 'store', 'default': "en"}
  66. option_geoloc_country = {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'help': "2 letters ISO code for your country e.g. 'FR' for France. This will be used by the geolocalisation system to parse the phone number of the calling party. Default = 'FR'", 'action': 'store', 'default': "FR"}
  67. options = [option_server, option_port, option_ssl, option_database, option_user, option_password, option_ascii, option_geoloc, option_geoloc_lang, option_geoloc_country]
  68. def stdout_write(string):
  69. '''Wrapper on sys.stdout.write'''
  70. sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  71. sys.stdout.flush()
  72. # When we output a command, we get an answer "200 result=1" on stdin
  73. # Purge stdin to avoid these Asterisk error messages :
  74. # utils.c ast_carefulwrite: write() returned error: Broken pipe
  75. input_line = sys.stdin.readline()
  76. return True
  77. def stderr_write(string):
  78. '''Wrapper on sys.stderr.write'''
  79. sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  80. sys.stdout.flush()
  81. return True
  82. def geolocate_phone_number(number, my_country_code, lang):
  83. import phonenumbers
  84. import phonenumbers.geocoder
  85. res = ''
  86. phonenum = phonenumbers.parse(number, my_country_code.upper())
  87. city = phonenumbers.area_description_for_number(phonenum, lang.lower())
  88. #country = phonenumbers.country_name_for_number(phonenum, lang.lower())
  89. country_code = phonenumbers.region_code_for_number(phonenum)
  90. if country_code == my_country_code.upper():
  91. # We don't display the country name when it's my own country
  92. if city:
  93. res = city
  94. else:
  95. # Convert country code to country name
  96. country = phonenumbers.geocoder._region_display_name(country_code, lang.lower())
  97. if country and city:
  98. res = country + ' ' + city
  99. elif country and not city:
  100. res = country
  101. return res
  102. def convert_to_ascii(my_unicode):
  103. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  104. import unicodedata
  105. if isinstance(my_unicode, unicode):
  106. my_unicode_with_ascii_chars_only = ''.join((char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn'))
  107. return str(my_unicode_with_ascii_chars_only)
  108. # If the argument is already of string type, we return it with the same value
  109. elif isinstance(my_unicode, str):
  110. return my_unicode
  111. else:
  112. return False
  113. def main(options, arguments):
  114. #print 'options = %s' % options
  115. #print 'arguments = %s' % arguments
  116. # AGI passes parameters to the script on standard input
  117. stdinput = {}
  118. while 1:
  119. input_line = sys.stdin.readline()
  120. if not input_line:
  121. break
  122. line = input_line.strip()
  123. try:
  124. variable, value = line.split(':')
  125. except:
  126. break
  127. if variable[:4] != 'agi_': # All AGI parameters start with 'agi_'
  128. stderr_write("bad stdin variable : %s\n" % variable)
  129. continue
  130. variable = variable.strip()
  131. value = value.strip()
  132. if variable and value:
  133. stdinput[variable] = value
  134. stderr_write("full AGI environnement :\n")
  135. for variable in stdinput.keys():
  136. stderr_write("%s = %s\n" % (variable, stdinput.get(variable)))
  137. # If we already have a "True" caller ID name
  138. # i.e. not just digits, but a real name, then we don't try to
  139. # connect to OpenERP or geoloc, we just keep it
  140. if stdinput.get('agi_calleridname') and not stdinput.get('agi_calleridname').isdigit() and stdinput.get('agi_calleridname').lower() not in ['asterisk', 'unknown', 'anonymous']:
  141. stdout_write('VERBOSE "Incoming CallerID name is %s"\n' % stdinput.get('agi_calleridname'))
  142. stdout_write('VERBOSE "As it is a real name, we do not change it"\n')
  143. return True
  144. input_cid_number = stdinput.get('agi_callerid')
  145. stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8')
  146. if not isinstance(input_cid_number, str):
  147. stdout_write('VERBOSE "CallerID number is empty"\n')
  148. exit(0)
  149. # Match for particular cases and anonymous phone calls
  150. # To test anonymous call in France, dial 3651 + number
  151. if not input_cid_number.isdigit():
  152. stdout_write('VERBOSE "CallerID number (%s) is not a digit"\n' % input_cid_number)
  153. exit(0)
  154. stdout_write('VERBOSE "CallerID number = %s"\n' % input_cid_number)
  155. res = False
  156. if options.server: # Yes, this script can be used without "-s openerp_server" !
  157. if options.ssl:
  158. stdout_write('VERBOSE "Starting XML-RPC secure request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  159. protocol = 'https'
  160. else:
  161. stdout_write('VERBOSE "Starting clear XML-RPC request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  162. protocol = 'http'
  163. sock = xmlrpclib.ServerProxy('%s://%s:%s/xmlrpc/object' % (protocol, options.server, str(options.port)))
  164. try:
  165. res = sock.execute(options.database, options.user, options.password, 'res.partner', 'get_name_from_phone_number', input_cid_number)
  166. stdout_write('VERBOSE "End of XML-RPC request on OpenERP"\n')
  167. if not res:
  168. stdout_write('VERBOSE "Phone number not found in OpenERP"\n')
  169. except:
  170. stdout_write('VERBOSE "Could not connect to OpenERP"\n')
  171. res = False
  172. # To simulate a long execution of the XML-RPC request
  173. #import time
  174. #time.sleep(5)
  175. # Function to limit the size of the CID name to 40 chars
  176. if res:
  177. if len(res) > 40:
  178. res = res[0:40]
  179. elif options.geoloc:
  180. # if the number is not found in OpenERP, we try to geolocate
  181. stdout_write('VERBOSE "Trying to geolocate with country %s and lang %s"\n' % (options.country, options.lang))
  182. res = geolocate_phone_number(input_cid_number, options.country, options.lang)
  183. else:
  184. # if the number is not found in OpenERP and geoloc is off, we put 'default_cid_name' as CID Name
  185. res = default_cid_name
  186. # All SIP phones should support UTF-8... but in case you have analog phones over TDM
  187. # or buggy phones, you should use the command line option --ascii
  188. if options.ascii:
  189. res = convert_to_ascii(res)
  190. stdout_write('VERBOSE "CallerID Name = %s"\n' % res)
  191. stdout_write('SET CALLERID "%s"<%s>\n' % (res, input_cid_number))
  192. return True
  193. if __name__ == '__main__':
  194. parser = OptionParser()
  195. for option in options:
  196. param = option['names']
  197. del option['names']
  198. parser.add_option(*param, **option)
  199. options, arguments = parser.parse_args()
  200. sys.argv[:] = arguments
  201. main(options, arguments)