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.

372 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. Default = 443 when SSL is on, "
  97. "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([x not in phone_chars for x in agi.env['agi_calleridname']]) and
  209. agi.env['agi_calleridname'].lower()
  210. not in ['asterisk', 'unknown', 'anonymous'] and
  211. not options.notify):
  212. agi.verbose(
  213. "Incoming CallerID name is %s"
  214. % agi.env['agi_calleridname'])
  215. agi.verbose("As it is a real name, we do not change it")
  216. return True
  217. phone_number = agi.env['agi_callerid']
  218. if not isinstance(phone_number, str):
  219. agi.verbose("Phone number is empty")
  220. exit(0)
  221. # Match for particular cases and anonymous phone calls
  222. # To test anonymous call in France, dial 3651 + number
  223. if not phone_number.isdigit():
  224. agi.verbose("Phone number (%s) is not a digit" % phone_number)
  225. exit(0)
  226. agi.verbose("Phone number = %s" % phone_number)
  227. if options.notify and not arguments:
  228. agi.verbose(
  229. "When using the notify option, you must give arguments "
  230. "to the script")
  231. exit(0)
  232. if options.notify:
  233. method = 'incall_notify_by_login'
  234. else:
  235. method = 'get_name_from_phone_number'
  236. if options.port:
  237. port = options.port
  238. # default port depends on protocol
  239. else:
  240. if options.ssl:
  241. port = 443
  242. else:
  243. port = 8069
  244. res = False
  245. # Yes, this script can be used without "-s odoo_server" !
  246. if options.server and options.jsonrpc:
  247. import odoorpc
  248. proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc'
  249. agi.verbose(
  250. "Starting %s request on Odoo %s:%d database %s username %s" % (
  251. proto.upper(), options.server, port, options.database,
  252. options.username))
  253. try:
  254. odoo = odoorpc.ODOO(options.server, proto, port)
  255. odoo.login(options.database, options.username, options.password)
  256. if options.notify:
  257. res = odoo.execute(
  258. 'phone.common', method, phone_number, arguments)
  259. else:
  260. res = odoo.execute('phone.common', method, phone_number)
  261. agi.verbose("Called method %s" % method)
  262. except:
  263. agi.verbose("Could not connect to Odoo in JSON-RPC")
  264. elif options.server:
  265. proto = options.ssl and 'https' or 'http'
  266. agi.verbose(
  267. "Starting %s XML-RPC request on Odoo %s:%d "
  268. "database %s user ID %d" % (
  269. proto, options.server, port, options.database,
  270. options.userid))
  271. sock = xmlrpclib.ServerProxy(
  272. '%s://%s:%d/xmlrpc/object' % (proto, options.server, port))
  273. try:
  274. if options.notify:
  275. res = sock.execute(
  276. options.database, options.userid, options.password,
  277. 'phone.common', method, phone_number, arguments)
  278. else:
  279. res = sock.execute(
  280. options.database, options.userid, options.password,
  281. 'phone.common', method, phone_number)
  282. agi.verbose("Called method %s" % method)
  283. except:
  284. agi.verbose("Could not connect to Odoo in XML-RPC")
  285. # To simulate a long execution of the XML-RPC request
  286. # import time
  287. # time.sleep(5)
  288. # Function to limit the size of the name
  289. if res:
  290. if len(res) > options.max_size:
  291. res = res[0:options.max_size]
  292. elif options.geoloc:
  293. # if the number is not found in Odoo, we try to geolocate
  294. agi.verbose(
  295. "Trying to geolocate with country %s and lang %s"
  296. % (options.country, options.lang))
  297. res = geolocate_phone_number(
  298. phone_number, options.country, options.lang)
  299. else:
  300. # if the number is not found in Odoo and geoloc is off,
  301. # we put 'not_found_name' as Name
  302. agi.verbose("Phone number not found in Odoo")
  303. res = not_found_name
  304. # All SIP phones should support UTF-8...
  305. # but in case you have analog phones over TDM
  306. # or buggy phones, you should use the command line option --ascii
  307. if options.ascii:
  308. res = convert_to_ascii(res)
  309. agi.verbose("Name = %s" % res)
  310. if res:
  311. if options.outgoing:
  312. agi.set_variable('connectedlinename', res)
  313. else:
  314. agi.set_callerid('"%s"<%s>' % (res, phone_number))
  315. return True
  316. if __name__ == '__main__':
  317. usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..."
  318. epilog = "Script written by Alexis de Lattre. "
  319. "Published under the GNU AGPL licence."
  320. description = "This is an AGI script that sends a query to Odoo. "
  321. "It can also be used without Odoo to geolocate phone numbers "
  322. "of incoming calls."
  323. parser = OptionParser(usage=usage, epilog=epilog, description=description)
  324. for option in options:
  325. param = option['names']
  326. del option['names']
  327. parser.add_option(*param, **option)
  328. options, arguments = parser.parse_args()
  329. sys.argv[:] = arguments
  330. main(options, arguments)