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.

404 lines
16 KiB

8 years ago
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # © 2010-2016 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. __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>"
  80. __date__ = "June 2015"
  81. __version__ = "0.6"
  82. # Name that will be displayed if there is no match
  83. # and no geolocalisation. Set it to False if you don't want
  84. # to have a 'not_found_name' when nothing is found
  85. not_found_name = False
  86. # Define command line options
  87. options = [
  88. {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string',
  89. 'action': 'store', 'default': False,
  90. 'help': 'DNS or IP address of the Odoo server. Default = none '
  91. '(will not try to connect to Odoo)'},
  92. {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int',
  93. 'action': 'store', 'default': 8069,
  94. 'help': "Port of Odoo's XML-RPC interface. Default = 8069"},
  95. {'names': ('-e', '--ssl'), 'dest': 'ssl',
  96. 'help': "Use SSL connections instead of clear connections. "
  97. "Default = no, use clear XML-RPC or JSON-RPC",
  98. 'action': 'store_true', 'default': False},
  99. {'names': ('-j', '--jsonrpc'), 'dest': 'jsonrpc',
  100. 'help': "Use JSON-RPC instead of the default protocol XML-RPC. "
  101. "Default = no, use XML-RPC",
  102. 'action': 'store_true', 'default': False},
  103. {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string',
  104. 'action': 'store', 'default': 'odoo',
  105. 'help': "Odoo database name. Default = 'odoo'"},
  106. {'names': ('-u', '--user-id'), 'dest': 'userid', 'type': 'int',
  107. 'action': 'store', 'default': 2,
  108. 'help': "Odoo user ID to use when connecting to Odoo in "
  109. "XML-RPC. Default = 2"},
  110. {'names': ('-t', '--username'), 'dest': 'username', 'type': 'string',
  111. 'action': 'store', 'default': 'demo',
  112. 'help': "Odoo username to use when connecting to Odoo in "
  113. "JSON-RPC. Default = demo"},
  114. {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string',
  115. 'action': 'store', 'default': 'demo',
  116. 'help': "Password of the Odoo user. Default = 'demo'"},
  117. {'names': ('-a', '--ascii'), 'dest': 'ascii',
  118. 'action': 'store_true', 'default': False,
  119. 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8"},
  120. {'names': ('-n', '--notify'), 'dest': 'notify',
  121. 'action': 'store_true', 'default': False,
  122. 'help': "Notify Odoo users via a pop-up (requires the Odoo "
  123. "module 'base_phone_popup'). If you use this option, you must pass "
  124. "the logins of the Odoo users to notify as argument to the "
  125. "script. Default = no"},
  126. {'names': ('-g', '--geoloc'), 'dest': 'geoloc',
  127. 'action': 'store_true', 'default': False,
  128. 'help': "Try to geolocate phone numbers unknown to Odoo. This "
  129. "features requires the 'phonenumbers' Python lib. To install it, "
  130. "run 'sudo pip install phonenumbers' Default = no"},
  131. {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'type': 'string',
  132. 'action': 'store', 'default': "en",
  133. 'help': "Language in which the name of the country and city name "
  134. "will be displayed by the geolocalisation database. Use the 2 "
  135. "letters ISO code of the language. Default = 'en'"},
  136. {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'type': 'string',
  137. 'action': 'store', 'default': "FR",
  138. 'help': "2 letters ISO code for your country e.g. 'FR' for France. "
  139. "This will be used by the geolocalisation system to parse the phone "
  140. "number of the calling party. Default = 'FR'"},
  141. {'names': ('-o', '--outgoing'), 'dest': 'outgoing',
  142. 'action': 'store_true', 'default': False,
  143. 'help': "Update the Connected Line ID name on outgoing calls via a "
  144. "call to the Asterisk function CONNECTEDLINE(), instead of updating "
  145. "the Caller ID name on incoming calls. Default = no."},
  146. {'names': ('-i', '--outgoing-agi-variable'), 'dest': 'outgoing_agi_var',
  147. 'type': 'string', 'action': 'store', 'default': "extension",
  148. 'help': "Enter the name of the AGI variable (without the 'agi_' "
  149. "prefix) from which the script will get the phone number dialed by "
  150. "the user on outgoing calls. For example, with Xivo, you should "
  151. "specify 'dnid' as the AGI variable. Default = 'extension'"},
  152. {'names': ('-m', '--max-size'), 'dest': 'max_size', 'type': 'int',
  153. 'action': 'store', 'default': 40,
  154. 'help': "If the name has more characters this maximum size, cut it "
  155. "to this maximum size. Default = 40"},
  156. ]
  157. def stdout_write(string):
  158. '''Wrapper on sys.stdout.write'''
  159. sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  160. sys.stdout.flush()
  161. # When we output a command, we get an answer "200 result=1" on stdin
  162. # Purge stdin to avoid these Asterisk error messages :
  163. # utils.c ast_carefulwrite: write() returned error: Broken pipe
  164. sys.stdin.readline()
  165. return True
  166. def stderr_write(string):
  167. '''Wrapper on sys.stderr.write'''
  168. sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
  169. sys.stdout.flush()
  170. return True
  171. def geolocate_phone_number(number, my_country_code, lang):
  172. import phonenumbers
  173. import phonenumbers.geocoder
  174. res = ''
  175. phonenum = phonenumbers.parse(number, my_country_code.upper())
  176. city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower())
  177. country_code = phonenumbers.region_code_for_number(phonenum)
  178. # We don't display the country name when it's my own country
  179. if country_code == my_country_code.upper():
  180. if city:
  181. res = city
  182. else:
  183. # Convert country code to country name
  184. country = phonenumbers.geocoder._region_display_name(
  185. country_code, lang.lower())
  186. if country and city:
  187. res = country + ' ' + city
  188. elif country and not city:
  189. res = country
  190. return res
  191. def convert_to_ascii(my_unicode):
  192. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  193. import unicodedata
  194. if isinstance(my_unicode, unicode):
  195. my_unicode_with_ascii_chars_only = ''.join((
  196. char for char in unicodedata.normalize('NFD', my_unicode)
  197. if unicodedata.category(char) != 'Mn'))
  198. return str(my_unicode_with_ascii_chars_only)
  199. # If the argument is already of string type, return it with the same value
  200. elif isinstance(my_unicode, str):
  201. return my_unicode
  202. else:
  203. return False
  204. def main(options, arguments):
  205. # print 'options = %s' % options
  206. # print 'arguments = %s' % arguments
  207. # AGI passes parameters to the script on standard input
  208. stdinput = {}
  209. while 1:
  210. input_line = sys.stdin.readline()
  211. if not input_line:
  212. break
  213. line = input_line.strip()
  214. try:
  215. variable, value = line.split(':')
  216. except:
  217. break
  218. if variable[:4] != 'agi_': # All AGI parameters start with 'agi_'
  219. stderr_write("bad stdin variable : %s\n" % variable)
  220. continue
  221. variable = variable.strip()
  222. value = value.strip()
  223. if variable and value:
  224. stdinput[variable] = value
  225. stderr_write("full AGI environnement :\n")
  226. for variable in stdinput.keys():
  227. stderr_write("%s = %s\n" % (variable, stdinput.get(variable)))
  228. if options.outgoing:
  229. phone_number = stdinput.get('agi_%s' % options.outgoing_agi_var)
  230. stdout_write('VERBOSE "Dialed phone number is %s"\n' % phone_number)
  231. else:
  232. # If we already have a "True" caller ID name
  233. # i.e. not just digits, but a real name, then we don't try to
  234. # connect to Odoo or geoloc, we just keep it
  235. if (
  236. stdinput.get('agi_calleridname') and
  237. not stdinput.get('agi_calleridname').isdigit() and
  238. stdinput.get('agi_calleridname').lower()
  239. not in ['asterisk', 'unknown', 'anonymous'] and
  240. not options.notify):
  241. stdout_write(
  242. 'VERBOSE "Incoming CallerID name is %s"\n'
  243. % stdinput.get('agi_calleridname'))
  244. stdout_write(
  245. 'VERBOSE "As it is a real name, we do not change it"\n')
  246. return True
  247. phone_number = stdinput.get('agi_callerid')
  248. stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8')
  249. if not isinstance(phone_number, str):
  250. stdout_write('VERBOSE "Phone number is empty"\n')
  251. exit(0)
  252. # Match for particular cases and anonymous phone calls
  253. # To test anonymous call in France, dial 3651 + number
  254. if not phone_number.isdigit():
  255. stdout_write(
  256. 'VERBOSE "Phone number (%s) is not a digit"\n' % phone_number)
  257. exit(0)
  258. stdout_write('VERBOSE "Phone number = %s"\n' % phone_number)
  259. if options.notify and not arguments:
  260. stdout_write(
  261. 'VERBOSE "When using the notify option, you must give arguments '
  262. 'to the script"\n')
  263. exit(0)
  264. if options.notify:
  265. method = 'incall_notify_by_login'
  266. else:
  267. method = 'get_name_from_phone_number'
  268. res = False
  269. # Yes, this script can be used without "-s odoo_server" !
  270. if options.server and options.jsonrpc:
  271. import odoorpc
  272. proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc'
  273. stdout_write(
  274. 'VERBOSE "Starting %s request on Odoo %s:%d database '
  275. '%s username %s"\n' % (
  276. proto.upper(), options.server, options.port, options.database,
  277. options.username))
  278. try:
  279. odoo = odoorpc.ODOO(options.server, proto, options.port)
  280. odoo.login(options.database, options.username, options.password)
  281. if options.notify:
  282. res = odoo.execute(
  283. 'phone.common', method, phone_number, arguments)
  284. else:
  285. res = odoo.execute('phone.common', method, phone_number)
  286. stdout_write('VERBOSE "Called method %s"\n' % method)
  287. except:
  288. stdout_write(
  289. 'VERBOSE "Could not connect to Odoo in JSON-RPC"\n')
  290. elif options.server:
  291. proto = options.ssl and 'https' or 'http'
  292. stdout_write(
  293. 'VERBOSE "Starting %s XML-RPC request on Odoo %s:%d '
  294. 'database %s user ID %d"\n' % (
  295. proto, options.server, options.port, options.database,
  296. options.userid))
  297. sock = xmlrpclib.ServerProxy(
  298. '%s://%s:%d/xmlrpc/object'
  299. % (proto, options.server, options.port))
  300. try:
  301. if options.notify:
  302. res = sock.execute(
  303. options.database, options.userid, options.password,
  304. 'phone.common', method, phone_number, arguments)
  305. else:
  306. res = sock.execute(
  307. options.database, options.userid, options.password,
  308. 'phone.common', method, phone_number)
  309. stdout_write('VERBOSE "Called method %s"\n' % method)
  310. except:
  311. stdout_write('VERBOSE "Could not connect to Odoo in XML-RPC"\n')
  312. # To simulate a long execution of the XML-RPC request
  313. # import time
  314. # time.sleep(5)
  315. # Function to limit the size of the name
  316. if res:
  317. if len(res) > options.max_size:
  318. res = res[0:options.max_size]
  319. elif options.geoloc:
  320. # if the number is not found in Odoo, we try to geolocate
  321. stdout_write(
  322. 'VERBOSE "Trying to geolocate with country %s and lang %s"\n'
  323. % (options.country, options.lang))
  324. res = geolocate_phone_number(
  325. phone_number, options.country, options.lang)
  326. else:
  327. # if the number is not found in Odoo and geoloc is off,
  328. # we put 'not_found_name' as Name
  329. stdout_write('VERBOSE "Phone number not found in Odoo"\n')
  330. res = not_found_name
  331. # All SIP phones should support UTF-8...
  332. # but in case you have analog phones over TDM
  333. # or buggy phones, you should use the command line option --ascii
  334. if options.ascii:
  335. res = convert_to_ascii(res)
  336. stdout_write('VERBOSE "Name = %s"\n' % res)
  337. if res:
  338. if options.outgoing:
  339. stdout_write('SET VARIABLE connectedlinename "%s"\n' % res)
  340. else:
  341. stdout_write('SET CALLERID "%s"<%s>\n' % (res, phone_number))
  342. return True
  343. if __name__ == '__main__':
  344. usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..."
  345. epilog = "Script written by Alexis de Lattre. "
  346. "Published under the GNU AGPL licence."
  347. description = "This is an AGI script that sends a query to Odoo. "
  348. "It can also be used without Odoo to geolocate phone numbers "
  349. "of incoming calls."
  350. parser = OptionParser(usage=usage, epilog=epilog, description=description)
  351. for option in options:
  352. param = option['names']
  353. del option['names']
  354. parser.add_option(*param, **option)
  355. options, arguments = parser.parse_args()
  356. sys.argv[:] = arguments
  357. main(options, arguments)