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.

360 lines
15 KiB

8 years ago
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # © 2010-2018 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. Name lookup in Odoo for incoming and outgoing calls with an
  19. Asterisk IPBX
  20. This script is designed to be used as an AGI on an Asterisk IPBX...
  21. BUT I advise you to use a wrapper around this script to control the
  22. execution time. Why ? Because if the script takes too much time to
  23. execute or get stucks (in the XML-RPC request for example), then the
  24. incoming phone call will also get stucks and you will miss a call !
  25. The simplest solution I found is to use the "timeout" shell command to
  26. call this script, for example :
  27. # timeout 2s get_name_agi.py <OPTIONS>
  28. See my 2 sample wrappers "set_name_incoming_timeout.sh" and
  29. "set_name_outgoing_timeout.sh"
  30. It's probably a good idea to create a user in Odoo dedicated to this task.
  31. This user only needs to be part of the group "Phone CallerID", which has
  32. read access on the 'res.partner' and other objects with phone numbers and
  33. names.
  34. Note that this script can be used without Odoo, with just the
  35. geolocalisation feature : for that, don't use option --server ;
  36. only use --geoloc
  37. This script can be used both on incoming and outgoing calls :
  38. 1) INCOMING CALLS
  39. When executed from the dialplan on an incoming phone call, it will
  40. lookup in Odoo's partners and other objects with phone numbers
  41. (leads, employees, etc...), and, if it finds the phone number, it will
  42. get the corresponding name of the person and use this name as CallerID
  43. name for the incoming call.
  44. Requires the "base_phone" module
  45. available from https://github.com/OCA/connector-telephony
  46. Asterisk dialplan example :
  47. [from-extern]
  48. exten = _0141981242,1,AGI(/usr/local/bin/set_name_incoming_timeout.sh)
  49. same = n,Dial(SIP/10, 30)
  50. same = n,Answer
  51. same = n,Voicemail(10@default,u)
  52. same = n,Hangup
  53. 2) OUTGOING CALLS
  54. When executed from the dialplan on an outgoing call, it will
  55. lookup in Odoo the name corresponding to the phone number
  56. that is called by the user and it will update the name of the
  57. callee on the screen of the phone of the caller.
  58. For that, it uses the CONNECTEDLINE dialplan function of Asterisk
  59. See the following page for more info:
  60. https://wiki.asterisk.org/wiki/display/AST/Manipulating+Party+ID+Information
  61. It is not possible to set the CONNECTEDLINE directly from an AGI script,
  62. (at least not with Asterisk 11) so the AGI script sets a variable
  63. "connectedlinename" that can then be read from the dialplan and passed
  64. as parameter to the CONNECTEDLINE function.
  65. Here is the code that I used on the pre-process subroutine
  66. "odoo-out-call" of the Outgoing Call of my Xivo server :
  67. [odoo-out-call]
  68. exten = s,1,AGI(/var/lib/asterisk/agi-bin/set_name_outgoing_timeout.sh)
  69. same = n,Set(CONNECTEDLINE(name,i)=${connectedlinename})
  70. same = n,Set(CONNECTEDLINE(name-pres,i)=allowed)
  71. same = n,Set(CONNECTEDLINE(num,i)=${XIVO_DSTNUM})
  72. same = n,Set(CONNECTEDLINE(num-pres)=allowed)
  73. same = n,Return()
  74. Of course, you should adapt this example to the Asterisk server you are using.
  75. """
  76. import xmlrpclib
  77. import sys
  78. from optparse import OptionParser
  79. from asterisk import agi as agilib # pip install pyst2
  80. __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>"
  81. __date__ = "February 2018"
  82. __version__ = "0.6"
  83. # Name that will be displayed if there is no match
  84. # and no geolocalisation. Set it to False if you don't want
  85. # to have a 'not_found_name' when nothing is found
  86. not_found_name = False
  87. # Define command line options
  88. options = [
  89. {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string',
  90. 'action': 'store', 'default': False,
  91. 'help': 'DNS or IP address of the Odoo server. Default = none '
  92. '(will not try to connect to Odoo)'},
  93. {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int',
  94. 'action': 'store', 'default': 8069,
  95. 'help': "Port of Odoo's XML-RPC interface. Default = 8069"},
  96. {'names': ('-e', '--ssl'), 'dest': 'ssl',
  97. 'help': "Use SSL connections instead of clear connections. "
  98. "Default = no, use clear XML-RPC or JSON-RPC",
  99. 'action': 'store_true', 'default': False},
  100. {'names': ('-j', '--jsonrpc'), 'dest': 'jsonrpc',
  101. 'help': "Use JSON-RPC instead of the default protocol XML-RPC. "
  102. "Default = no, use XML-RPC",
  103. 'action': 'store_true', 'default': False},
  104. {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string',
  105. 'action': 'store', 'default': 'odoo',
  106. 'help': "Odoo database name. Default = 'odoo'"},
  107. {'names': ('-u', '--user-id'), 'dest': 'userid', 'type': 'int',
  108. 'action': 'store', 'default': 2,
  109. 'help': "Odoo user ID to use when connecting to Odoo in "
  110. "XML-RPC. Default = 2"},
  111. {'names': ('-t', '--username'), 'dest': 'username', 'type': 'string',
  112. 'action': 'store', 'default': 'demo',
  113. 'help': "Odoo username to use when connecting to Odoo in "
  114. "JSON-RPC. Default = demo"},
  115. {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string',
  116. 'action': 'store', 'default': 'demo',
  117. 'help': "Password of the Odoo user. Default = 'demo'"},
  118. {'names': ('-a', '--ascii'), 'dest': 'ascii',
  119. 'action': 'store_true', 'default': False,
  120. 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8"},
  121. {'names': ('-n', '--notify'), 'dest': 'notify',
  122. 'action': 'store_true', 'default': False,
  123. 'help': "Notify Odoo users via a pop-up (requires the Odoo "
  124. "module 'base_phone_popup'). If you use this option, you must pass "
  125. "the logins of the Odoo users to notify as argument to the "
  126. "script. Default = no"},
  127. {'names': ('-g', '--geoloc'), 'dest': 'geoloc',
  128. 'action': 'store_true', 'default': False,
  129. 'help': "Try to geolocate phone numbers unknown to Odoo. This "
  130. "features requires the 'phonenumbers' Python lib. To install it, "
  131. "run 'sudo pip install phonenumbers' Default = no"},
  132. {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'type': 'string',
  133. 'action': 'store', 'default': "en",
  134. 'help': "Language in which the name of the country and city name "
  135. "will be displayed by the geolocalisation database. Use the 2 "
  136. "letters ISO code of the language. Default = 'en'"},
  137. {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'type': 'string',
  138. 'action': 'store', 'default': "FR",
  139. 'help': "2 letters ISO code for your country e.g. 'FR' for France. "
  140. "This will be used by the geolocalisation system to parse the phone "
  141. "number of the calling party. Default = 'FR'"},
  142. {'names': ('-o', '--outgoing'), 'dest': 'outgoing',
  143. 'action': 'store_true', 'default': False,
  144. 'help': "Update the Connected Line ID name on outgoing calls via a "
  145. "call to the Asterisk function CONNECTEDLINE(), instead of updating "
  146. "the Caller ID name on incoming calls. Default = no."},
  147. {'names': ('-i', '--outgoing-agi-variable'), 'dest': 'outgoing_agi_var',
  148. 'type': 'string', 'action': 'store', 'default': "extension",
  149. 'help': "Enter the name of the AGI variable (without the 'agi_' "
  150. "prefix) from which the script will get the phone number dialed by "
  151. "the user on outgoing calls. For example, with Xivo, you should "
  152. "specify 'dnid' as the AGI variable. Default = 'extension'"},
  153. {'names': ('-m', '--max-size'), 'dest': 'max_size', 'type': 'int',
  154. 'action': 'store', 'default': 40,
  155. 'help': "If the name has more characters this maximum size, cut it "
  156. "to this maximum size. Default = 40"},
  157. ]
  158. def geolocate_phone_number(number, my_country_code, lang):
  159. import phonenumbers
  160. import phonenumbers.geocoder # Takes an enormous amount of time...
  161. res = ''
  162. phonenum = phonenumbers.parse(number, my_country_code.upper())
  163. city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower())
  164. country_code = phonenumbers.region_code_for_number(phonenum)
  165. # We don't display the country name when it's my own country
  166. if country_code == my_country_code.upper():
  167. if city:
  168. res = city
  169. else:
  170. # Convert country code to country name
  171. country = phonenumbers.geocoder._region_display_name(
  172. country_code, lang.lower())
  173. if country and city:
  174. res = country + ' ' + city
  175. elif country and not city:
  176. res = country
  177. return res
  178. def convert_to_ascii(my_unicode):
  179. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  180. import unicodedata
  181. if isinstance(my_unicode, unicode):
  182. my_unicode_with_ascii_chars_only = ''.join((
  183. char for char in unicodedata.normalize('NFD', my_unicode)
  184. if unicodedata.category(char) != 'Mn'))
  185. return str(my_unicode_with_ascii_chars_only)
  186. # If the argument is already of string type, return it with the same value
  187. elif isinstance(my_unicode, str):
  188. return my_unicode
  189. else:
  190. return False
  191. def main(options, arguments):
  192. # print 'options = %s' % options
  193. # print 'arguments = %s' % arguments
  194. agi = agilib.AGI()
  195. if options.outgoing:
  196. phone_number = agi.env['agi_%s' % options.outgoing_agi_var]
  197. agi.verbose("Dialed phone number is %s" % phone_number)
  198. else:
  199. # If we already have a "True" caller ID name
  200. # i.e. not just digits, but a real name, then we don't try to
  201. # connect to Odoo or geoloc, we just keep it
  202. if (
  203. agi.env.get('agi_calleridname') and
  204. not agi.env['agi_calleridname'].isdigit() and
  205. agi.env['agi_calleridname'].lower()
  206. not in ['asterisk', 'unknown', 'anonymous'] and
  207. not options.notify):
  208. agi.verbose(
  209. "Incoming CallerID name is %s"
  210. % agi.env['agi_calleridname'])
  211. agi.verbose("As it is a real name, we do not change it")
  212. return True
  213. phone_number = agi.env['agi_callerid']
  214. if not isinstance(phone_number, str):
  215. agi.verbose("Phone number is empty")
  216. exit(0)
  217. # Match for particular cases and anonymous phone calls
  218. # To test anonymous call in France, dial 3651 + number
  219. if not phone_number.isdigit():
  220. agi.verbose("Phone number (%s) is not a digit" % phone_number)
  221. exit(0)
  222. agi.verbose("Phone number = %s" % phone_number)
  223. if options.notify and not arguments:
  224. agi.verbose(
  225. "When using the notify option, you must give arguments "
  226. "to the script")
  227. exit(0)
  228. if options.notify:
  229. method = 'incall_notify_by_login'
  230. else:
  231. method = 'get_name_from_phone_number'
  232. res = False
  233. # Yes, this script can be used without "-s odoo_server" !
  234. if options.server and options.jsonrpc:
  235. import odoorpc
  236. proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc'
  237. agi.verbose(
  238. "Starting %s request on Odoo %s:%d database %s username %s" % (
  239. proto.upper(), options.server, options.port, options.database,
  240. options.username))
  241. try:
  242. odoo = odoorpc.ODOO(options.server, proto, options.port)
  243. odoo.login(options.database, options.username, options.password)
  244. if options.notify:
  245. res = odoo.execute(
  246. 'phone.common', method, phone_number, arguments)
  247. else:
  248. res = odoo.execute('phone.common', method, phone_number)
  249. agi.verbose("Called method %s" % method)
  250. except:
  251. agi.verbose("Could not connect to Odoo in JSON-RPC")
  252. elif options.server:
  253. proto = options.ssl and 'https' or 'http'
  254. agi.verbose(
  255. "Starting %s XML-RPC request on Odoo %s:%d "
  256. "database %s user ID %d" % (
  257. proto, options.server, options.port, options.database,
  258. options.userid))
  259. sock = xmlrpclib.ServerProxy(
  260. '%s://%s:%d/xmlrpc/object'
  261. % (proto, options.server, options.port))
  262. try:
  263. if options.notify:
  264. res = sock.execute(
  265. options.database, options.userid, options.password,
  266. 'phone.common', method, phone_number, arguments)
  267. else:
  268. res = sock.execute(
  269. options.database, options.userid, options.password,
  270. 'phone.common', method, phone_number)
  271. agi.verbose("Called method %s" % method)
  272. except:
  273. agi.verbose("Could not connect to Odoo in XML-RPC")
  274. # To simulate a long execution of the XML-RPC request
  275. # import time
  276. # time.sleep(5)
  277. # Function to limit the size of the name
  278. if res:
  279. if len(res) > options.max_size:
  280. res = res[0:options.max_size]
  281. elif options.geoloc:
  282. # if the number is not found in Odoo, we try to geolocate
  283. agi.verbose(
  284. "Trying to geolocate with country %s and lang %s"
  285. % (options.country, options.lang))
  286. res = geolocate_phone_number(
  287. phone_number, options.country, options.lang)
  288. else:
  289. # if the number is not found in Odoo and geoloc is off,
  290. # we put 'not_found_name' as Name
  291. agi.verbose("Phone number not found in Odoo")
  292. res = not_found_name
  293. # All SIP phones should support UTF-8...
  294. # but in case you have analog phones over TDM
  295. # or buggy phones, you should use the command line option --ascii
  296. if options.ascii:
  297. res = convert_to_ascii(res)
  298. agi.verbose("Name = %s" % res)
  299. if res:
  300. if options.outgoing:
  301. agi.set_variable('connectedlinename', res)
  302. else:
  303. agi.set_callerid('"%s"<%s>' % (res, phone_number))
  304. return True
  305. if __name__ == '__main__':
  306. usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..."
  307. epilog = "Script written by Alexis de Lattre. "
  308. "Published under the GNU AGPL licence."
  309. description = "This is an AGI script that sends a query to Odoo. "
  310. "It can also be used without Odoo to geolocate phone numbers "
  311. "of incoming calls."
  312. parser = OptionParser(usage=usage, epilog=epilog, description=description)
  313. for option in options:
  314. param = option['names']
  315. del option['names']
  316. parser.add_option(*param, **option)
  317. options, arguments = parser.parse_args()
  318. sys.argv[:] = arguments
  319. main(options, arguments)