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.

1029 lines
39 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Asterisk Click2dial module for OpenERP
  5. # Copyright (C) 2010-2013 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 netsvc
  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 :
  30. # 8d0e1c941cce727c702582f3c9fcd49beb4eeaa4
  31. # so a version after Nov 20th, 2012
  32. from Asterisk import Manager
  33. logger = netsvc.Logger()
  34. class asterisk_server(osv.osv):
  35. """Asterisk server object, to store all the parameters of the Asterisk
  36. IPBXs
  37. """
  38. _name = "asterisk.server"
  39. _description = "Asterisk Servers"
  40. _columns = {
  41. 'name': fields.char(
  42. 'Asterisk server name',
  43. size=50,
  44. required=True,
  45. help="Asterisk server name."
  46. ),
  47. 'active': fields.boolean(
  48. 'Active',
  49. help="The active field allows you to hide the Asterisk server "
  50. "without deleting it."
  51. ),
  52. 'ip_address': fields.char(
  53. 'Asterisk IP addr. or DNS',
  54. size=50,
  55. required=True,
  56. help="IP address or DNS name of the Asterisk server."
  57. ),
  58. 'port': fields.integer(
  59. 'Port',
  60. required=True,
  61. help="TCP port on which the Asterisk Manager Interface listens. "
  62. "Defined in /etc/asterisk/manager.conf on Asterisk."
  63. ),
  64. 'out_prefix': fields.char(
  65. 'Out prefix',
  66. size=4,
  67. help="Prefix to dial to place outgoing calls. "
  68. "If you don't use a prefix to place outgoing calls, "
  69. "leave empty."
  70. ),
  71. 'national_prefix': fields.char(
  72. 'National prefix',
  73. size=4,
  74. help="Prefix for national phone calls "
  75. "(don't include the 'out prefix'). "
  76. "For e.g., in France, the phone numbers look like "
  77. "'01 41 98 12 42' : the National prefix is '0'."
  78. ),
  79. 'international_prefix': fields.char(
  80. 'International prefix',
  81. required=True,
  82. size=4,
  83. help="Prefix to add to make international phone calls "
  84. "(don't include the 'out prefix'). "
  85. "For e.g., in France, the International prefix is '00'."
  86. ),
  87. 'country_prefix': fields.char(
  88. 'My country prefix',
  89. required=True,
  90. size=4,
  91. help="Phone prefix of the country where the Asterisk server is "
  92. "located. For e.g. the phone prefix for France is '33'. "
  93. "If the phone number to dial starts with the "
  94. "'My country prefix', OpenERP will remove the country prefix "
  95. "from the phone number and add the 'out prefix' followed by "
  96. "the 'national prefix'. If the phone number to dial doesn't "
  97. "start with the 'My country prefix', OpenERP will add the "
  98. "'out prefix' followed by the 'international prefix'."
  99. ),
  100. 'login': fields.char(
  101. 'AMI login',
  102. size=30,
  103. required=True,
  104. help="Login that OpenERP will use to communicate with the "
  105. "Asterisk Manager Interface. "
  106. "Refer to /etc/asterisk/manager.conf on your Asterisk server."
  107. ),
  108. 'password': fields.char(
  109. 'AMI password',
  110. size=30,
  111. required=True,
  112. help="Password that Asterisk will use to communicate with the "
  113. "Asterisk Manager Interface. "
  114. "Refer to /etc/asterisk/manager.conf on your Asterisk server."
  115. ),
  116. 'context': fields.char(
  117. 'Dialplan context',
  118. size=50,
  119. required=True,
  120. help="Asterisk dialplan context from which the calls will be "
  121. "made. Refer to /etc/asterisk/extensions.conf on your "
  122. "Asterisk server."
  123. ),
  124. 'wait_time': fields.integer(
  125. 'Wait time (sec)',
  126. required=True,
  127. help="Amount of time (in seconds) Asterisk will try to reach the "
  128. "user's phone before hanging up."
  129. ),
  130. 'extension_priority': fields.integer(
  131. 'Extension priority',
  132. required=True,
  133. help="Priority of the extension in the Asterisk dialplan. "
  134. "Refer to /etc/asterisk/extensions.conf on your Asterisk "
  135. "server."
  136. ),
  137. 'alert_info': fields.char(
  138. 'Alert-Info SIP header',
  139. size=255,
  140. help="Set Alert-Info header in SIP request to user's IP Phone for "
  141. "the click2dial feature. If empty, the Alert-Info header "
  142. "will not be added. You can use it to have a special ring "
  143. "tone for click2dial (a silent one !) or to activate "
  144. "auto-answer for example."
  145. ),
  146. 'number_of_digits_to_match_from_end': fields.integer(
  147. 'Number of digits to match from end',
  148. help='In several situations, the Asterisk-OpenERP connector will '
  149. 'have to find a Partner in OpenERP from a phone number '
  150. 'presented by the calling party. As the phone numbers '
  151. 'presented by your phone operator may not always be '
  152. 'displayed in a standard format, the best method to find the '
  153. 'related Partner in OpenERP is to try to match the end of '
  154. 'the phone numbers of the Partners in OpenERP with the N '
  155. 'last digits of the phone number presented by the calling '
  156. 'party. N is the value you should enter in this field.'
  157. ),
  158. 'company_id': fields.many2one(
  159. 'res.company',
  160. 'Company',
  161. help="Company who uses the Asterisk server."
  162. ),
  163. }
  164. _defaults = {
  165. 'active': lambda *a: True,
  166. 'port': lambda *a: 5038, # Default AMI port
  167. 'out_prefix': lambda *a: '0',
  168. 'national_prefix': lambda *a: '0',
  169. 'international_prefix': lambda *a: '00',
  170. 'extension_priority': lambda *a: 1,
  171. 'wait_time': lambda *a: 15,
  172. 'number_of_digits_to_match_from_end': lambda *a: 9,
  173. }
  174. def _check_validity(self, cr, uid, ids):
  175. for server in self.browse(cr, uid, ids):
  176. country_prefix = ('Country prefix', server.country_prefix)
  177. international_prefix = (
  178. 'International prefix',
  179. server.international_prefix
  180. )
  181. out_prefix = ('Out prefix', server.out_prefix)
  182. national_prefix = ('National prefix', server.national_prefix)
  183. dialplan_context = ('Dialplan context', server.context)
  184. alert_info = ('Alert-Info SIP header', server.alert_info)
  185. login = ('AMI login', server.login)
  186. password = ('AMI password', server.password)
  187. for digit_prefix in [
  188. country_prefix,
  189. international_prefix,
  190. out_prefix,
  191. national_prefix
  192. ]:
  193. if digit_prefix[1] and not digit_prefix[1].isdigit():
  194. raise osv.except_osv(
  195. _('Error :'),
  196. _("Only use digits for the '%s' on the Asterisk "
  197. "server '%s'" % (digit_prefix[0], server.name))
  198. )
  199. if server.wait_time < 1 or server.wait_time > 120:
  200. raise osv.except_osv(
  201. _('Error :'),
  202. _("You should set a 'Wait time' value between 1 and 120 "
  203. "seconds for the Asterisk server '%s'" % server.name)
  204. )
  205. if server.extension_priority < 1:
  206. raise osv.except_osv(
  207. _('Error :'),
  208. _("The 'extension priority' must be a positive value for "
  209. "the Asterisk server '%s'" % server.name)
  210. )
  211. if server.port > 65535 or server.port < 1:
  212. raise osv.except_osv(
  213. _('Error :'),
  214. _("You should set a TCP port between 1 and 65535 for the "
  215. "Asterisk server '%s'" % server.name)
  216. )
  217. if (server.number_of_digits_to_match_from_end > 20
  218. or server.number_of_digits_to_match_from_end < 1):
  219. raise osv.except_osv(
  220. _('Error :'),
  221. _("You should set a 'Number of digits to match from end' "
  222. "between 1 and 20 for the Asterisk server '%s'"
  223. % server.name)
  224. )
  225. for check_string in [
  226. dialplan_context,
  227. alert_info,
  228. login,
  229. password
  230. ]:
  231. if check_string[1]:
  232. try:
  233. check_string[1].encode('ascii')
  234. except UnicodeEncodeError:
  235. raise osv.except_osv(
  236. _('Error :'),
  237. _("The '%s' should only have ASCII caracters for "
  238. "the Asterisk server '%s'"
  239. % (check_string[0], server.name))
  240. )
  241. return True
  242. _constraints = [
  243. (_check_validity, "Error message in raise", [
  244. 'out_prefix',
  245. 'country_prefix',
  246. 'national_prefix',
  247. 'international_prefix',
  248. 'wait_time',
  249. 'extension_priority',
  250. 'port',
  251. 'context',
  252. 'alert_info',
  253. 'login',
  254. 'password',
  255. 'number_of_digits_to_match_from_end'
  256. ]),
  257. ]
  258. def _reformat_number(self, cr, uid, erp_number, ast_server, context=None):
  259. '''
  260. This function is dedicated to the transformation of the number
  261. available in OpenERP to the number that Asterisk should dial.
  262. You may have to inherit this function in another module specific
  263. for your company if you are not happy with the way I reformat
  264. the OpenERP numbers.
  265. '''
  266. error_title_msg = _("Invalid phone number")
  267. invalid_format_msg = _("The phone number is not written in valid "
  268. "format.")
  269. # Let's call the variable tmp_number now
  270. tmp_number = erp_number
  271. logger.notifyChannel(
  272. 'click2dial',
  273. netsvc.LOG_DEBUG,
  274. 'Number before reformat = %s' % tmp_number
  275. )
  276. # Check if empty
  277. if not tmp_number:
  278. raise osv.except_osv(error_title_msg, invalid_format_msg)
  279. # Before starting to use prefix, we convert empty prefix whose value
  280. # is False to an empty string
  281. country_prefix = ast_server.country_prefix or ''
  282. national_prefix = ast_server.national_prefix or ''
  283. international_prefix = ast_server.international_prefix or ''
  284. out_prefix = ast_server.out_prefix or ''
  285. # Maybe one day we will use
  286. # phonenumbers.format_out_of_country_calling_number(
  287. # phonenumbers.parse('<phone_number_e164', None), 'FR'
  288. # )
  289. # The country code seems to be OK with the ones of OpenERP
  290. # But it returns sometimes numbers with '-'...
  291. # we have to investigate this first
  292. # International format
  293. if tmp_number[0] != '+':
  294. raise # This should never happen
  295. # Remove the starting '+' of the number
  296. tmp_number = tmp_number.replace('+', '')
  297. logger.notifyChannel(
  298. 'click2dial',
  299. netsvc.LOG_DEBUG,
  300. 'Number after removal of special char = %s' % tmp_number
  301. )
  302. # At this stage, 'tmp_number' should only contain digits
  303. if not tmp_number.isdigit():
  304. raise osv.except_osv(error_title_msg, invalid_format_msg)
  305. logger.notifyChannel(
  306. 'click2dial',
  307. netsvc.LOG_DEBUG,
  308. 'Country prefix = %s' % country_prefix
  309. )
  310. if country_prefix == tmp_number[0:len(country_prefix)]:
  311. # If the number is a national number,
  312. # remove 'my country prefix' and add 'national prefix'
  313. tmp_number = (national_prefix
  314. + tmp_number[len(country_prefix):len(tmp_number)])
  315. logger.notifyChannel(
  316. 'click2dial',
  317. netsvc.LOG_DEBUG,
  318. 'National prefix = %s - Number with national prefix = %s'
  319. % (national_prefix, tmp_number)
  320. )
  321. else:
  322. # If the number is an international number,
  323. # add 'international prefix'
  324. tmp_number = international_prefix + tmp_number
  325. logger.notifyChannel(
  326. 'click2dial',
  327. netsvc.LOG_DEBUG,
  328. 'International prefix = %s - Number with international '
  329. 'prefix = %s' % (international_prefix, tmp_number)
  330. )
  331. # Add 'out prefix' to all numbers
  332. tmp_number = out_prefix + tmp_number
  333. logger.notifyChannel(
  334. 'click2dial',
  335. netsvc.LOG_DEBUG,
  336. 'Out prefix = %s - Number to be sent to Asterisk = %s'
  337. % (out_prefix, tmp_number)
  338. )
  339. return tmp_number
  340. def _convert_number_to_international_format(self, cr, uid, number,
  341. ast_server, context=None):
  342. """Convert the number presented by the phone network to a number
  343. in international format e.g. +33141981242
  344. """
  345. if number and number.isdigit() and len(number) > 5:
  346. if (ast_server.international_prefix
  347. and number[0:len(ast_server.international_prefix)]
  348. == ast_server.international_prefix):
  349. number = number[len(ast_server.international_prefix):]
  350. number = '+' + number
  351. elif (ast_server.national_prefix
  352. and number[0:len(ast_server.national_prefix)]
  353. == ast_server.national_prefix):
  354. number = number[len(ast_server.national_prefix):]
  355. number = '+' + ast_server.country_prefix + number
  356. return number
  357. def _get_asterisk_server_from_user(self, cr, uid, context=None):
  358. '''Returns an asterisk.server browse object'''
  359. # We check if the user has an Asterisk server configured
  360. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  361. if user.asterisk_server_id.id:
  362. ast_server = user.asterisk_server_id
  363. else:
  364. asterisk_server_ids = self.search(
  365. cr,
  366. uid,
  367. [('company_id', '=', user.company_id.id)],
  368. context=context
  369. )
  370. # If no asterisk server is configured on the user,
  371. # we take the first one
  372. if not asterisk_server_ids:
  373. raise osv.except_osv(
  374. _('Error :'),
  375. _("No Asterisk server configured for the company '%s'.")
  376. % user.company_id.name
  377. )
  378. else:
  379. ast_server = self.browse(
  380. cr, uid, asterisk_server_ids[0], context=context
  381. )
  382. return ast_server
  383. def _connect_to_asterisk(self, cr, uid, context=None):
  384. '''
  385. Open the connection to the asterisk manager
  386. Returns an instance of the Asterisk Manager
  387. '''
  388. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  389. # Note : if I write 'Error' without ' :', it won't get translated...
  390. # I don't understand why !
  391. ast_server = self._get_asterisk_server_from_user(
  392. cr, uid, context=context
  393. )
  394. # We check if the current user has a chan type
  395. if not user.asterisk_chan_type:
  396. raise osv.except_osv(
  397. _('Error :'),
  398. _('No channel type configured for the current user.')
  399. )
  400. # We check if the current user has an internal number
  401. if not user.resource:
  402. raise osv.except_osv(
  403. _('Error :'),
  404. _('No resource name configured for the current user')
  405. )
  406. logger.notifyChannel(
  407. 'click2dial',
  408. netsvc.LOG_DEBUG,
  409. "User's phone : %s/%s" % (user.asterisk_chan_type, user.resource)
  410. )
  411. logger.notifyChannel(
  412. 'click2dial',
  413. netsvc.LOG_DEBUG,
  414. "Asterisk server = %s:%d"
  415. % (ast_server.ip_address, ast_server.port)
  416. )
  417. # Connect to the Asterisk Manager Interface
  418. try:
  419. ast_manager = Manager.Manager(
  420. (ast_server.ip_address, ast_server.port),
  421. ast_server.login,
  422. ast_server.password
  423. )
  424. except Exception, e:
  425. logger.notifyChannel(
  426. 'click2dial',
  427. netsvc.LOG_ERROR,
  428. "Error in the Originate request to Asterisk server %s"
  429. % ast_server.ip_address
  430. )
  431. logger.notifyChannel(
  432. 'click2dial',
  433. netsvc.LOG_ERROR,
  434. "Here is the detail of the error : '%s'" % unicode(e)
  435. )
  436. raise osv.except_osv(
  437. _('Error :'),
  438. _("Problem in the request from OpenERP to Asterisk. Here is "
  439. "the detail of the error: '%s'" % unicode(e))
  440. )
  441. return (user, ast_server, ast_manager)
  442. def _dial_with_asterisk(self, cr, uid, erp_number, context=None):
  443. if not erp_number:
  444. raise osv.except_osv(
  445. _('Error :'),
  446. "Hara kiri : you must call the function with erp_number"
  447. )
  448. user, ast_server, ast_manager = self._connect_to_asterisk(
  449. cr, uid, context=context
  450. )
  451. ast_number = self._reformat_number(
  452. cr, uid, erp_number, ast_server, context=context
  453. )
  454. # The user should have a CallerID
  455. if not user.callerid:
  456. raise osv.except_osv(
  457. _('Error :'),
  458. _('No callerID configured for the current user')
  459. )
  460. variable = []
  461. if user.asterisk_chan_type == 'SIP':
  462. # We can only have one alert-info header in a SIP request
  463. if user.alert_info:
  464. variable.append('SIPAddHeader=Alert-Info: ' + user.alert_info)
  465. elif ast_server.alert_info:
  466. variable.append(
  467. 'SIPAddHeader=Alert-Info: ' + ast_server.alert_info
  468. )
  469. if user.variable:
  470. for user_variable in user.variable.split('|'):
  471. variable.append(user_variable.strip())
  472. try:
  473. ast_manager.Originate(
  474. user.asterisk_chan_type + '/' + user.resource +
  475. (('/' + user.dial_suffix) if user.dial_suffix else ''),
  476. context=ast_server.context,
  477. extension=ast_number,
  478. priority=str(ast_server.extension_priority),
  479. timeout=str(ast_server.wait_time * 1000),
  480. caller_id=user.callerid,
  481. variable=variable)
  482. except Exception, e:
  483. logger.notifyChannel(
  484. 'click2dial',
  485. netsvc.LOG_ERROR,
  486. "Error in the Originate request to Asterisk server %s"
  487. % ast_server.ip_address
  488. )
  489. logger.notifyChannel(
  490. 'click2dial',
  491. netsvc.LOG_ERROR,
  492. "Here is the detail of the error : '%s'" % unicode(e)
  493. )
  494. raise osv.except_osv(
  495. _('Error :'),
  496. _("Click to dial with Asterisk failed.\n"
  497. "Here is the error: '%s'" % unicode(e))
  498. )
  499. finally:
  500. ast_manager.Logoff()
  501. return True
  502. def _get_calling_number(self, cr, uid, context=None):
  503. user, ast_server, ast_manager = self._connect_to_asterisk(
  504. cr, uid, context=context
  505. )
  506. calling_party_number = False
  507. try:
  508. list_chan = ast_manager.Status()
  509. # from pprint import pprint
  510. # pprint(list_chan)
  511. logger.notifyChannel(
  512. 'click2dial',
  513. netsvc.LOG_DEBUG,
  514. "Result of Status AMI request: %s" % list_chan
  515. )
  516. for chan in list_chan.values():
  517. sip_account = user.asterisk_chan_type + '/' + user.resource
  518. if (chan.get('ChannelState') == '4' # 4 = Ring
  519. and chan.get('ConnectedLineNum')
  520. == user.internal_number):
  521. logger.notifyChannel(
  522. 'click2dial',
  523. netsvc.LOG_DEBUG,
  524. "Found a matching Event in 'Ring' state"
  525. )
  526. calling_party_number = chan.get('CallerIDNum')
  527. break
  528. if (chan.get('ChannelState') == '6' # 6 = Up
  529. and sip_account in chan.get('BridgedChannel', '')):
  530. logger.notifyChannel(
  531. 'click2dial',
  532. netsvc.LOG_DEBUG,
  533. "Found a matching Event in 'Up' state"
  534. )
  535. calling_party_number = chan.get('CallerIDNum')
  536. break
  537. # Compatibility with Asterisk 1.4
  538. if (chan.get('State') == 'Up'
  539. and sip_account in chan.get('Link', '')):
  540. logger.notifyChannel(
  541. 'click2dial',
  542. netsvc.LOG_DEBUG,
  543. "Found a matching Event in 'Up' state"
  544. )
  545. calling_party_number = chan.get('CallerIDNum')
  546. break
  547. except Exception, e:
  548. logger.notifyChannel(
  549. 'click2dial',
  550. netsvc.LOG_ERROR,
  551. "Error in the Status request to Asterisk server %s"
  552. % ast_server.ip_address
  553. )
  554. logger.notifyChannel(
  555. 'click2dial',
  556. netsvc.LOG_ERROR,
  557. "Here is the detail of the error : '%s'" % unicode(e)
  558. )
  559. raise osv.except_osv(
  560. _('Error :'),
  561. _("Can't get calling number from Asterisk.\n"
  562. "Here is the error: '%s'" % unicode(e))
  563. )
  564. finally:
  565. ast_manager.Logoff()
  566. logger.notifyChannel(
  567. 'click2dial',
  568. netsvc.LOG_DEBUG,
  569. "The calling party number is '%s'" % calling_party_number
  570. )
  571. return calling_party_number
  572. asterisk_server()
  573. # Parameters specific for each user
  574. class res_users(osv.osv):
  575. _inherit = "res.users"
  576. _columns = {
  577. 'internal_number': fields.char(
  578. 'Internal number',
  579. size=15,
  580. help="User's internal phone number."
  581. ),
  582. 'dial_suffix': fields.char(
  583. 'User-specific dial suffix',
  584. size=15,
  585. help="User-specific dial suffix such as aa=2wb for SCCP auto "
  586. "answer."
  587. ),
  588. 'callerid': fields.char(
  589. 'Caller ID',
  590. size=50,
  591. help="Caller ID used for the calls initiated by this user."
  592. ),
  593. # You'd probably think: Asterisk should reuse the callerID of sip.conf!
  594. # But it cannot, cf
  595. # lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  596. 'asterisk_chan_type': fields.selection(
  597. [
  598. ('SIP', 'SIP'),
  599. ('IAX2', 'IAX2'),
  600. ('DAHDI', 'DAHDI'),
  601. ('Zap', 'Zap'),
  602. ('Skinny', 'Skinny'),
  603. ('MGCP', 'MGCP'),
  604. ('mISDN', 'mISDN'),
  605. ('H323', 'H323'),
  606. ('SCCP', 'SCCP'),
  607. ],
  608. 'Asterisk channel type',
  609. help="Asterisk channel type, as used in the Asterisk dialplan. "
  610. "If the user has a regular IP phone, the channel type is "
  611. "'SIP'."
  612. ),
  613. 'resource': fields.char(
  614. 'Resource name',
  615. size=64,
  616. help="Resource name for the channel type selected. For example, "
  617. "if you use 'Dial(SIP/phone1)' in your Asterisk dialplan to "
  618. "ring the SIP phone of this user, then the resource name for "
  619. "this user is 'phone1'. For a SIP phone, the phone number "
  620. "is often used as resource name, but not always."
  621. ),
  622. 'alert_info': fields.char(
  623. 'User-specific Alert-Info SIP header',
  624. size=255,
  625. help="Set a user-specific Alert-Info header in SIP request to "
  626. "user's IP Phone for the click2dial feature. If empty, the "
  627. "Alert-Info header will not be added. You can use it to have "
  628. "a special ring tone for click2dial (a silent one !) or to "
  629. "activate auto-answer for example."
  630. ),
  631. 'variable': fields.char(
  632. 'User-specific Variable',
  633. size=255,
  634. help="Set a user-specific 'Variable' field in the Asterisk "
  635. "Manager Interface 'originate' request for the click2dial "
  636. "feature. If you want to have several variable headers, "
  637. "separate them with '|'."
  638. ),
  639. 'asterisk_server_id': fields.many2one(
  640. 'asterisk.server',
  641. 'Asterisk server',
  642. help="Asterisk server on which the user's phone is connected. "
  643. "If you leave this field empty, it will use the first "
  644. "Asterisk server of the user's company."
  645. ),
  646. }
  647. _defaults = {
  648. 'asterisk_chan_type': lambda *a: 'SIP',
  649. }
  650. def _check_validity(self, cr, uid, ids):
  651. for user in self.browse(cr, uid, ids):
  652. for check_string in [
  653. ('Resource name', user.resource),
  654. ('Internal number', user.internal_number),
  655. ('Caller ID', user.callerid)
  656. ]:
  657. if check_string[1]:
  658. try:
  659. check_string[1].encode('ascii')
  660. except UnicodeEncodeError:
  661. raise osv.except_osv(
  662. _('Error :'),
  663. _("The '%s' for the user '%s' should only have "
  664. "ASCII caracters" % (check_string[0], user.name))
  665. )
  666. return True
  667. _constraints = [
  668. (_check_validity, "Error message in raise", [
  669. 'resource',
  670. 'internal_number',
  671. 'callerid'
  672. ]),
  673. ]
  674. res_users()
  675. class res_partner_address(osv.osv):
  676. _inherit = "res.partner.address"
  677. def _format_phonenumber_to_e164(self, cr, uid, ids, name, arg,
  678. context=None):
  679. result = {}
  680. for addr in self.read(cr, uid, ids, ['phone', 'mobile', 'fax'],
  681. context=context):
  682. result[addr['id']] = {}
  683. for fromfield, tofield in [
  684. ('phone', 'phone_e164'),
  685. ('mobile', 'mobile_e164'),
  686. ('fax', 'fax_e164')
  687. ]:
  688. if not addr.get(fromfield):
  689. res = False
  690. else:
  691. try:
  692. res = phonenumbers.format_number(
  693. phonenumbers.parse(addr.get(fromfield), None),
  694. phonenumbers.PhoneNumberFormat.E164
  695. )
  696. except Exception, e:
  697. logger.notifyChannel(
  698. 'click2dial',
  699. netsvc.LOG_ERROR,
  700. "Cannot reformat the phone number '%s' to E.164 "
  701. "format. Error message: %s"
  702. % (addr.get(fromfield), e)
  703. )
  704. logger.notifyChannel(
  705. 'click2dial',
  706. netsvc.LOG_ERROR,
  707. "You should fix this number and run the wizard "
  708. "'Reformat all phone numbers' from the menu "
  709. "Settings > Configuration > Asterisk"
  710. )
  711. # If I raise an exception here, it won't be possible to
  712. # install the module on a DB with bad phone numbers
  713. res = False
  714. result[addr['id']][tofield] = res
  715. return result
  716. _columns = {
  717. 'phone_e164': fields.function(
  718. _format_phonenumber_to_e164,
  719. type='char',
  720. size=64,
  721. string='Phone in E.164 format',
  722. method=True,
  723. readonly=True,
  724. multi="e164",
  725. store={
  726. 'res.partner.address': (lambda self, cr, uid, ids, c=None:
  727. ids, ['phone'], 10),
  728. }
  729. ),
  730. 'mobile_e164': fields.function(
  731. _format_phonenumber_to_e164,
  732. type='char',
  733. size=64,
  734. string='Mobile in E.164 format',
  735. method=True,
  736. readonly=True,
  737. multi="e164",
  738. store={
  739. 'res.partner.address': (lambda self, cr, uid, ids, c=None:
  740. ids, ['mobile'], 10),
  741. }
  742. ),
  743. 'fax_e164': fields.function(
  744. _format_phonenumber_to_e164,
  745. type='char',
  746. size=64,
  747. string='Fax in E.164 format',
  748. method=True,
  749. readonly=True,
  750. multi="e164",
  751. store={
  752. 'res.partner.address': (lambda self, cr, uid, ids, c=None:
  753. ids, ['fax'], 10),
  754. }
  755. ),
  756. }
  757. def _reformat_phonenumbers(self, cr, uid, vals, context=None):
  758. """Reformat phone numbers in international format i.e. +33141981242"""
  759. phonefields = ['phone', 'fax', 'mobile']
  760. if any([vals.get(field) for field in phonefields]):
  761. user = self.pool.get('res.users').browse(
  762. cr, uid, uid, context=context
  763. )
  764. # country_id on res.company is a fields.function that looks at
  765. # company_id.partner_id.addres(default).country_id
  766. if user.company_id.partner_id.country:
  767. user_countrycode = user.company_id.partner_id.country.code
  768. else:
  769. # We need to raise an exception here because, if we pass None
  770. # as second arg of phonenumbers.parse(), it will raise an
  771. # exception when you try to enter a phone number in national
  772. # format... so it's better to raise the exception here
  773. raise osv.except_osv(
  774. _('Error :'),
  775. _("You should set a country on the company '%s'"
  776. % user.company_id.name)
  777. )
  778. for field in phonefields:
  779. if vals.get(field):
  780. try:
  781. res_parse = phonenumbers.parse(
  782. vals.get(field),
  783. user_countrycode
  784. )
  785. except Exception, e:
  786. raise osv.except_osv(
  787. _('Error :'),
  788. _("Cannot reformat the phone number '%s' to "
  789. "international format. Error message: %s"
  790. % (vals.get(field), e))
  791. )
  792. vals[field] = phonenumbers.format_number(
  793. res_parse,
  794. phonenumbers.PhoneNumberFormat.INTERNATIONAL
  795. )
  796. return vals
  797. def create(self, cr, uid, vals, context=None):
  798. vals_reformated = self._reformat_phonenumbers(
  799. cr, uid, vals, context=context
  800. )
  801. return super(res_partner_address, self).create(
  802. cr, uid, vals_reformated, context=context
  803. )
  804. def write(self, cr, uid, ids, vals, context=None):
  805. vals_reformated = self._reformat_phonenumbers(
  806. cr, uid, vals, context=context
  807. )
  808. return super(res_partner_address, self).write(
  809. cr, uid, ids, vals_reformated, context=context
  810. )
  811. def dial(self, cr, uid, ids, phone_field=None, context=None):
  812. """Read the number to dial and call _connect_to_asterisk the
  813. right way
  814. """
  815. if phone_field is None:
  816. phone_field = ['phone', 'phone_e164']
  817. erp_number_read = self.read(
  818. cr, uid, ids[0], phone_field, context=context
  819. )
  820. erp_number_e164 = erp_number_read[phone_field[1]]
  821. erp_number_display = erp_number_read[phone_field[0]]
  822. # Check if the number to dial is not empty
  823. if not erp_number_display:
  824. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  825. elif erp_number_display and not erp_number_e164:
  826. raise osv.except_osv(
  827. _('Error :'),
  828. _("The phone number isn't stored in the standard E.164 "
  829. "format. Try to run the wizard 'Reformat all phone numbers' "
  830. "from the menu Settings > Configuration > Asterisk.")
  831. )
  832. return self.pool.get('asterisk.server')._dial_with_asterisk(
  833. cr, uid, erp_number_e164, context=context
  834. )
  835. def action_dial_phone(self, cr, uid, ids, context=None):
  836. """Function called by the button 'Dial' next to the 'phone' field
  837. in the partner address view
  838. """
  839. return self.dial(
  840. cr, uid, ids, phone_field=['phone', 'phone_e164'], context=context
  841. )
  842. def action_dial_mobile(self, cr, uid, ids, context=None):
  843. """Function called by the button 'Dial' next to the 'mobile' field
  844. in the partner address view
  845. """
  846. return self.dial(
  847. cr, uid, ids, phone_field=['mobile', 'mobile_e164'],
  848. context=context
  849. )
  850. def get_name_from_phone_number(self, cr, uid, number, context=None):
  851. """Function to get name from phone number. Useful for use from Asterisk
  852. to add CallerID name to incoming calls.
  853. The "scripts/" subdirectory of this module has an AGI script that you
  854. can install on your Asterisk IPBX : the script will be called from the
  855. Asterisk dialplan via the AGI() function and it will use this function
  856. via an XML-RPC request.
  857. """
  858. res = self.get_partner_from_phone_number(
  859. cr, uid, number, context=context
  860. )
  861. if res:
  862. return res[2]
  863. else:
  864. return False
  865. def get_partner_from_phone_number(self, cr, uid, presented_number,
  866. context=None):
  867. # We check that "presented_number" is really a number
  868. logger.notifyChannel(
  869. 'click2dial',
  870. netsvc.LOG_DEBUG,
  871. u"Call get_name_from_phone_number with number = %s"
  872. % presented_number
  873. )
  874. if not isinstance(presented_number, (str, unicode)):
  875. logger.notifyChannel(
  876. 'click2dial',
  877. netsvc.LOG_WARNING,
  878. u"Number '%s' should be a 'str' or 'unicode' but it is a '%s'"
  879. % (presented_number, type(presented_number))
  880. )
  881. return False
  882. if not presented_number.isdigit():
  883. logger.notifyChannel(
  884. 'click2dial',
  885. netsvc.LOG_WARNING,
  886. u"Number '%s' should only contain digits." % presented_number
  887. )
  888. return False
  889. ast_server_obj = self.pool.get('asterisk.server')
  890. ast_server = ast_server_obj._get_asterisk_server_from_user(
  891. cr, uid, context=context
  892. )
  893. nr_digits_to_match_from_end = (
  894. ast_server.number_of_digits_to_match_from_end
  895. )
  896. if len(presented_number) >= nr_digits_to_match_from_end:
  897. end_number_to_match = presented_number[
  898. -nr_digits_to_match_from_end:len(presented_number)
  899. ]
  900. else:
  901. end_number_to_match = presented_number
  902. logger.notifyChannel(
  903. 'click2dial',
  904. netsvc.LOG_DEBUG,
  905. "Will search phone and mobile numbers in res.partner ending with "
  906. "'%s'" % end_number_to_match
  907. )
  908. # We try to match a phone or mobile number with the same end
  909. pg_seach_number = str('%' + end_number_to_match)
  910. res_ids = self.search(cr, uid, [
  911. '|',
  912. ('phone_e164', 'ilike', pg_seach_number),
  913. ('mobile_e164', 'ilike', pg_seach_number)
  914. ], context=context)
  915. # TODO : use is_number_match() of the phonenumber lib ?
  916. if len(res_ids) > 1:
  917. logger.notifyChannel(
  918. 'click2dial',
  919. netsvc.LOG_WARNING,
  920. u"There are several partners addresses (IDS = %s) with a "
  921. u"phone number ending with '%s'"
  922. % (str(res_ids), end_number_to_match)
  923. )
  924. if res_ids:
  925. entry = self.read(
  926. cr, uid, res_ids[0], ['name', 'partner_id'], context=context
  927. )
  928. logger.notifyChannel(
  929. 'click2dial',
  930. netsvc.LOG_DEBUG,
  931. u"Answer get_partner_from_phone_number with name = %s"
  932. % entry['name']
  933. )
  934. return (
  935. entry['id'],
  936. entry['partner_id']
  937. and entry['partner_id'][0]
  938. or False, entry['name']
  939. )
  940. else:
  941. logger.notifyChannel(
  942. 'click2dial',
  943. netsvc.LOG_DEBUG,
  944. u"No match for end of phone number '%s'" % end_number_to_match
  945. )
  946. return False
  947. res_partner_address()
  948. # This module supports multi-company
  949. class res_company(osv.osv):
  950. _inherit = "res.company"
  951. _columns = {
  952. 'asterisk_server_ids': fields.one2many(
  953. 'asterisk.server',
  954. 'company_id',
  955. 'Asterisk servers',
  956. help="List of Asterisk servers."
  957. )
  958. }
  959. res_company()