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.

550 lines
32 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 open a socket (needed to communicate with Asterisk server)
  23. import socket
  24. # Lib required to print logs
  25. import logging
  26. # Lib to translate error messages
  27. from tools.translate import _
  28. # Lib for phone number reformating -> pip install phonenumbers
  29. import phonenumbers
  30. _logger = logging.getLogger(__name__)
  31. class asterisk_server(osv.osv):
  32. '''Asterisk server object, to store all the parameters of the Asterisk IPBXs'''
  33. _name = "asterisk.server"
  34. _description = "Asterisk Servers"
  35. _columns = {
  36. 'name': fields.char('Asterisk server name', size=50, required=True, help="Asterisk server name."),
  37. 'active': fields.boolean('Active', help="The active field allows you to hide the Asterisk server without deleting it."),
  38. 'ip_address': fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IP address or DNS name of the Asterisk server."),
  39. 'port': fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  40. '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."),
  41. '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'."),
  42. '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'."),
  43. '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'."),
  44. '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."),
  45. '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."),
  46. '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."),
  47. '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."),
  48. '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."),
  49. '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. If you want to have several variable headers, separate them with '|'."),
  50. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  51. }
  52. _defaults = {
  53. 'active': True,
  54. 'port': 5038, # Default AMI port
  55. 'out_prefix': '0',
  56. 'national_prefix': '0',
  57. 'international_prefix': '00',
  58. 'extension_priority': 1,
  59. 'wait_time': 15,
  60. }
  61. def _check_validity(self, cr, uid, ids):
  62. for server in self.browse(cr, uid, ids):
  63. country_prefix = ('Country prefix', server.country_prefix)
  64. international_prefix = ('International prefix', server.international_prefix)
  65. out_prefix = ('Out prefix', server.out_prefix)
  66. national_prefix = ('National prefix', server.national_prefix)
  67. dialplan_context = ('Dialplan context', server.context)
  68. alert_info = ('Alert-Info SIP header', server.alert_info)
  69. login = ('AMI login', server.login)
  70. password = ('AMI password', server.password)
  71. for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
  72. if digit_prefix[1] and not digit_prefix[1].isdigit():
  73. raise osv.except_osv(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
  74. if server.wait_time < 1 or server.wait_time > 120:
  75. raise osv.except_osv(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
  76. if server.extension_priority < 1:
  77. raise osv.except_osv(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
  78. if server.port > 65535 or server.port < 1:
  79. raise osv.except_osv(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterik server '%s'" % server.name))
  80. for check_string in [dialplan_context, alert_info, login, password]:
  81. if check_string[1]:
  82. try:
  83. string = check_string[1].encode('ascii')
  84. except UnicodeEncodeError:
  85. raise osv.except_osv(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
  86. return True
  87. _constraints = [
  88. (_check_validity, "Error message in raise", ['out_prefix', 'country_prefix', 'national_prefix', 'international_prefix', 'wait_time', 'extension_priority', 'port', 'context', 'alert_info', 'login', 'password']),
  89. ]
  90. def _reformat_number(self, cr, uid, erp_number, ast_server, context=None):
  91. '''
  92. This function is dedicated to the transformation of the number
  93. available in OpenERP to the number that Asterisk should dial.
  94. You may have to inherit this function in another module specific
  95. for your company if you are not happy with the way I reformat
  96. the OpenERP numbers.
  97. '''
  98. error_title_msg = _("Invalid phone number")
  99. 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")
  100. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  101. invalid_format_msg = _("The phone number is not written in valid format.")
  102. # Let's call the variable tmp_number now
  103. tmp_number = erp_number
  104. _logger.debug('Number before reformat = %s' % tmp_number)
  105. # Check if empty
  106. if not tmp_number:
  107. raise osv.except_osv(error_title_msg, invalid_format_msg)
  108. # Before starting to use prefix, we convert empty prefix whose value
  109. # is False to an empty string
  110. country_prefix = ast_server.country_prefix or ''
  111. national_prefix = ast_server.national_prefix or ''
  112. international_prefix = ast_server.international_prefix or ''
  113. out_prefix = ast_server.out_prefix or ''
  114. # Maybe one day we will use
  115. # phonenumbers.format_out_of_country_calling_number(phonenumbers.parse('<phone_number_e164', None), 'FR')
  116. # The country code seems to be OK with the ones of OpenERP
  117. # But it returns sometimes numbers with '-'... we have to investigate this first
  118. # International format
  119. if tmp_number[0] != '+':
  120. raise # This should never happen
  121. # Remove the starting '+' of the number
  122. tmp_number = tmp_number.replace('+','')
  123. _logger.debug('Number after removal of special char = %s' % tmp_number)
  124. # At this stage, 'tmp_number' should only contain digits
  125. if not tmp_number.isdigit():
  126. raise osv.except_osv(error_title_msg, invalid_format_msg)
  127. _logger.debug('Country prefix = %s' % country_prefix)
  128. if country_prefix == tmp_number[0:len(country_prefix)]:
  129. # If the number is a national number,
  130. # remove 'my country prefix' and add 'national prefix'
  131. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  132. _logger.debug('National prefix = %s - Number with national prefix = %s' % (national_prefix, tmp_number))
  133. else:
  134. # If the number is an international number,
  135. # add 'international prefix'
  136. tmp_number = international_prefix + tmp_number
  137. _logger.debug('International prefix = %s - Number with international prefix = %s' % (international_prefix, tmp_number))
  138. # Add 'out prefix' to all numbers
  139. tmp_number = out_prefix + tmp_number
  140. _logger.debug('Out prefix = %s - Number to be sent to Asterisk = %s' % (out_prefix, tmp_number))
  141. return tmp_number
  142. def _convert_number_to_international_format(self, cr, uid, number, ast_server, context=None):
  143. '''Convert the number presented by the phone network to a number
  144. in international format e.g. +33141981242'''
  145. if number and number.isdigit() and len(number) > 5:
  146. if ast_server.international_prefix and number[0:len(ast_server.international_prefix)] == ast_server.international_prefix:
  147. number = number[len(ast_server.international_prefix):]
  148. number = '+' + number
  149. elif ast_server.national_prefix and number[0:len(ast_server.national_prefix)] == ast_server.national_prefix:
  150. number = number[len(ast_server.national_prefix):]
  151. number = '+' + ast_server.country_prefix + number
  152. return number
  153. def _get_asterisk_server_from_user(self, cr, uid, user, context=None):
  154. '''Returns an asterisk.server browse object'''
  155. # We check if the user has an Asterisk server configured
  156. if user.asterisk_server_id.id:
  157. ast_server = user.asterisk_server_id
  158. else:
  159. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  160. # If no asterisk server is configured on the user, we take the first one
  161. if not asterisk_server_ids:
  162. raise osv.except_osv(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  163. else:
  164. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  165. return ast_server
  166. def _parse_asterisk_answer(self, cr, uid, sock, end_string='\r\n\r\n', context=None):
  167. '''Parse the answer of the Asterisk Manager Interface'''
  168. answer = ''
  169. data = ''
  170. # TODO : if there is an error, we will stay in the while loop
  171. # ex :
  172. # Response: Error
  173. # Message: Permission denied
  174. while end_string not in data:
  175. data = sock.recv(1024)
  176. if data:
  177. answer += data
  178. # remove end_string from answer
  179. if answer[-len(end_string):] == end_string:
  180. answer = answer[:-len(end_string)]
  181. return answer
  182. def _connect_to_asterisk(self, cr, uid, method='dial', options=None, context=None):
  183. '''
  184. Open the socket to the Asterisk Manager Interface (AMI)
  185. and send instructions to Dial to Asterisk. That's the important function !
  186. '''
  187. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  188. # Note : if I write 'Error' without ' :', it won't get translated...
  189. # I don't understand why !
  190. ast_server = self._get_asterisk_server_from_user(cr, uid, user, context=context)
  191. # We check if the current user has a chan type
  192. if not user.asterisk_chan_type:
  193. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  194. # We check if the current user has an internal number
  195. if not user.internal_number:
  196. raise osv.except_osv(_('Error :'), _('No internal phone number configured for the current user'))
  197. _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.internal_number))
  198. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  199. # Connect to the Asterisk Manager Interface, using IPv6-ready code
  200. try:
  201. res = socket.getaddrinfo(str(ast_server.ip_address), ast_server.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  202. except:
  203. _logger.warning("Can't resolve the DNS of the Asterisk server '%s'" % ast_server.ip_address)
  204. raise osv.except_osv(_('Error :'), _("Can't resolve the DNS of the Asterisk server : '%s'" % ast_server.ip_address))
  205. for result in res:
  206. af, socktype, proto, canonname, sockaddr = result
  207. sock = socket.socket(af, socktype, proto)
  208. try:
  209. sock.connect(sockaddr)
  210. header_received = sock.recv(1024)
  211. _logger.debug('Header received from Asterisk : %s' % header_received)
  212. # Login to Asterisk
  213. login_act = 'Action: login\r\n' + \
  214. 'Events: off\r\n' + \
  215. 'Username: ' + ast_server.login + '\r\n' + \
  216. 'Secret: ' + ast_server.password + '\r\n\r\n'
  217. sock.send(login_act.encode('ascii'))
  218. login_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  219. if 'Response: Success' in login_answer:
  220. _logger.debug("Successful authentification to Asterisk :\n%s" % login_answer)
  221. else:
  222. raise osv.except_osv(_('Error :'), _("Authentification to Asterisk failed :\n%s" % login_answer))
  223. if method == 'dial':
  224. # Convert the phone number in the format that will be sent to Asterisk
  225. erp_number = options.get('erp_number')
  226. if not erp_number:
  227. raise osv.except_osv(_('Error :'), "Hara kiri : you must call the function with erp_number in the options")
  228. ast_number = self._reformat_number(cr, uid, erp_number, ast_server, context=context)
  229. # The user should have a CallerID
  230. if not user.callerid:
  231. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  232. # Dial with Asterisk
  233. originate_act = 'Action: originate\r\n' + \
  234. 'Channel: ' + user.asterisk_chan_type + '/' + user.internal_number + ( ('/' + user.dial_suffix) if user.dial_suffix else '') + '\r\n' + \
  235. 'Priority: ' + str(ast_server.extension_priority) + '\r\n' + \
  236. 'Timeout: ' + str(ast_server.wait_time*1000) + '\r\n' + \
  237. 'CallerId: ' + user.callerid + '\r\n' + \
  238. 'Exten: ' + ast_number + '\r\n' + \
  239. 'Context: ' + ast_server.context + '\r\n'
  240. if ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  241. for server_alertinfo in ast_server.alert_info.split('|'):
  242. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + server_alertinfo.strip() + '\r\n'
  243. if user.alert_info and user.asterisk_chan_type == 'SIP':
  244. for user_alertinfo in user.alert_info.split('|'):
  245. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + user_alertinfo.strip() + '\r\n'
  246. if user.variable:
  247. for user_variable in user.variable.split('|'):
  248. originate_act += 'Variable: ' + user_variable.strip() + '\r\n'
  249. originate_act += '\r\n'
  250. sock.send(originate_act.encode('ascii'))
  251. originate_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  252. if 'Response: Success' in originate_answer:
  253. _logger.debug('Successfull originate command : %s' % originate_answer)
  254. else:
  255. raise osv.except_osv(_('Error :'), _("Click to dial with Asterisk failed :\n%s" % originate_answer))
  256. elif method == "get_calling_number":
  257. status_act = 'Action: Status\r\n\r\n' # TODO : add ActionID
  258. sock.send(status_act.encode('ascii'))
  259. status_answer = self._parse_asterisk_answer(cr, uid, sock, end_string='Event: StatusComplete', context=context).decode('utf-8')
  260. if 'Response: Success' in status_answer:
  261. _logger.debug('Successfull Status command :\n%s' % status_answer)
  262. else:
  263. raise osv.except_osv(_('Error :'), _("Status command to Asterisk failed :\n%s" % status_answer))
  264. # Parse answer
  265. calling_party_number = False
  266. status_answer_split = status_answer.split('\r\n\r\n')
  267. for event in status_answer_split:
  268. string_bridge_match = 'BridgedChannel: ' + user.asterisk_chan_type + '/' + user.internal_number
  269. string_link_match = 'Link: ' + user.asterisk_chan_type + '/' + user.internal_number # Asterisk 1.4 ? Or is it related to the fact that it's an IAX trunk ?
  270. if string_bridge_match in event or string_link_match in event:
  271. _logger.debug("Found a matching Event")
  272. event_split = event.split('\r\n')
  273. for event_line in event_split:
  274. if 'CallerIDNum' in event_line:
  275. line_detail = event_line.split(': ')
  276. if len(line_detail) <> 2:
  277. raise osv.except_osv('Error :', "Hara kiri... this is not possible")
  278. calling_party_number = line_detail[1]
  279. _logger.debug("The calling party number is '%s'" % calling_party_number)
  280. # Logout of Asterisk
  281. sock.send(('Action: Logoff\r\n\r\n').encode('ascii'))
  282. logout_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  283. if 'Response: Goodbye' in logout_answer:
  284. _logger.debug('Successfull logout from Asterisk :\n%s' % logout_answer)
  285. else:
  286. _logger.warning('Logout from Asterisk failed :\n%s' % logout_answer)
  287. # we catch only network problems here
  288. except socket.error:
  289. _logger.warning("Unable to connect to the Asterisk server '%s' IP '%s:%d'" % (ast_server.name, ast_server.ip_address, ast_server.port))
  290. raise osv.except_osv(_('Error :'), _("The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk."))
  291. finally:
  292. sock.close()
  293. if method == 'dial':
  294. _logger.info("Asterisk Click2Dial from %s/%s to %s" % (user.asterisk_chan_type, user.internal_number, ast_number))
  295. return True
  296. elif method == "get_calling_number":
  297. return calling_party_number
  298. else:
  299. return False
  300. asterisk_server()
  301. # Parameters specific for each user
  302. class res_users(osv.osv):
  303. _inherit = "res.users"
  304. _columns = {
  305. 'internal_number': fields.char('Internal number', size=15,
  306. help="User's internal phone number."),
  307. 'dial_suffix': fields.char('User-specific dial suffix', size=15,
  308. help="User-specific dial suffix such as aa=2wb for SCCP auto answer."),
  309. 'callerid': fields.char('Caller ID', size=50,
  310. help="Caller ID used for the calls initiated by this user."),
  311. # You'd probably think : Asterisk should reuse the callerID of sip.conf !
  312. # But it cannot, cf http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  313. 'asterisk_chan_type': fields.selection([
  314. ('SIP', 'SIP'),
  315. ('Local', 'Local'),
  316. ('IAX2', 'IAX2'),
  317. ('DAHDI', 'DAHDI'),
  318. ('Zap', 'Zap'),
  319. ('Skinny', 'Skinny'),
  320. ('MGCP', 'MGCP'),
  321. ('mISDN', 'mISDN'),
  322. ('H323', 'H323'),
  323. ('SCCP', 'SCCP'),
  324. ], 'Asterisk channel type',
  325. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  326. '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. If you want to have several variable headers, separate them with '|'."),
  327. '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 '|'."),
  328. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  329. 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."),
  330. }
  331. _defaults = {
  332. 'asterisk_chan_type': 'SIP',
  333. }
  334. def _check_validity(self, cr, uid, ids):
  335. for user in self.browse(cr, uid, ids):
  336. for check_string in [('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  337. if check_string[1]:
  338. try:
  339. plom = check_string[1].encode('ascii')
  340. except UnicodeEncodeError:
  341. raise osv.except_osv(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  342. return True
  343. _constraints = [
  344. (_check_validity, "Error message in raise", ['internal_number', 'callerid']),
  345. ]
  346. res_users()
  347. class res_partner_address(osv.osv):
  348. _inherit = "res.partner.address"
  349. def _format_phonenumber_to_e164(self, cr, uid, ids, name, arg, context=None):
  350. result = {}
  351. for addr in self.read(cr, uid, ids, ['phone', 'mobile', 'fax'], context=context):
  352. result[addr['id']] = {}
  353. for fromfield, tofield in [('phone', 'phone_e164'), ('mobile', 'mobile_e164'), ('fax', 'fax_e164')]:
  354. if not addr.get(fromfield):
  355. res = False
  356. else:
  357. try:
  358. res = phonenumbers.format_number(phonenumbers.parse(addr.get(fromfield), None), phonenumbers.PhoneNumberFormat.E164)
  359. except Exception, e:
  360. _logger.error("Cannot reformat the phone number '%s' to E.164 format. Error message: %s" % (addr.get(fromfield), e))
  361. _logger.error("You should fix this number and run the wizard 'Reformat all phone numbers' from the menu Settings > Configuration > Asterisk")
  362. # If I raise an exception here, it won't be possible to install
  363. # the module on a DB with bad phone numbers
  364. #raise osv.except_osv(_('Error :'), _("Cannot reformat the phone number '%s' to E.164 format. Error message: %s" % (addr.get(fromfield), e)))
  365. res = False
  366. result[addr['id']][tofield] = res
  367. #print "RESULT _format_phonenumber_to_e164", result
  368. return result
  369. _columns = {
  370. 'phone_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Phone in E.164 format', readonly=True, multi="e164", store={
  371. 'res.partner.address': (lambda self, cr, uid, ids, c={}: ids, ['phone'], 10),
  372. }),
  373. 'mobile_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Mobile in E.164 format', readonly=True, multi="e164", store={
  374. 'res.partner.address': (lambda self, cr, uid, ids, c={}: ids, ['mobile'], 10),
  375. }),
  376. 'fax_e164': fields.function(_format_phonenumber_to_e164, type='char', size=64, string='Fax in E.164 format', readonly=True, multi="e164", store={
  377. 'res.partner.address': (lambda self, cr, uid, ids, c={}: ids, ['fax'], 10),
  378. }),
  379. }
  380. def _reformat_phonenumbers(self, cr, uid, vals, context=None):
  381. """Reformat phone numbers in international format i.e. +33141981242"""
  382. phonefields = ['phone', 'fax', 'mobile']
  383. if any([vals.get(field) for field in phonefields]):
  384. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  385. # country_id on res.company is a fields.function that looks at
  386. # company_id.partner_id.addres(default).country_id
  387. if user.company_id.country_id:
  388. user_countrycode = user.company_id.country_id.code
  389. else:
  390. # 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
  391. raise osv.except_osv(_('Error :'), _("You should set a country on the company '%s'" % user.company_id.name))
  392. #print "user_countrycode=", user_countrycode
  393. for field in phonefields:
  394. if vals.get(field):
  395. try:
  396. res_parse = phonenumbers.parse(vals.get(field), user_countrycode)
  397. except Exception, e:
  398. raise osv.except_osv(_('Error :'), _("Cannot reformat the phone number '%s' to international format. Error message: %s" % (vals.get(field), e)))
  399. #print "res_parse=", res_parse
  400. vals[field] = phonenumbers.format_number(res_parse, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
  401. return vals
  402. def create(self, cr, uid, vals, context=None):
  403. vals_reformated = self._reformat_phonenumbers(cr, uid, vals, context=context)
  404. return super(res_partner_address, self).create(cr, uid, vals_reformated, context=context)
  405. def write(self, cr, uid, ids, vals, context=None):
  406. vals_reformated = self._reformat_phonenumbers(cr, uid, vals, context=context)
  407. return super(res_partner_address, self).write(cr, uid, ids, vals_reformated, context=context)
  408. def dial(self, cr, uid, ids, phone_field=['phone', 'phone_e164'], context=None):
  409. '''Read the number to dial and call _connect_to_asterisk the right way'''
  410. erp_number_read = self.read(cr, uid, ids[0], phone_field, context=context)
  411. erp_number_e164 = erp_number_read[phone_field[1]]
  412. erp_number_display = erp_number_read[phone_field[0]]
  413. # Check if the number to dial is not empty
  414. if not erp_number_display:
  415. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  416. elif erp_number_display and not erp_number_e164:
  417. 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."))
  418. options = {'erp_number': erp_number_e164}
  419. return self.pool.get('asterisk.server')._connect_to_asterisk(cr, uid, method='dial', options=options, context=context)
  420. def action_dial_phone(self, cr, uid, ids, context=None):
  421. '''Function called by the button 'Dial' next to the 'phone' field
  422. in the partner address view'''
  423. return self.dial(cr, uid, ids, phone_field=['phone', 'phone_e164'], context=context)
  424. def action_dial_mobile(self, cr, uid, ids, context=None):
  425. '''Function called by the button 'Dial' next to the 'mobile' field
  426. in the partner address view'''
  427. return self.dial(cr, uid, ids, phone_field=['mobile', 'mobile_e164'], context=context)
  428. def get_name_from_phone_number(self, cr, uid, number, context=None):
  429. '''Function to get name from phone number. Usefull for use from Asterisk
  430. to add CallerID name to incoming calls.
  431. The "scripts/" subdirectory of this module has an AGI script that you can
  432. install on your Asterisk IPBX : the script will be called from the Asterisk
  433. dialplan via the AGI() function and it will use this function via an XML-RPC
  434. request.
  435. '''
  436. res = self.get_partner_from_phone_number(cr, uid, number, context=context)
  437. if res:
  438. return res[2]
  439. else:
  440. return False
  441. def get_partner_from_phone_number(self, cr, uid, number, context=None):
  442. # We check that "number" is really a number
  443. _logger.debug(u"Call get_name_from_phone_number with number = %s" % number)
  444. if not isinstance(number, (str, unicode)):
  445. _logger.warning(u"Number should be a 'str' or 'unicode' but it is a '%s'" % type(number))
  446. return False
  447. _logger.warning(u"Number should only contain digits.")
  448. if not number.isdigit():
  449. return False
  450. # We try to match a phone or mobile number with the same end
  451. pg_seach_number = str('%' + number)
  452. res_ids = self.search(cr, uid, ['|', ('phone_e164', 'ilike', pg_seach_number), ('mobile_e164', 'ilike', pg_seach_number)], context=context)
  453. # TODO : use is_number_match() of the phonenumber lib ?
  454. if len(res_ids) > 1:
  455. _logger.warning(u"There are several partners addresses (IDS = %s) with the same phone number %s" % (str(res_ids), number))
  456. if res_ids:
  457. entry = self.read(cr, uid, res_ids[0], ['name', 'partner_id'], context=context)
  458. _logger.debug(u"Answer get_partner_from_phone_number with name = %s" % entry['name'])
  459. return (entry['id'], entry['partner_id'] and entry['partner_id'][0] or False, entry['name'])
  460. else:
  461. _logger.debug(u"No match for phone number %s" % number)
  462. return False
  463. res_partner_address()
  464. # This module supports multi-company
  465. class res_company(osv.osv):
  466. _inherit = "res.company"
  467. _columns = {
  468. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  469. }
  470. res_company()