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.

374 lines
15 KiB

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