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.

409 lines
23 KiB

12 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. # Lib for phone number reformating -> pip install phonenumbers
  25. import phonenumbers
  26. # Lib py-asterisk from http://code.google.com/p/py-asterisk/
  27. # We need a version which has this commit : http://code.google.com/p/py-asterisk/source/detail?r=8d0e1c941cce727c702582f3c9fcd49beb4eeaa4
  28. # so a version after Nov 20th, 2012
  29. from Asterisk import Manager
  30. _logger = logging.getLogger(__name__)
  31. class asterisk_server(orm.Model):
  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 OpenERP 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."),
  50. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  51. }
  52. def _get_prefix_from_country(self, cr, uid, context=None):
  53. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  54. country_code = user.company_id and user.company_id.partner_id and user.company_id.partner_id.country_id and user.company_id.partner_id.country_id.code or False
  55. default_country_prefix = False
  56. if country_code:
  57. default_country_prefix = phonenumbers.country_code_for_region(country_code)
  58. return default_country_prefix
  59. _defaults = {
  60. 'active': True,
  61. 'port': 5038, # Default AMI port
  62. 'national_prefix': '0',
  63. 'international_prefix': '00',
  64. 'country_prefix': _get_prefix_from_country,
  65. 'extension_priority': 1,
  66. 'wait_time': 15,
  67. 'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'asterisk.server', context=context),
  68. }
  69. def _check_validity(self, cr, uid, ids):
  70. for server in self.browse(cr, uid, ids):
  71. country_prefix = ('Country prefix', server.country_prefix)
  72. international_prefix = ('International prefix', server.international_prefix)
  73. out_prefix = ('Out prefix', server.out_prefix)
  74. national_prefix = ('National prefix', server.national_prefix)
  75. dialplan_context = ('Dialplan context', server.context)
  76. alert_info = ('Alert-Info SIP header', server.alert_info)
  77. login = ('AMI login', server.login)
  78. password = ('AMI password', server.password)
  79. for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
  80. if digit_prefix[1] and not digit_prefix[1].isdigit():
  81. raise orm.except_orm(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
  82. if server.wait_time < 1 or server.wait_time > 120:
  83. raise orm.except_orm(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
  84. if server.extension_priority < 1:
  85. raise orm.except_orm(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
  86. if server.port > 65535 or server.port < 1:
  87. raise orm.except_orm(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterisk server '%s'" % server.name))
  88. for check_string in [dialplan_context, alert_info, login, password]:
  89. if check_string[1]:
  90. try:
  91. string = check_string[1].encode('ascii')
  92. except UnicodeEncodeError:
  93. raise orm.except_orm(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
  94. return True
  95. _constraints = [
  96. (_check_validity, "Error message in raise", ['out_prefix', 'country_prefix', 'national_prefix', 'international_prefix', 'wait_time', 'extension_priority', 'port', 'context', 'alert_info', 'login', 'password']),
  97. ]
  98. def _reformat_number(self, cr, uid, erp_number, ast_server, context=None):
  99. '''
  100. This function is dedicated to the transformation of the number
  101. available in OpenERP to the number that Asterisk should dial.
  102. You may have to inherit this function in another module specific
  103. for your company if you are not happy with the way I reformat
  104. the OpenERP numbers.
  105. '''
  106. error_title_msg = _("Invalid phone number")
  107. 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")
  108. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  109. invalid_format_msg = _("The phone number is not written in valid format.")
  110. # Let's call the variable tmp_number now
  111. tmp_number = erp_number
  112. _logger.debug('Number before reformat = %s' % tmp_number)
  113. # Check if empty
  114. if not tmp_number:
  115. raise orm.except_orm(error_title_msg, invalid_format_msg)
  116. # Before starting to use prefix, we convert empty prefix whose value
  117. # is False to an empty string
  118. country_prefix = ast_server.country_prefix or ''
  119. national_prefix = ast_server.national_prefix or ''
  120. international_prefix = ast_server.international_prefix or ''
  121. out_prefix = ast_server.out_prefix or ''
  122. # Maybe one day we will use
  123. # phonenumbers.format_out_of_country_calling_number(phonenumbers.parse('<phone_number_e164', None), 'FR')
  124. # The country code seems to be OK with the ones of OpenERP
  125. # But it returns sometimes numbers with '-'... we have to investigate this first
  126. # International format
  127. if tmp_number[0] != '+':
  128. raise # This should never happen
  129. # Remove the starting '+' of the number
  130. tmp_number = tmp_number.replace('+','')
  131. _logger.debug('Number after removal of special char = %s' % tmp_number)
  132. # At this stage, 'tmp_number' should only contain digits
  133. if not tmp_number.isdigit():
  134. raise orm.except_orm(error_title_msg, invalid_format_msg)
  135. _logger.debug('Country prefix = %s' % country_prefix)
  136. if country_prefix == tmp_number[0:len(country_prefix)]:
  137. # If the number is a national number,
  138. # remove 'my country prefix' and add 'national prefix'
  139. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  140. _logger.debug('National prefix = %s - Number with national prefix = %s' % (national_prefix, tmp_number))
  141. else:
  142. # If the number is an international number,
  143. # add 'international prefix'
  144. tmp_number = international_prefix + tmp_number
  145. _logger.debug('International prefix = %s - Number with international prefix = %s' % (international_prefix, tmp_number))
  146. # Add 'out prefix' to all numbers
  147. tmp_number = out_prefix + tmp_number
  148. _logger.debug('Out prefix = %s - Number to be sent to Asterisk = %s' % (out_prefix, tmp_number))
  149. return tmp_number
  150. # TODO : one day, we will use phonenumbers.format_out_of_country_calling_number() ?
  151. # if yes, then we can trash the fields international_prefix, national_prefix
  152. # country_prefix and this kind of code
  153. def _convert_number_to_international_format(self, cr, uid, number, ast_server, context=None):
  154. '''Convert the number presented by the phone network to a number
  155. in international format e.g. +33141981242'''
  156. if number and number.isdigit() and len(number) > 5:
  157. if ast_server.international_prefix and number[0:len(ast_server.international_prefix)] == ast_server.international_prefix:
  158. number = number[len(ast_server.international_prefix):]
  159. number = '+' + number
  160. elif ast_server.national_prefix and number[0:len(ast_server.national_prefix)] == ast_server.national_prefix:
  161. number = number[len(ast_server.national_prefix):]
  162. number = '+' + ast_server.country_prefix + number
  163. return number
  164. def _get_asterisk_server_from_user(self, cr, uid, context=None):
  165. '''Returns an asterisk.server browse object'''
  166. # We check if the user has an Asterisk server configured
  167. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  168. if user.asterisk_server_id.id:
  169. ast_server = user.asterisk_server_id
  170. else:
  171. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  172. # If no asterisk server is configured on the user, we take the first one
  173. if not asterisk_server_ids:
  174. raise orm.except_orm(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  175. else:
  176. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  177. return ast_server
  178. def _connect_to_asterisk(self, cr, uid, context=None):
  179. '''
  180. Open the connection to the Asterisk Manager
  181. Returns an instance of the Asterisk Manager
  182. '''
  183. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  184. # Note : if I write 'Error' without ' :', it won't get translated...
  185. # I don't understand why !
  186. ast_server = self._get_asterisk_server_from_user(cr, uid, context=context)
  187. # We check if the current user has a chan type
  188. if not user.asterisk_chan_type:
  189. raise orm.except_orm(_('Error :'), _('No channel type configured for the current user.'))
  190. # We check if the current user has an internal number
  191. if not user.resource:
  192. raise orm.except_orm(_('Error :'), _('No resource name configured for the current user'))
  193. _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.resource))
  194. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  195. # Connect to the Asterisk Manager Interface
  196. try:
  197. ast_manager = Manager.Manager((ast_server.ip_address, ast_server.port), ast_server.login, ast_server.password)
  198. except Exception, e:
  199. _logger.error("Error in the Originate request to Asterisk server %s" % ast_server.ip_address)
  200. _logger.error("Here is the detail of the error : %s" % e.strerror)
  201. raise orm.except_orm(_('Error :'), _("Problem in the request from OpenERP to Asterisk. Here is the detail of the error: %s." % e.strerror))
  202. return False
  203. return (user, ast_server, ast_manager)
  204. def _dial_with_asterisk(self, cr, uid, erp_number, context=None):
  205. #print "_dial_with_asterisk erp_number=", erp_number
  206. if not erp_number:
  207. raise orm.except_orm(_('Error :'), "Hara kiri : you must call the function with erp_number")
  208. user, ast_server, ast_manager = self._connect_to_asterisk(cr, uid, context=context)
  209. ast_number = self._reformat_number(cr, uid, erp_number, ast_server, context=context)
  210. # The user should have a CallerID
  211. if not user.callerid:
  212. raise orm.except_orm(_('Error :'), _('No callerID configured for the current user'))
  213. variable = []
  214. if user.asterisk_chan_type == 'SIP':
  215. # We can only have one alert-info header in a SIP request
  216. if user.alert_info:
  217. variable.append('SIPAddHeader=Alert-Info: ' + user.alert_info)
  218. elif ast_server.alert_info:
  219. variable.append('SIPAddHeader=Alert-Info: ' + ast_server.alert_info)
  220. if user.variable:
  221. for user_variable in user.variable.split('|'):
  222. variable.append(user_variable.strip())
  223. try:
  224. ast_manager.Originate(
  225. user.asterisk_chan_type + '/' + user.resource + ( ('/' + user.dial_suffix) if user.dial_suffix else ''),
  226. context = ast_server.context,
  227. extension = ast_number,
  228. priority = str(ast_server.extension_priority),
  229. timeout = str(ast_server.wait_time*1000),
  230. caller_id = user.callerid,
  231. account = user.cdraccount,
  232. variable = variable)
  233. except Exception, e:
  234. _logger.error("Error in the Originate request to Asterisk server %s" % ast_server.ip_address)
  235. _logger.error("Here is the detail of the error : '%s'" % unicode(e))
  236. raise orm.except_orm(_('Error :'), _("Click to dial with Asterisk failed.\nHere is the error: '%s'" % unicode(e)))
  237. finally:
  238. ast_manager.Logoff()
  239. return True
  240. def _get_calling_number(self, cr, uid, context=None):
  241. user, ast_server, ast_manager = self._connect_to_asterisk(cr, uid, context=context)
  242. calling_party_number = False
  243. try:
  244. list_chan = ast_manager.Status()
  245. #from pprint import pprint
  246. #pprint(list_chan)
  247. _logger.debug("Result of Status AMI request: %s", list_chan)
  248. for chan in list_chan.values():
  249. sip_account = user.asterisk_chan_type + '/' + user.resource
  250. if chan.get('ChannelState') == '4' and chan.get('ConnectedLineNum') == user.internal_number: # 4 = Ring
  251. _logger.debug("Found a matching Event in 'Ring' state")
  252. calling_party_number = chan.get('CallerIDNum')
  253. break
  254. if chan.get('ChannelState') == '6' and sip_account in chan.get('BridgedChannel', ''): # 6 = Up
  255. _logger.debug("Found a matching Event in 'Up' state")
  256. calling_party_number = chan.get('CallerIDNum')
  257. break
  258. # Compatibility with Asterisk 1.4
  259. if chan.get('State') == 'Up' and sip_account in chan.get('Link', ''):
  260. _logger.debug("Found a matching Event in 'Up' state")
  261. calling_party_number = chan.get('CallerIDNum')
  262. break
  263. except Exception, e:
  264. _logger.error("Error in the Status request to Asterisk server %s" % ast_server.ip_address)
  265. _logger.error("Here is the detail of the error : '%s'" % unicode(e))
  266. raise orm.except_orm(_('Error :'), _("Can't get calling number from Asterisk.\nHere is the error: '%s'" % unicode(e)))
  267. finally:
  268. ast_manager.Logoff()
  269. _logger.debug("The calling party number is '%s'" % calling_party_number)
  270. return calling_party_number
  271. # Parameters specific for each user
  272. class res_users(orm.Model):
  273. _inherit = "res.users"
  274. _columns = {
  275. 'internal_number': fields.char('Internal number', size=15,
  276. help="User's internal phone number."),
  277. 'dial_suffix': fields.char('User-specific dial suffix', size=15,
  278. help="User-specific dial suffix such as aa=2wb for SCCP auto answer."),
  279. 'callerid': fields.char('Caller ID', size=50,
  280. help="Caller ID used for the calls initiated by this user."),
  281. # You'd probably think : Asterisk should reuse the callerID of sip.conf !
  282. # But it cannot, cf http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  283. 'cdraccount': fields.char('CDR Account', size=50,
  284. help="Call Detail Record (CDR) account used for billing this user."),
  285. 'asterisk_chan_type': fields.selection([
  286. ('SIP', 'SIP'),
  287. ('IAX2', 'IAX2'),
  288. ('DAHDI', 'DAHDI'),
  289. ('Zap', 'Zap'),
  290. ('Skinny', 'Skinny'),
  291. ('MGCP', 'MGCP'),
  292. ('mISDN', 'mISDN'),
  293. ('H323', 'H323'),
  294. ('SCCP', 'SCCP'),
  295. ('Local', 'Local'),
  296. ], 'Asterisk channel type',
  297. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  298. 'resource': fields.char('Resource name', size=64,
  299. help="Resource name for the channel type selected. For example, if you use 'Dial(SIP/phone1)' in your Asterisk dialplan to ring the SIP phone of this user, then the resource name for this user is 'phone1'. For a SIP phone, the phone number is often used as resource name, but not always."),
  300. '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."),
  301. '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 '|'."),
  302. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  303. 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."),
  304. }
  305. _defaults = {
  306. 'asterisk_chan_type': 'SIP',
  307. }
  308. def _check_validity(self, cr, uid, ids):
  309. for user in self.browse(cr, uid, ids):
  310. for check_string in [('Resource name', user.resource), ('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  311. if check_string[1]:
  312. try:
  313. plom = check_string[1].encode('ascii')
  314. except UnicodeEncodeError:
  315. raise orm.except_orm(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  316. return True
  317. _constraints = [
  318. (_check_validity, "Error message in raise", ['resource', 'internal_number', 'callerid']),
  319. ]
  320. class phone_common(orm.AbstractModel):
  321. _inherit = 'phone.common'
  322. def action_dial(self, cr, uid, ids, context=None):
  323. '''Read the number to dial and call _connect_to_asterisk the right way'''
  324. if context is None:
  325. context = {}
  326. if not isinstance(context.get('field2dial'), (unicode, str)):
  327. raise orm.except_orm(_('Error :'), "The function action_dial must be called with a 'field2dial' key in the context containing a string '<phone_field>'.")
  328. else:
  329. phone_field = context.get('field2dial')
  330. erp_number_read = self.read(cr, uid, ids[0], [phone_field], context=context)
  331. erp_number_e164 = erp_number_read[phone_field]
  332. # Check if the number to dial is not empty
  333. if not erp_number_e164:
  334. raise orm.except_orm(_('Error :'), _('There is no phone number !'))
  335. return self.pool['asterisk.server']._dial_with_asterisk(cr, uid, erp_number_e164, context=context)
  336. def _prepare_incall_pop_action(
  337. self, cr, uid, record_res, number, context=None):
  338. # Not executed because this module doesn't depend on base_phone_popup
  339. # TODO move to a dedicated module asterisk_popup ?
  340. action = super(phone_common, self)._prepare_incall_pop_action(
  341. cr, uid, record_res, number, context=context)
  342. if not action:
  343. action = {
  344. 'name': _('No Partner Found'),
  345. 'type': 'ir.actions.act_window',
  346. 'res_model': 'wizard.open.calling.partner',
  347. 'view_mode': 'form',
  348. 'views': [[False, 'form']], # Beurk, but needed
  349. 'target': 'new',
  350. 'context': {'incall_number_popup': number}
  351. }
  352. return action