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.

252 lines
12 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. options = [
  58. {'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},
  59. {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'help': "Port of OpenERP's XML-RPC interface. Default = 8069", 'action': 'store', 'default': 8069},
  60. {'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},
  61. {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'help': "OpenERP database name. Default = 'openerp'", 'action': 'store', 'default': 'openerp'},
  62. {'names': ('-u', '--user-id'), 'dest': 'user', 'type': 'int', 'help': "OpenERP user ID to use when connecting to OpenERP. Default = 2", 'action': 'store', 'default': 2},
  63. {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'help': "Password of the OpenERP user. Default = 'demo'", 'action': 'store', 'default': 'demo'},
  64. {'names': ('-a', '--ascii'), 'dest': 'ascii', 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8", 'action': 'store_true', 'default': False},
  65. {'names': ('-n', '--notify'), 'dest': 'notify', 'help': "Notify OpenERP users via a pop-up (requires the OpenERP module 'asterisk_popup'). If you use this option, you must pass the logins of the OpenERP users to notify as argument to the script. Default = no", 'action': 'store_true', 'default': False},
  66. {'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},
  67. {'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"},
  68. {'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"},
  69. ]
  70. def stdout_write(string):
  71. '''Wrapper on sys.stdout.write'''
  72. sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  73. sys.stdout.flush()
  74. # When we output a command, we get an answer "200 result=1" on stdin
  75. # Purge stdin to avoid these Asterisk error messages :
  76. # utils.c ast_carefulwrite: write() returned error: Broken pipe
  77. input_line = sys.stdin.readline()
  78. return True
  79. def stderr_write(string):
  80. '''Wrapper on sys.stderr.write'''
  81. sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  82. sys.stdout.flush()
  83. return True
  84. def geolocate_phone_number(number, my_country_code, lang):
  85. import phonenumbers
  86. import phonenumbers.geocoder
  87. res = ''
  88. phonenum = phonenumbers.parse(number, my_country_code.upper())
  89. city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower())
  90. #country = phonenumbers.country_name_for_number(phonenum, lang.lower())
  91. country_code = phonenumbers.region_code_for_number(phonenum)
  92. if country_code == my_country_code.upper():
  93. # We don't display the country name when it's my own country
  94. if city:
  95. res = city
  96. else:
  97. # Convert country code to country name
  98. country = phonenumbers.geocoder._region_display_name(country_code, lang.lower())
  99. if country and city:
  100. res = country + ' ' + city
  101. elif country and not city:
  102. res = country
  103. return res
  104. def convert_to_ascii(my_unicode):
  105. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  106. import unicodedata
  107. if isinstance(my_unicode, unicode):
  108. my_unicode_with_ascii_chars_only = ''.join((char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn'))
  109. return str(my_unicode_with_ascii_chars_only)
  110. # If the argument is already of string type, we return it with the same value
  111. elif isinstance(my_unicode, str):
  112. return my_unicode
  113. else:
  114. return False
  115. def main(options, arguments):
  116. #print 'options = %s' % options
  117. #print 'arguments = %s' % arguments
  118. # AGI passes parameters to the script on standard input
  119. stdinput = {}
  120. while 1:
  121. input_line = sys.stdin.readline()
  122. if not input_line:
  123. break
  124. line = input_line.strip()
  125. try:
  126. variable, value = line.split(':')
  127. except:
  128. break
  129. if variable[:4] != 'agi_': # All AGI parameters start with 'agi_'
  130. stderr_write("bad stdin variable : %s\n" % variable)
  131. continue
  132. variable = variable.strip()
  133. value = value.strip()
  134. if variable and value:
  135. stdinput[variable] = value
  136. stderr_write("full AGI environnement :\n")
  137. for variable in stdinput.keys():
  138. stderr_write("%s = %s\n" % (variable, stdinput.get(variable)))
  139. # If we already have a "True" caller ID name
  140. # i.e. not just digits, but a real name, then we don't try to
  141. # connect to OpenERP or geoloc, we just keep it
  142. if stdinput.get('agi_calleridname') and not stdinput.get('agi_calleridname').isdigit() and stdinput.get('agi_calleridname').lower() not in ['asterisk', 'unknown', 'anonymous']:
  143. stdout_write('VERBOSE "Incoming CallerID name is %s"\n' % stdinput.get('agi_calleridname'))
  144. stdout_write('VERBOSE "As it is a real name, we do not change it"\n')
  145. return True
  146. input_cid_number = stdinput.get('agi_callerid')
  147. stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8')
  148. if not isinstance(input_cid_number, str):
  149. stdout_write('VERBOSE "CallerID number is empty"\n')
  150. exit(0)
  151. # Match for particular cases and anonymous phone calls
  152. # To test anonymous call in France, dial 3651 + number
  153. if not input_cid_number.isdigit():
  154. stdout_write('VERBOSE "CallerID number (%s) is not a digit"\n' % input_cid_number)
  155. exit(0)
  156. stdout_write('VERBOSE "CallerID number = %s"\n' % input_cid_number)
  157. res = False
  158. if options.server: # Yes, this script can be used without "-s openerp_server" !
  159. if options.ssl:
  160. stdout_write('VERBOSE "Starting XML-RPC secure request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  161. protocol = 'https'
  162. else:
  163. stdout_write('VERBOSE "Starting clear XML-RPC request on OpenERP %s:%s"\n' % (options.server, str(options.port)))
  164. protocol = 'http'
  165. sock = xmlrpclib.ServerProxy(
  166. '%s://%s:%s/xmlrpc/object'
  167. % (protocol, options.server, str(options.port)))
  168. try:
  169. if options.notify and arguments:
  170. res = sock.execute(
  171. options.database, options.user, options.password,
  172. 'res.partner', 'incall_notify_by_login',
  173. input_cid_number, arguments)
  174. stdout_write('VERBOSE "Calling incall_notify_by_login"\n')
  175. else:
  176. res = sock.execute(
  177. options.database, options.user, options.password,
  178. 'res.partner', 'get_name_from_phone_number',
  179. input_cid_number)
  180. stdout_write('VERBOSE "Calling get_name_from_phone_number"\n')
  181. stdout_write('VERBOSE "End of XML-RPC request on OpenERP"\n')
  182. if not res:
  183. stdout_write('VERBOSE "Phone number not found in OpenERP"\n')
  184. except:
  185. stdout_write('VERBOSE "Could not connect to OpenERP"\n')
  186. res = False
  187. # To simulate a long execution of the XML-RPC request
  188. #import time
  189. #time.sleep(5)
  190. # Function to limit the size of the CID name to 40 chars
  191. if res:
  192. if len(res) > 40:
  193. res = res[0:40]
  194. elif options.geoloc:
  195. # if the number is not found in OpenERP, we try to geolocate
  196. stdout_write('VERBOSE "Trying to geolocate with country %s and lang %s"\n' % (options.country, options.lang))
  197. res = geolocate_phone_number(input_cid_number, options.country, options.lang)
  198. else:
  199. # if the number is not found in OpenERP and geoloc is off, we put 'default_cid_name' as CID Name
  200. res = default_cid_name
  201. # All SIP phones should support UTF-8... but in case you have analog phones over TDM
  202. # or buggy phones, you should use the command line option --ascii
  203. if options.ascii:
  204. res = convert_to_ascii(res)
  205. stdout_write('VERBOSE "CallerID Name = %s"\n' % res)
  206. stdout_write('SET CALLERID "%s"<%s>\n' % (res, input_cid_number))
  207. return True
  208. if __name__ == '__main__':
  209. usage = "Usage: get_cid_name.py [options] login1 login2 login3 ..."
  210. epilog = "Script written by Alexis de Lattre. Published under the GNU AGPL licence."
  211. description = "This is an AGI script that sends a query to OpenERP. It can also be used without OpenERP as to geolocate phone numbers of incoming calls."
  212. parser = OptionParser(usage=usage, epilog=epilog, description=description)
  213. for option in options:
  214. param = option['names']
  215. del option['names']
  216. parser.add_option(*param, **option)
  217. options, arguments = parser.parse_args()
  218. sys.argv[:] = arguments
  219. main(options, arguments)