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.

501 lines
28 KiB

13 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Asterisk Click2dial module for OpenERP
  5. # Copyright (C) 2010-2012 Alexis de Lattre <alexis@via.ecp.fr>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from osv import osv, fields
  22. # Lib required to print logs
  23. import logging
  24. # Lib to translate error messages
  25. from tools.translate import _
  26. # Lib for phone number reformating -> pip install phonenumbers
  27. import phonenumbers
  28. # Lib py-asterisk from http://code.google.com/p/py-asterisk/
  29. # We need a version which has this commit : http://code.google.com/p/py-asterisk/source/detail?r=8d0e1c941cce727c702582f3c9fcd49beb4eeaa4
  30. # so a version after Nov 20th, 2012
  31. from Asterisk import Manager
  32. _logger = logging.getLogger(__name__)
  33. class asterisk_server(osv.osv):
  34. '''Asterisk server object, to store all the parameters of the Asterisk IPBXs'''
  35. _name = "asterisk.server"
  36. _description = "Asterisk Servers"
  37. _columns = {
  38. 'name': fields.char('Asterisk server name', size=50, required=True, help="Asterisk server name."),
  39. 'active': fields.boolean('Active', help="The active field allows you to hide the Asterisk server without deleting it."),
  40. 'ip_address': fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IP address or DNS name of the Asterisk server."),
  41. 'port': fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  42. 'out_prefix': fields.char('Out prefix', size=4, help="Prefix to dial to place outgoing calls. If you don't use a prefix to place outgoing calls, leave empty."),
  43. 'national_prefix': fields.char('National prefix', size=4, help="Prefix for national phone calls (don't include the 'out prefix'). For e.g., in France, the phone numbers look like '01 41 98 12 42' : the National prefix is '0'."),
  44. 'international_prefix': fields.char('International prefix', required=True, size=4, help="Prefix to add to make international phone calls (don't include the 'out prefix'). For e.g., in France, the International prefix is '00'."),
  45. 'country_prefix': fields.char('My country prefix', required=True, size=4, help="Phone prefix of the country where the Asterisk server is located. For e.g. the phone prefix for France is '33'. If the phone number to dial starts with the 'My country prefix', OpenERP will remove the country prefix from the phone number and add the 'out prefix' followed by the 'national prefix'. If the phone number to dial doesn't start with the 'My country prefix', OpenERP will add the 'out prefix' followed by the 'international prefix'."),
  46. 'login': fields.char('AMI login', size=30, required=True, help="Login that OpenERP will use to communicate with the Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf on your Asterisk server."),
  47. 'password': fields.char('AMI password', size=30, required=True, help="Password that Asterisk will use to communicate with the Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf on your Asterisk server."),
  48. 'context': fields.char('Dialplan context', size=50, required=True, help="Asterisk dialplan context from which the calls will be made. Refer to /etc/asterisk/extensions.conf on your Asterisk server."),
  49. 'wait_time': fields.integer('Wait time (sec)', required=True, help="Amount of time (in seconds) Asterisk will try to reach the user's phone before hanging up."),
  50. 'extension_priority': fields.integer('Extension priority', required=True, help="Priority of the extension in the Asterisk dialplan. Refer to /etc/asterisk/extensions.conf on your Asterisk server."),
  51. 'alert_info': fields.char('Alert-Info SIP header', size=255, help="Set Alert-Info header in SIP request to user's IP Phone for the click2dial feature. If empty, the Alert-Info header will not be added. You can use it to have a special ring tone for click2dial (a silent one !) or to activate auto-answer for example."),
  52. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  53. }
  54. _defaults = {
  55. 'active': True,
  56. 'port': 5038, # Default AMI port
  57. 'out_prefix': '0',
  58. 'national_prefix': '0',
  59. 'international_prefix': '00',
  60. 'extension_priority': 1,
  61. 'wait_time': 15,
  62. }
  63. def _check_validity(self, cr, uid, ids):
  64. for server in self.browse(cr, uid, ids):
  65. country_prefix = ('Country prefix', server.country_prefix)
  66. international_prefix = ('International prefix', server.international_prefix)
  67. out_prefix = ('Out prefix', server.out_prefix)
  68. national_prefix = ('National prefix', server.national_prefix)
  69. dialplan_context = ('Dialplan context', server.context)
  70. alert_info = ('Alert-Info SIP header', server.alert_info)
  71. login = ('AMI login', server.login)
  72. password = ('AMI password', server.password)
  73. for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
  74. if digit_prefix[1] and not digit_prefix[1].isdigit():
  75. raise osv.except_osv(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
  76. if server.wait_time < 1 or server.wait_time > 120:
  77. raise osv.except_osv(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
  78. if server.extension_priority < 1:
  79. raise osv.except_osv(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
  80. if server.port > 65535 or server.port < 1:
  81. raise osv.except_osv(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterik server '%s'" % server.name))
  82. for check_string in [dialplan_context, alert_info, login, password]:
  83. if check_string[1]:
  84. try:
  85. string = check_string[1].encode('ascii')
  86. except UnicodeEncodeError:
  87. raise osv.except_osv(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
  88. return True
  89. _constraints = [
  90. (_check_validity, "Error message in raise", ['out_prefix', 'country_prefix', 'national_prefix', 'international_prefix', 'wait_time', 'extension_priority', 'port', 'context', 'alert_info', 'login', 'password']),
  91. ]
  92. def _reformat_number(self, cr, uid, erp_number, ast_server, context=None):
  93. '''
  94. This function is dedicated to the transformation of the number
  95. available in OpenERP to the number that Asterisk should dial.
  96. You may have to inherit this function in another module specific
  97. for your company if you are not happy with the way I reformat
  98. the OpenERP numbers.
  99. '''
  100. error_title_msg = _("Invalid phone number")
  101. invalid_international_format_msg = _("The phone number is not written in valid international format. Example of valid international format : +33 1 41 98 12 42")
  102. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  103. invalid_format_msg = _("The phone number is not written in valid format.")
  104. # Let's call the variable tmp_number now
  105. tmp_number = erp_number
  106. _logger.debug('Number before reformat = %s' % tmp_number)
  107. # Check if empty
  108. if not tmp_number:
  109. raise osv.except_osv(error_title_msg, invalid_format_msg)
  110. # Before starting to use prefix, we convert empty prefix whose value
  111. # is False to an empty string
  112. country_prefix = ast_server.country_prefix or ''
  113. national_prefix = ast_server.national_prefix or ''
  114. international_prefix = ast_server.international_prefix or ''
  115. out_prefix = ast_server.out_prefix or ''
  116. # Maybe one day we will use
  117. # phonenumbers.format_out_of_country_calling_number(phonenumbers.parse('<phone_number_e164', None), 'FR')
  118. # The country code seems to be OK with the ones of OpenERP
  119. # But it returns sometimes numbers with '-'... we have to investigate this first
  120. # International format
  121. if tmp_number[0] != '+':
  122. raise # This should never happen
  123. # Remove the starting '+' of the number
  124. tmp_number = tmp_number.replace('+','')
  125. _logger.debug('Number after removal of special char = %s' % tmp_number)
  126. # At this stage, 'tmp_number' should only contain digits
  127. if not tmp_number.isdigit():
  128. raise osv.except_osv(error_title_msg, invalid_format_msg)
  129. _logger.debug('Country prefix = %s' % country_prefix)
  130. if country_prefix == tmp_number[0:len(country_prefix)]:
  131. # If the number is a national number,
  132. # remove 'my country prefix' and add 'national prefix'
  133. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  134. _logger.debug('National prefix = %s - Number with national prefix = %s' % (national_prefix, tmp_number))
  135. else:
  136. # If the number is an international number,
  137. # add 'international prefix'
  138. tmp_number = international_prefix + tmp_number
  139. _logger.debug('International prefix = %s - Number with international prefix = %s' % (international_prefix, tmp_number))
  140. # Add 'out prefix' to all numbers
  141. tmp_number = out_prefix + tmp_number
  142. _logger.debug('Out prefix = %s - Number to be sent to Asterisk = %s' % (out_prefix, tmp_number))
  143. return tmp_number
  144. def _convert_number_to_international_format(self, cr, uid, number, ast_server, context=None):
  145. '''Convert the number presented by the phone network to a number
  146. in international format e.g. +33141981242'''
  147. if number and number.isdigit() and len(number) > 5:
  148. if ast_server.international_prefix and number[0:len(ast_server.international_prefix)] == ast_server.international_prefix:
  149. number = number[len(ast_server.international_prefix):]
  150. number = '+' + number
  151. elif ast_server.national_prefix and number[0:len(ast_server.national_prefix)] == ast_server.national_prefix:
  152. number = number[len(ast_server.national_prefix):]
  153. number = '+' + ast_server.country_prefix + number
  154. return number
  155. def _get_asterisk_server_from_user(self, cr, uid, user, context=None):
  156. '''Returns an asterisk.server browse object'''
  157. # We check if the user has an Asterisk server configured
  158. if user.asterisk_server_id.id:
  159. ast_server = user.asterisk_server_id
  160. else:
  161. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  162. # If no asterisk server is configured on the user, we take the first one
  163. if not asterisk_server_ids:
  164. raise osv.except_osv(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  165. else:
  166. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  167. return ast_server
  168. def _connect_to_asterisk(self, cr, uid, context=None):
  169. '''
  170. Open the connection to the asterisk manager
  171. Returns an instance of the Asterisk Manager
  172. '''
  173. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  174. # Note : if I write 'Error' without ' :', it won't get translated...
  175. # I don't understand why !
  176. ast_server = self._get_asterisk_server_from_user(cr, uid, user, context=context)
  177. # We check if the current user has a chan type
  178. if not user.asterisk_chan_type:
  179. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  180. # We check if the current user has an internal number
  181. if not user.resource:
  182. raise osv.except_osv(_('Error :'), _('No resource name configured for the current user'))
  183. _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.resource))
  184. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  185. # Connect to the Asterisk Manager Interface
  186. try:
  187. ast_manager = Manager.Manager((ast_server.ip_address, ast_server.port), ast_server.login, ast_server.password)
  188. except Exception, e:
  189. _logger.error("Error in the Originate request to Asterisk server %s" % ast_server.ip_address)
  190. _logger.error("Here is the detail of the error : '%s'" % unicode(e))
  191. raise osv.except_osv(_('Error :'), _("Problem in the request from OpenERP to Asterisk. Here is the detail of the error: '%s'" % unicode(e)))
  192. return False
  193. return (user, ast_server, ast_manager)
  194. def _dial_with_asterisk(self, cr, uid, erp_number, context=None):
  195. #print "_dial_with_asterisk erp_number=", erp_number
  196. if not erp_number:
  197. raise osv.except_osv(_('Error :'), "Hara kiri : you must call the function with erp_number")
  198. user, ast_server, ast_manager = self._connect_to_asterisk(cr, uid, context=context)
  199. ast_number = self._reformat_number(cr, uid, erp_number, ast_server, context=context)
  200. # The user should have a CallerID
  201. if not user.callerid:
  202. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  203. variable = []
  204. if user.asterisk_chan_type == 'SIP':
  205. # We can only have one alert-info header in a SIP request
  206. if user.alert_info:
  207. variable.append('SIPAddHeader=Alert-Info: ' + user.alert_info)
  208. elif ast_server.alert_info:
  209. variable.append('SIPAddHeader=Alert-Info: ' + ast_server.alert_info)
  210. if user.variable:
  211. for user_variable in user.variable.split('|'):
  212. variable.append(user_variable.strip())
  213. try:
  214. ast_manager.Originate(
  215. user.asterisk_chan_type + '/' + user.resource + ( ('/' + user.dial_suffix) if user.dial_suffix else ''),
  216. context = ast_server.context,
  217. extension = ast_number,
  218. priority = str(ast_server.extension_priority),
  219. timeout = str(ast_server.wait_time*1000),
  220. caller_id = user.callerid,
  221. variable = variable)
  222. except Exception, e:
  223. _logger.error("Error in the Originate request to Asterisk server %s" % ast_server.ip_address)
  224. _logger.error("Here is the detail of the error : '%s'" % unicode(e))
  225. raise osv.except_osv(_('Error :'), _("Click to dial with Asterisk failed.\nHere is the error: '%s'" % unicode(e)))
  226. finally:
  227. ast_manager.Logoff()
  228. return True
  229. def _get_calling_number(self, cr, uid, context=None):
  230. user, ast_server, ast_manager = self._connect_to_asterisk(cr, uid, context=context)
  231. calling_party_number = False
  232. try:
  233. list_chan = ast_manager.Status()
  234. #from pprint import pprint
  235. #pprint(list_chan)
  236. _logger.debug("Result of Status AMI request: %s", list_chan)
  237. for chan in list_chan.values():
  238. sip_account = user.asterisk_chan_type + '/' + user.resource
  239. if chan.get('ChannelState') == '4' and chan.get('ConnectedLineNum') == user.internal_number: # 4 = Ring
  240. _logger.debug("Found a matching Event in 'Ring' state")
  241. calling_party_number = chan.get('CallerIDNum')
  242. break
  243. if chan.get('ChannelState') == '6' and sip_account in chan.get('BridgedChannel'): # 6 = Up
  244. _logger.debug("Found a matching Event in 'Up' state")
  245. calling_party_number = chan.get('CallerIDNum')
  246. break
  247. except Exception, e:
  248. _logger.error("Error in the Status request to Asterisk server %s" % ast_server.ip_address)
  249. _logger.error("Here is the detail of the error : '%s'" % unicode(e))
  250. raise osv.except_osv(_('Error :'), _("Can't get calling number from Asterisk.\nHere is the error: '%s'" % unicode(e)))
  251. finally:
  252. ast_manager.Logoff()
  253. _logger.debug("The calling party number is '%s'" % calling_party_number)
  254. return calling_party_number
  255. # Parameters specific for each user
  256. class res_users(osv.osv):
  257. _inherit = "res.users"
  258. _columns = {
  259. 'internal_number': fields.char('Internal number', size=15,
  260. help="User's internal phone number."),
  261. 'dial_suffix': fields.char('User-specific dial suffix', size=15,
  262. help="User-specific dial suffix such as aa=2wb for SCCP auto answer."),
  263. 'callerid': fields.char('Caller ID', size=50,
  264. help="Caller ID used for the calls initiated by this user."),
  265. # You'd probably think : Asterisk should reuse the callerID of sip.conf !
  266. # But it cannot, cf http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  267. 'asterisk_chan_type': fields.selection([
  268. ('SIP', 'SIP'),
  269. ('Local', 'Local'),
  270. ('IAX2', 'IAX2'),
  271. ('DAHDI', 'DAHDI'),
  272. ('Zap', 'Zap'),
  273. ('Skinny', 'Skinny'),
  274. ('MGCP', 'MGCP'),
  275. ('mISDN', 'mISDN'),
  276. ('H323', 'H323'),
  277. ('SCCP', 'SCCP'),
  278. ], 'Asterisk channel type',
  279. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  280. 'resource': fields.char('Resource name', size=64,
  281. help="Resource name for the channel type selected. For example, if you use 'Dial(SIP/phone1)' in your Asterisk dialplan to ring the SIP phone of this user, then the resource name for this user is 'phone1'. For a SIP phone, the phone number is often used as resource name, but not always."),
  282. 'alert_info': fields.char('User-specific Alert-Info SIP header', size=255, help="Set a user-specific Alert-Info header in SIP request to user's IP Phone for the click2dial feature. If empty, the Alert-Info header will not be added. You can use it to have a special ring tone for click2dial (a silent one !) or to activate auto-answer for example."),
  283. 'variable': fields.char('User-specific Variable', size=255, help="Set a user-specific 'Variable' field in the Asterisk Manager Interface 'originate' request for the click2dial feature. If you want to have several variable headers, separate them with '|'."),
  284. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  285. help="Asterisk server on which the user's phone is connected. If you leave this field empty, it will use the first Asterisk server of the user's company."),
  286. }
  287. _defaults = {
  288. 'asterisk_chan_type': 'SIP',
  289. }
  290. def _check_validity(self, cr, uid, ids):
  291. for user in self.browse(cr, uid, ids):
  292. for check_string in [('Resource name', user.resource), ('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  293. if check_string[1]:
  294. try:
  295. plom = check_string[1].encode('ascii')
  296. except UnicodeEncodeError:
  297. raise osv.except_osv(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  298. return True
  299. _constraints = [
  300. (_check_validity, "Error message in raise", ['resource', 'internal_number', 'callerid']),
  301. ]
  302. class res_partner(osv.osv):
  303. _inherit = "res.partner"
  304. def _format_phonenumber_to_e164(self, cr, uid, ids, name, arg, context=None):
  305. result = {}
  306. for partner in self.read(cr, uid, ids, ['phone', 'mobile', 'fax'], context=context):
  307. result[partner['id']] = {}
  308. for fromfield, tofield in [('phone', 'phone_e164'), ('mobile', 'mobile_e164'), ('fax', 'fax_e164')]:
  309. if not partner.get(fromfield):
  310. res = False
  311. else:
  312. try:
  313. res = phonenumbers.format_number(phonenumbers.parse(partner.get(fromfield), None), phonenumbers.PhoneNumberFormat.E164)
  314. except Exception, e:
  315. _logger.error("Cannot reformat the phone number '%s' to E.164 format. Error message: %s" % (partner.get(fromfield), e))
  316. _logger.error("You should fix this number and run the wizard 'Reformat all phone numbers' from the menu Settings > Configuration > Asterisk")
  317. # If I raise an exception here, it won't be possible to install
  318. # the module on a DB with bad phone numbers
  319. #raise osv.except_osv(_('Error :'), _("Cannot reformat the phone number '%s' to E.164 format. Error message: %s" % (partner.get(fromfield), e)))
  320. res = False
  321. result[partner['id']][tofield] = res
  322. #print "RESULT _format_phonenumber_to_e164", result
  323. return result
  324. _columns = {
  325. 'phone_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Phone in E.164 format', readonly=True, multi="e164", store={
  326. 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['phone'], 10),
  327. }),
  328. 'mobile_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Mobile in E.164 format', readonly=True, multi="e164", store={
  329. 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['mobile'], 10),
  330. }),
  331. 'fax_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Fax in E.164 format', readonly=True, multi="e164", store={
  332. 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['fax'], 10),
  333. }),
  334. }
  335. def _reformat_phonenumbers(self, cr, uid, vals, context=None):
  336. """Reformat phone numbers in international format i.e. +33141981242"""
  337. phonefields = ['phone', 'fax', 'mobile']
  338. if any([vals.get(field) for field in phonefields]):
  339. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  340. # country_id on res.company is a fields.function that looks at
  341. # company_id.partner_id.addres(default).country_id
  342. if user.company_id.country_id:
  343. user_countrycode = user.company_id.country_id.code
  344. else:
  345. # We need to raise an exception here because, if we pass None as second arg of phonenumbers.parse(), it will raise an exception when you try to enter a phone number in national format... so it's better to raise the exception here
  346. raise osv.except_osv(_('Error :'), _("You should set a country on the company '%s'" % user.company_id.name))
  347. #print "user_countrycode=", user_countrycode
  348. for field in phonefields:
  349. if vals.get(field):
  350. try:
  351. res_parse = phonenumbers.parse(vals.get(field), user_countrycode)
  352. except Exception, e:
  353. raise osv.except_osv(_('Error :'), _("Cannot reformat the phone number '%s' to international format. Error message: %s" % (vals.get(field), e)))
  354. #print "res_parse=", res_parse
  355. vals[field] = phonenumbers.format_number(res_parse, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
  356. return vals
  357. def create(self, cr, uid, vals, context=None):
  358. vals_reformated = self._reformat_phonenumbers(cr, uid, vals, context=context)
  359. return super(res_partner, self).create(cr, uid, vals_reformated, context=context)
  360. def write(self, cr, uid, ids, vals, context=None):
  361. vals_reformated = self._reformat_phonenumbers(cr, uid, vals, context=context)
  362. return super(res_partner, self).write(cr, uid, ids, vals_reformated, context=context)
  363. def dial(self, cr, uid, ids, phone_field=['phone', 'phone_e164'], context=None):
  364. '''Read the number to dial and call _connect_to_asterisk the right way'''
  365. erp_number_read = self.read(cr, uid, ids[0], phone_field, context=context)
  366. erp_number_e164 = erp_number_read[phone_field[1]]
  367. erp_number_display = erp_number_read[phone_field[0]]
  368. # Check if the number to dial is not empty
  369. if not erp_number_display:
  370. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  371. elif erp_number_display and not erp_number_e164:
  372. raise osv.except_osv(_('Error :'), _("The phone number isn't stored in the standard E.164 format. Try to run the wizard 'Reformat all phone numbers' from the menu Settings > Configuration > Asterisk."))
  373. return self.pool.get('asterisk.server')._dial_with_asterisk(cr, uid, erp_number_e164, context=context)
  374. def action_dial_phone(self, cr, uid, ids, context=None):
  375. '''Function called by the button 'Dial' next to the 'phone' field
  376. in the partner view'''
  377. return self.dial(cr, uid, ids, phone_field=['phone', 'phone_e164'], context=context)
  378. def action_dial_mobile(self, cr, uid, ids, context=None):
  379. '''Function called by the button 'Dial' next to the 'mobile' field
  380. in the partner view'''
  381. return self.dial(cr, uid, ids, phone_field=['mobile', 'mobile_e164'], context=context)
  382. def get_name_from_phone_number(self, cr, uid, number, context=None):
  383. '''Function to get name from phone number. Usefull for use from Asterisk
  384. to add CallerID name to incoming calls.
  385. The "scripts/" subdirectory of this module has an AGI script that you can
  386. install on your Asterisk IPBX : the script will be called from the Asterisk
  387. dialplan via the AGI() function and it will use this function via an XML-RPC
  388. request.
  389. '''
  390. res = self.get_partner_from_phone_number(cr, uid, number, context=context)
  391. if res:
  392. return res[2]
  393. else:
  394. return False
  395. def get_partner_from_phone_number(self, cr, uid, number, context=None):
  396. # We check that "number" is really a number
  397. _logger.debug(u"Call get_name_from_phone_number with number = %s" % number)
  398. if not isinstance(number, (str, unicode)):
  399. _logger.warning(u"Number should be a 'str' or 'unicode' but it is a '%s'" % type(number))
  400. return False
  401. _logger.warning(u"Number should only contain digits.")
  402. if not number.isdigit():
  403. return False
  404. # We try to match a phone or mobile number with the same end
  405. pg_seach_number = str('%' + number)
  406. res_ids = self.search(cr, uid, ['|', ('phone_e164', 'ilike', pg_seach_number), ('mobile_e164', 'ilike', pg_seach_number)], context=context)
  407. # TODO : use is_number_match() of the phonenumber lib ?
  408. if len(res_ids) > 1:
  409. _logger.warning(u"There are several partners (IDS = %s) with the same phone number %s" % (str(res_ids), number))
  410. if res_ids:
  411. entry = self.read(cr, uid, res_ids[0], ['name', 'parent_id'], context=context)
  412. _logger.debug(u"Answer get_partner_from_phone_number with name = %s" % entry['name'])
  413. return (entry['id'], entry['parent_id'] and entry['parent_id'][0] or False, entry['name'])
  414. else:
  415. _logger.debug(u"No match for phone number %s" % number)
  416. return False
  417. # This module supports multi-company
  418. class res_company(osv.osv):
  419. _inherit = "res.company"
  420. _columns = {
  421. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  422. }