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.

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