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.

275 lines
9.6 KiB

  1. #!/usr/bin/python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. Name lookup in OpenERP for incoming and outgoing calls with an
  5. FreeSWITCH system
  6. This script is designed to be used as an WSGI script on the same server
  7. as OpenERP/Odoo.
  8. Relevant documentation"
  9. https://wiki.freeswitch.org/wiki/Mod_cidlookup
  10. https://freeswitch.org/confluence/display/FREESWITCH/mod_cidlookup
  11. Apache Configuration:
  12. Listen 8080
  13. <VirtualHost *:8080>
  14. WSGIScriptAlias /wscgi-bin/ /var/www/wscgi-bin/
  15. ServerAdmin webmaster@localhost
  16. # ...
  17. </VirtualHost>
  18. FreeSWITCH mod_cidlookup configuration:
  19. <configuration name="cidlookup.conf" description="cidlookup Configuration">
  20. <settings>
  21. <param name="url" value="https://openerp.localdomain/wscgi-bin/get_caller_name.py?name=${caller_id_name}&number=${caller_id_number}&notify=1004,1007"/>
  22. <param name="cache" value="false"/>
  23. </settings>
  24. </configuration>
  25. If you want geoloc, add &geoloc=true to the end (it is going to be slow).
  26. Notify should be the internal number of the called parties. This should be
  27. comma (,) delimited, not :_: delimited. It is up to you to format the
  28. extensions list appropriately. The persons who are at extensions in the
  29. notify list will receive a poppup if so configured and if they are logged in.
  30. From the dialplan, do something like this <action application="set"
  31. data="effective_caller_id_name=${cidlookup(${caller_id_number})}"/>.
  32. If you are not using FreeTDM modules for the incoming line, doing
  33. <action application="pre_answer"/> before the cidlookup is a VERY good idea.
  34. If you are wishing to set the callee name, <action application="export"
  35. data="callee_id_name=${cidlookup($1)}" />
  36. Of course, you should adapt this example to the FreeSWITCH server you are
  37. using. This is especially true of the options variable in the application
  38. function. The user (by number id, not name) that is used to connect to
  39. OpenERP/Odoo must have "Phone CallerID" access rights. That may also require
  40. "Technical Features" rights.
  41. """
  42. __author__ = "Trever Adams <trever.adams@gmail.com>"
  43. __date__ = "May 2016"
  44. __version__ = "0.5"
  45. # Copyright (C) 2014-2015 Trever L. Adams <trever.adams@gmail.com>
  46. # Copyright (C) 2010-2014 Alexis de Lattre <alexis.delattre@akretion.com>
  47. #
  48. # This program is free software: you can redistribute it and/or modify
  49. # it under the terms of the GNU Affero General Public License as
  50. # published by the Free Software Foundation, either version 3 of the
  51. # License, or (at your option) any later version.
  52. #
  53. # This program is distributed in the hope that it will be useful,
  54. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  55. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  56. # GNU Affero General Public License for more details.
  57. #
  58. # You should have received a copy of the GNU Affero General Public License
  59. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  60. import sys
  61. sys.path.append('.')
  62. import xmlrpclib
  63. from cgi import parse_qs, escape
  64. import unicodedata
  65. # Name that will be displayed if there is no match
  66. # and no geolocalisation
  67. not_found_name = "Not in OpenERP"
  68. # Set to 1 for debugging output
  69. verbose = 0
  70. def stdout_write(string):
  71. '''Wrapper on sys.stdout.write'''
  72. if verbose == 1:
  73. sys.stdout.write(string)
  74. sys.stdout.flush()
  75. return True
  76. def stderr_write(string):
  77. '''Wrapper on sys.stderr.write'''
  78. if verbose == 1:
  79. sys.stderr.write(string)
  80. sys.stderr.flush()
  81. return True
  82. def geolocate_phone_number(number, my_country_code, lang):
  83. import phonenumbers
  84. from phonenumbers import geocoder
  85. res = ''
  86. phonenum = phonenumbers.parse(number, my_country_code.upper())
  87. city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower())
  88. country_code = phonenumbers.region_code_for_number(phonenum)
  89. # We don't display the country name when it's my own country
  90. if country_code == my_country_code.upper():
  91. if city:
  92. res = city
  93. else:
  94. # Convert country code to country name
  95. country = phonenumbers.geocoder._region_display_name(
  96. country_code, lang.lower())
  97. if country and city:
  98. res = country + ' ' + city
  99. elif country and not city:
  100. res = country
  101. return res
  102. def convert_to_ascii(my_unicode):
  103. '''Convert to ascii, with clever management of accents (é -> e, è -> e)'''
  104. if isinstance(my_unicode, unicode):
  105. my_unicode_with_ascii_chars_only = ''.join((
  106. char for char in unicodedata.normalize('NFD', my_unicode)
  107. if unicodedata.category(char) != 'Mn'))
  108. return str(my_unicode_with_ascii_chars_only)
  109. # If the argument is already of string type, return it with the same value
  110. elif isinstance(my_unicode, str):
  111. return my_unicode
  112. else:
  113. return False
  114. def main(name, phone_number, options):
  115. # print 'options = %s' % options
  116. # If we already have a "True" caller ID name
  117. # i.e. not just digits, but a real name, then we don't try to
  118. # connect to OpenERP or geoloc, we just keep it
  119. if (
  120. name and
  121. not name.isdigit() and
  122. name.lower()
  123. not in ['freeswitch', 'unknown', 'anonymous', 'unavailable']):
  124. stdout_write('Incoming CallerID name is %s\n' % name)
  125. stdout_write('As it is a real name, we do not change it\n')
  126. return name
  127. if not isinstance(phone_number, str):
  128. stdout_write('Phone number is empty\n')
  129. exit(0)
  130. # Match for particular cases and anonymous phone calls
  131. # To test anonymous call in France, dial 3651 + number
  132. if not phone_number.isdigit():
  133. stdout_write(
  134. 'Phone number (%s) is not a digit\n' % phone_number)
  135. exit(0)
  136. stdout_write('Phone number = %s\n' % phone_number)
  137. res = name
  138. # Yes, this script can be used without "-s openerp_server" !
  139. if options["server"]:
  140. if options["ssl"]:
  141. stdout_write(
  142. 'Starting XML-RPC secure request on OpenERP %s:%s\n'
  143. % (options["server"], str(options["port"])))
  144. protocol = 'https'
  145. else:
  146. stdout_write(
  147. 'Starting clear XML-RPC request on OpenERP %s:%s\n'
  148. % (options["server"], str(options["port"])))
  149. protocol = 'http'
  150. sock = xmlrpclib.ServerProxy(
  151. '%s://%s:%s/xmlrpc/object'
  152. % (protocol, options["server"], str(options["port"])))
  153. try:
  154. if options["notify"]:
  155. res = sock.execute(
  156. options["database"], options["user"], options["password"],
  157. 'phone.common', 'incall_notify_by_extension',
  158. phone_number, options["notify"])
  159. stdout_write('Calling incall_notify_by_extension\n')
  160. else:
  161. res = sock.execute(
  162. options["database"], options["user"], options["password"],
  163. 'phone.common', 'get_name_from_phone_number',
  164. phone_number)
  165. stdout_write('Calling get_name_from_phone_number\n')
  166. stdout_write('End of XML-RPC request on OpenERP\n')
  167. if not res:
  168. stdout_write('Phone number not found in OpenERP\n')
  169. except:
  170. stdout_write('Could not connect to OpenERP %s\n'
  171. % options["database"])
  172. res = False
  173. # To simulate a long execution of the XML-RPC request
  174. # import time
  175. # time.sleep(5)
  176. # Function to limit the size of the name
  177. if res:
  178. if len(res) > options["max_size"]:
  179. res = res[0:options["max_size"]]
  180. elif options["geoloc"]:
  181. # if the number is not found in OpenERP, we try to geolocate
  182. stdout_write(
  183. 'Trying to geolocate with country %s and lang %s\n'
  184. % (options["country"], options["lang"]))
  185. res = geolocate_phone_number(
  186. phone_number, options["country"], options["lang"])
  187. else:
  188. # if the number is not found in OpenERP and geoloc is off,
  189. # we put 'not_found_name' as Name
  190. res = not_found_name
  191. # All SIP phones should support UTF-8...
  192. # but in case you have analog phones over TDM
  193. # or buggy phones, you should use the command line option --ascii
  194. if options["ascii"]:
  195. res = convert_to_ascii(res)
  196. stdout_write('Name = %s\n' % res)
  197. return res
  198. def application(environ, start_response):
  199. output = ""
  200. name = False
  201. options = {}
  202. options["server"] = "127.0.0.1"
  203. options["port"] = 8069
  204. options["database"] = "test"
  205. options["user"] = 1
  206. options["password"] = "admin"
  207. options["geoloc"] = True
  208. options["country"] = "US"
  209. options["lang"] = "en"
  210. options["ssl"] = False
  211. options["ascii"] = True
  212. options["max_size"] = 40
  213. parameters = parse_qs(environ.get('QUERY_STRING', ''))
  214. if 'number' in parameters:
  215. number = escape(parameters['number'][0])
  216. if 'name' in parameters:
  217. name = escape(parameters['name'][0])
  218. if 'notify' in parameters:
  219. options["notify"] = []
  220. for item in parameters['notify'][0].split(','):
  221. options["notify"].append(escape(item))
  222. stdout_write(
  223. 'Trying to notify %s\n' % options["notify"])
  224. else:
  225. options["notify"] = False
  226. if 'geoloc' in parameters:
  227. options["geoloc"] = True
  228. else:
  229. options["geoloc"] = False
  230. output += main(name if name else False, number, options)
  231. status = '200 OK'
  232. response_headers = [('Content-type', 'text/plain'),
  233. ('Content-Length', str(len(output)))]
  234. start_response(status, response_headers)
  235. return [output]