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.

461 lines
19 KiB

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