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.

486 lines
20 KiB

  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 openerp.osv import fields, orm
  22. from openerp.tools.translate import _
  23. import logging
  24. # Lib for phone number reformating -> pip install phonenumbers
  25. import phonenumbers
  26. # Lib py-asterisk from http://code.google.com/p/py-asterisk/
  27. # -> pip install py-Asterisk
  28. from Asterisk import Manager
  29. _logger = logging.getLogger(__name__)
  30. class asterisk_server(orm.Model):
  31. '''Asterisk server object, stores the parameters of the Asterisk IPBXs'''
  32. _name = "asterisk.server"
  33. _description = "Asterisk Servers"
  34. _columns = {
  35. 'name': fields.char('Asterisk Server Name', size=50, required=True),
  36. 'active': fields.boolean(
  37. 'Active', help="The active field allows you to hide the Asterisk "
  38. "server without deleting it."),
  39. 'ip_address': fields.char(
  40. 'Asterisk IP address or DNS', size=50, required=True,
  41. help="IP address or DNS name of the Asterisk server."),
  42. 'port': fields.integer(
  43. 'Port', required=True,
  44. help="TCP port on which the Asterisk Manager Interface listens. "
  45. "Defined in /etc/asterisk/manager.conf on Asterisk."),
  46. 'out_prefix': fields.char(
  47. 'Out Prefix', size=4, help="Prefix to dial to make outgoing "
  48. "calls. If you don't use a prefix to make outgoing calls, "
  49. "leave empty."),
  50. 'login': fields.char(
  51. 'AMI Login', size=30, required=True,
  52. help="Login that OpenERP will use to communicate with the "
  53. "Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf "
  54. "on your Asterisk server."),
  55. 'password': fields.char(
  56. 'AMI Password', size=30, required=True,
  57. help="Password that OpenERP will use to communicate with the "
  58. "Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf "
  59. "on your Asterisk server."),
  60. 'context': fields.char(
  61. 'Dialplan Context', size=50, required=True,
  62. help="Asterisk dialplan context from which the calls will be "
  63. "made. Refer to /etc/asterisk/extensions.conf on your Asterisk "
  64. "server."),
  65. 'wait_time': fields.integer(
  66. 'Wait Time (sec)', required=True,
  67. help="Amount of time (in seconds) Asterisk will try to reach "
  68. "the user's phone before hanging up."),
  69. 'extension_priority': fields.integer(
  70. 'Extension Priority', required=True,
  71. help="Priority of the extension in the Asterisk dialplan. Refer "
  72. "to /etc/asterisk/extensions.conf on your Asterisk server."),
  73. 'alert_info': fields.char(
  74. 'Alert-Info SIP Header', size=255,
  75. help="Set Alert-Info header in SIP request to user's IP Phone "
  76. "for the click2dial feature. If empty, the Alert-Info header "
  77. "will not be added. You can use it to have a special ring tone "
  78. "for click2dial (a silent one !) or to activate auto-answer "
  79. "for example."),
  80. 'company_id': fields.many2one(
  81. 'res.company', 'Company',
  82. help="Company who uses the Asterisk server."),
  83. }
  84. _defaults = {
  85. 'active': True,
  86. 'port': 5038, # Default AMI port
  87. 'extension_priority': 1,
  88. 'wait_time': 15,
  89. 'company_id': lambda self, cr, uid, context:
  90. self.pool['res.company']._company_default_get(
  91. cr, uid, 'asterisk.server', context=context),
  92. }
  93. def _check_validity(self, cr, uid, ids):
  94. for server in self.browse(cr, uid, ids):
  95. out_prefix = ('Out prefix', server.out_prefix)
  96. dialplan_context = ('Dialplan context', server.context)
  97. alert_info = ('Alert-Info SIP header', server.alert_info)
  98. login = ('AMI login', server.login)
  99. password = ('AMI password', server.password)
  100. if out_prefix[1] and not out_prefix[1].isdigit():
  101. raise orm.except_orm(
  102. _('Error:'),
  103. _("Only use digits for the '%s' on the Asterisk server "
  104. "'%s'" % (out_prefix[0], server.name)))
  105. if server.wait_time < 1 or server.wait_time > 120:
  106. raise orm.except_orm(
  107. _('Error:'),
  108. _("You should set a 'Wait time' value between 1 and 120 "
  109. "seconds for the Asterisk server '%s'" % server.name))
  110. if server.extension_priority < 1:
  111. raise orm.except_orm(
  112. _('Error:'),
  113. _("The 'extension priority' must be a positive value for "
  114. "the Asterisk server '%s'" % server.name))
  115. if server.port > 65535 or server.port < 1:
  116. raise orm.except_orm(
  117. _('Error:'),
  118. _("You should set a TCP port between 1 and 65535 for the "
  119. "Asterisk server '%s'" % server.name))
  120. for check_str in [dialplan_context, alert_info, login, password]:
  121. if check_str[1]:
  122. try:
  123. check_str[1].encode('ascii')
  124. except UnicodeEncodeError:
  125. raise orm.except_orm(
  126. _('Error:'),
  127. _("The '%s' should only have ASCII caracters for "
  128. "the Asterisk server '%s'"
  129. % (check_str[0], server.name)))
  130. return True
  131. _constraints = [(
  132. _check_validity,
  133. "Error message in raise",
  134. [
  135. 'out_prefix', 'wait_time', 'extension_priority', 'port',
  136. 'context', 'alert_info', 'login', 'password']
  137. )]
  138. def _reformat_number(
  139. self, cr, uid, erp_number, ast_server=None, context=None):
  140. '''
  141. This function is dedicated to the transformation of the number
  142. available in OpenERP to the number that Asterisk should dial.
  143. You may have to inherit this function in another module specific
  144. for your company if you are not happy with the way I reformat
  145. the OpenERP numbers.
  146. '''
  147. assert(erp_number), 'Missing phone number'
  148. _logger.debug('Number before reformat = %s' % erp_number)
  149. if not ast_server:
  150. ast_server = self._get_asterisk_server_from_user(
  151. cr, uid, context=context)
  152. # erp_number are supposed to be in E.164 format, so no need to
  153. # give a country code here
  154. parsed_num = phonenumbers.parse(erp_number, None)
  155. country_code = ast_server.company_id.country_id.code
  156. assert(country_code), 'Missing country on company'
  157. _logger.debug('Country code = %s' % country_code)
  158. to_dial_number = phonenumbers.format_out_of_country_calling_number(
  159. parsed_num, country_code.upper()).replace(' ', '').replace('-', '')
  160. # Add 'out prefix' to all numbers
  161. if ast_server.out_prefix:
  162. _logger.debug('Out prefix = %s' % ast_server.out_prefix)
  163. to_dial_number = '%s%s' % (ast_server.out_prefix, to_dial_number)
  164. _logger.debug('Number to be sent to Asterisk = %s' % to_dial_number)
  165. return to_dial_number
  166. def _get_asterisk_server_from_user(self, cr, uid, context=None):
  167. '''Returns an asterisk.server browse object'''
  168. # We check if the user has an Asterisk server configured
  169. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  170. if user.asterisk_server_id.id:
  171. ast_server = user.asterisk_server_id
  172. else:
  173. asterisk_server_ids = self.search(
  174. cr, uid, [('company_id', '=', user.company_id.id)],
  175. context=context)
  176. # If the user doesn't have an asterisk server,
  177. # we take the first one of the user's company
  178. if not asterisk_server_ids:
  179. raise orm.except_orm(
  180. _('Error:'),
  181. _("No Asterisk server configured for the company '%s'.")
  182. % user.company_id.name)
  183. else:
  184. ast_server = self.browse(
  185. cr, uid, asterisk_server_ids[0], context=context)
  186. return ast_server
  187. def _connect_to_asterisk(self, cr, uid, context=None):
  188. '''
  189. Open the connection to the Asterisk Manager
  190. Returns an instance of the Asterisk Manager
  191. '''
  192. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  193. ast_server = self._get_asterisk_server_from_user(
  194. cr, uid, context=context)
  195. # We check if the current user has a chan type
  196. if not user.asterisk_chan_type:
  197. raise orm.except_orm(
  198. _('Error:'),
  199. _('No channel type configured for the current user.'))
  200. # We check if the current user has an internal number
  201. if not user.resource:
  202. raise orm.except_orm(
  203. _('Error:'),
  204. _('No resource name configured for the current user'))
  205. _logger.debug(
  206. "User's phone: %s/%s" % (user.asterisk_chan_type, user.resource))
  207. _logger.debug(
  208. "Asterisk server: %s:%d"
  209. % (ast_server.ip_address, ast_server.port))
  210. # Connect to the Asterisk Manager Interface
  211. try:
  212. ast_manager = Manager.Manager(
  213. (ast_server.ip_address, ast_server.port),
  214. ast_server.login, ast_server.password)
  215. except Exception, e:
  216. _logger.error(
  217. "Error in the request to the Asterisk Manager Interface %s"
  218. % ast_server.ip_address)
  219. _logger.error("Here is the error message: %s" % e)
  220. raise orm.except_orm(
  221. _('Error:'),
  222. _("Problem in the request from OpenERP to Asterisk. "
  223. "Here is the error message: %s" % e))
  224. return False
  225. return (user, ast_server, ast_manager)
  226. def test_ami_connection(self, cr, uid, ids, context=None):
  227. assert len(ids) == 1, 'Only 1 ID'
  228. ast_server = self.browse(cr, uid, ids[0], context=context)
  229. try:
  230. ast_manager = Manager.Manager(
  231. (ast_server.ip_address, ast_server.port),
  232. ast_server.login,
  233. ast_server.password)
  234. except Exception, e:
  235. raise orm.except_orm(
  236. _("Connection Test Failed!"),
  237. _("Here is the error message: %s" % e))
  238. finally:
  239. try:
  240. if ast_manager:
  241. ast_manager.Logoff()
  242. except Exception:
  243. pass
  244. raise orm.except_orm(
  245. _("Connection Test Successfull!"),
  246. _("OpenERP can successfully login to the Asterisk Manager "
  247. "Interface."))
  248. def _get_calling_number(self, cr, uid, context=None):
  249. user, ast_server, ast_manager = self._connect_to_asterisk(
  250. cr, uid, context=context)
  251. calling_party_number = False
  252. try:
  253. list_chan = ast_manager.Status()
  254. # from pprint import pprint
  255. # pprint(list_chan)
  256. _logger.debug("Result of Status AMI request: %s", list_chan)
  257. for chan in list_chan.values():
  258. sip_account = user.asterisk_chan_type + '/' + user.resource
  259. # 4 = Ring
  260. if (
  261. chan.get('ChannelState') == '4' and
  262. chan.get('ConnectedLineNum') == user.internal_number):
  263. _logger.debug("Found a matching Event in 'Ring' state")
  264. calling_party_number = chan.get('CallerIDNum')
  265. break
  266. # 6 = Up
  267. if (
  268. chan.get('ChannelState') == '6'
  269. and sip_account in chan.get('BridgedChannel', '')):
  270. _logger.debug("Found a matching Event in 'Up' state")
  271. calling_party_number = chan.get('CallerIDNum')
  272. break
  273. # Compatibility with Asterisk 1.4
  274. if (
  275. chan.get('State') == 'Up'
  276. and sip_account in chan.get('Link', '')):
  277. _logger.debug("Found a matching Event in 'Up' state")
  278. calling_party_number = chan.get('CallerIDNum')
  279. break
  280. except Exception, e:
  281. _logger.error(
  282. "Error in the Status request to Asterisk server %s"
  283. % ast_server.ip_address)
  284. _logger.error(
  285. "Here are the details of the error: '%s'" % unicode(e))
  286. raise orm.except_orm(
  287. _('Error:'),
  288. _("Can't get calling number from Asterisk.\nHere is the "
  289. "error: '%s'" % unicode(e)))
  290. finally:
  291. ast_manager.Logoff()
  292. _logger.debug("Calling party number: '%s'" % calling_party_number)
  293. return calling_party_number
  294. def get_record_from_my_channel(self, cr, uid, context=None):
  295. calling_number = self.pool['asterisk.server']._get_calling_number(
  296. cr, uid, context=context)
  297. #calling_number = "0641981246"
  298. if calling_number:
  299. record = self.pool['phone.common'].get_record_from_phone_number(
  300. cr, uid, calling_number, context=context)
  301. if record:
  302. return record
  303. else:
  304. return calling_number
  305. else:
  306. return False
  307. class res_users(orm.Model):
  308. _inherit = "res.users"
  309. _columns = {
  310. 'internal_number': fields.char(
  311. 'Internal Number', size=15,
  312. help="User's internal phone number."),
  313. 'dial_suffix': fields.char(
  314. 'User-specific Dial Suffix', size=15,
  315. help="User-specific dial suffix such as aa=2wb for SCCP "
  316. "auto answer."),
  317. 'callerid': fields.char(
  318. 'Caller ID', size=50,
  319. help="Caller ID used for the calls initiated by this user."),
  320. # You'd probably think: Asterisk should reuse the callerID of sip.conf!
  321. # But it cannot, cf
  322. # http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  323. 'cdraccount': fields.char(
  324. 'CDR Account', size=50,
  325. help="Call Detail Record (CDR) account used for billing this "
  326. "user."),
  327. 'asterisk_chan_type': fields.selection([
  328. ('SIP', 'SIP'),
  329. ('IAX2', 'IAX2'),
  330. ('DAHDI', 'DAHDI'),
  331. ('Zap', 'Zap'),
  332. ('Skinny', 'Skinny'),
  333. ('MGCP', 'MGCP'),
  334. ('mISDN', 'mISDN'),
  335. ('H323', 'H323'),
  336. ('SCCP', 'SCCP'),
  337. ('Local', 'Local'),
  338. ], 'Asterisk Channel Type',
  339. help="Asterisk channel type, as used in the Asterisk dialplan. "
  340. "If the user has a regular IP phone, the channel type is 'SIP'."),
  341. 'resource': fields.char(
  342. 'Resource Name', size=64,
  343. help="Resource name for the channel type selected. For example, "
  344. "if you use 'Dial(SIP/phone1)' in your Asterisk dialplan to ring "
  345. "the SIP phone of this user, then the resource name for this user "
  346. "is 'phone1'. For a SIP phone, the phone number is often used as "
  347. "resource name, but not always."),
  348. 'alert_info': fields.char(
  349. 'User-specific Alert-Info SIP Header', size=255,
  350. help="Set a user-specific Alert-Info header in SIP request to "
  351. "user's IP Phone for the click2dial feature. If empty, the "
  352. "Alert-Info header will not be added. You can use it to have a "
  353. "special ring tone for click2dial (a silent one !) or to "
  354. "activate auto-answer for example."),
  355. 'variable': fields.char(
  356. 'User-specific Variable', size=255,
  357. help="Set a user-specific 'Variable' field in the Asterisk "
  358. "Manager Interface 'originate' request for the click2dial "
  359. "feature. If you want to have several variable headers, separate "
  360. "them with '|'."),
  361. 'asterisk_server_id': fields.many2one(
  362. 'asterisk.server', 'Asterisk Server',
  363. help="Asterisk server on which the user's phone is connected. "
  364. "If you leave this field empty, it will use the first Asterisk "
  365. "server of the user's company."),
  366. }
  367. _defaults = {
  368. 'asterisk_chan_type': 'SIP',
  369. }
  370. def _check_validity(self, cr, uid, ids):
  371. for user in self.browse(cr, uid, ids):
  372. strings_to_check = [
  373. (_('Resource Name'), user.resource),
  374. (_('Internal Number'), user.internal_number),
  375. (_('Caller ID'), user.callerid),
  376. ]
  377. for check_string in strings_to_check:
  378. if check_string[1]:
  379. try:
  380. check_string[1].encode('ascii')
  381. except UnicodeEncodeError:
  382. raise orm.except_orm(
  383. _('Error:'),
  384. _("The '%s' for the user '%s' should only have "
  385. "ASCII caracters")
  386. % (check_string[0], user.name))
  387. return True
  388. _constraints = [(
  389. _check_validity,
  390. "Error message in raise",
  391. ['resource', 'internal_number', 'callerid']
  392. )]
  393. class phone_common(orm.AbstractModel):
  394. _inherit = 'phone.common'
  395. def click2dial(self, cr, uid, erp_number, context=None):
  396. if not erp_number:
  397. orm.except_orm(
  398. _('Error:'),
  399. _('Missing phone number'))
  400. user, ast_server, ast_manager = \
  401. self.pool['asterisk.server']._connect_to_asterisk(
  402. cr, uid, context=context)
  403. ast_number = self.pool['asterisk.server']._reformat_number(
  404. cr, uid, erp_number, ast_server, context=context)
  405. # The user should have a CallerID
  406. if not user.callerid:
  407. raise orm.except_orm(
  408. _('Error:'),
  409. _('No callerID configured for the current user'))
  410. variable = []
  411. if user.asterisk_chan_type == 'SIP':
  412. # We can only have one alert-info header in a SIP request
  413. if user.alert_info:
  414. variable.append(
  415. 'SIPAddHeader=Alert-Info: %s' % user.alert_info)
  416. elif ast_server.alert_info:
  417. variable.append(
  418. 'SIPAddHeader=Alert-Info: %s' % ast_server.alert_info)
  419. if user.variable:
  420. for user_variable in user.variable.split('|'):
  421. variable.append(user_variable.strip())
  422. channel = '%s/%s' % (user.asterisk_chan_type, user.resource)
  423. if user.dial_suffix:
  424. channel += '/%s' % user.dial_suffix
  425. try:
  426. ast_manager.Originate(
  427. channel,
  428. context=ast_server.context,
  429. extension=ast_number,
  430. priority=str(ast_server.extension_priority),
  431. timeout=str(ast_server.wait_time * 1000),
  432. caller_id=user.callerid,
  433. account=user.cdraccount,
  434. variable=variable)
  435. except Exception, e:
  436. _logger.error(
  437. "Error in the Originate request to Asterisk server %s"
  438. % ast_server.ip_address)
  439. _logger.error(
  440. "Here are the details of the error: '%s'" % unicode(e))
  441. raise orm.except_orm(
  442. _('Error:'),
  443. _("Click to dial with Asterisk failed.\nHere is the error: "
  444. "'%s'")
  445. % unicode(e))
  446. finally:
  447. ast_manager.Logoff()
  448. return {'dialed_number': ast_number}