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.

394 lines
21 KiB

13 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Asterisk Click2dial module for OpenERP
  5. # Copyright (C) 2010-2012 Alexis de Lattre <alexis@via.ecp.fr>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from osv import osv, fields
  22. # Lib required to open a socket (needed to communicate with Asterisk server)
  23. import socket
  24. # Lib required to print logs
  25. import logging
  26. # Lib to translate error messages
  27. from tools.translate import _
  28. # Lib for regexp
  29. import re
  30. _logger = logging.getLogger(__name__)
  31. class asterisk_server(osv.osv):
  32. '''Asterisk server object, to store all the parameters of the Asterisk IPBXs'''
  33. _name = "asterisk.server"
  34. _description = "Asterisk Servers"
  35. _columns = {
  36. 'name': fields.char('Asterisk server name', size=50, required=True, help="Asterisk server name."),
  37. 'active': fields.boolean('Active', help="The active field allows you to hide the Asterisk server without deleting it."),
  38. 'ip_address': fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IP address or DNS name of the Asterisk server."),
  39. 'port': fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  40. 'out_prefix': fields.char('Out prefix', size=4, help="Prefix to dial to place outgoing calls. If you don't use a prefix to place outgoing calls, leave empty."),
  41. 'national_prefix': fields.char('National prefix', size=4, help="Prefix for national phone calls (don't include the 'out prefix'). For e.g., in France, the phone numbers look like '01 41 98 12 42' : the National prefix is '0'."),
  42. 'international_prefix': fields.char('International prefix', required=True, size=4, help="Prefix to add to make international phone calls (don't include the 'out prefix'). For e.g., in France, the International prefix is '00'."),
  43. 'country_prefix': fields.char('My country prefix', required=True, size=4, help="Phone prefix of the country where the Asterisk server is located. For e.g. the phone prefix for France is '33'. If the phone number to dial starts with the 'My country prefix', OpenERP will remove the country prefix from the phone number and add the 'out prefix' followed by the 'national prefix'. If the phone number to dial doesn't start with the 'My country prefix', OpenERP will add the 'out prefix' followed by the 'international prefix'."),
  44. 'national_format_allowed': fields.boolean('National format allowed ?', help="Do we allow to use click2dial on phone numbers written in national format, e.g. 01 41 98 12 42, or only in the international format, e.g. +33 1 41 98 12 42 ?"),
  45. '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."),
  46. 'password': fields.char('AMI password', size=30, required=True, help="Password that Asterisk will use to communicate with the Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf on your Asterisk server."),
  47. '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."),
  48. '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."),
  49. '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."),
  50. 'alert_info': fields.char('Alert-Info SIP header', size=40, help="Set Alert-Info header in SIP request to user's IP Phone. If empty, the Alert-Info header will not be added. You can use it to have a special ring tone for click2dial, for example you could choose a silent ring tone."),
  51. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  52. }
  53. _defaults = {
  54. 'active': lambda *a: 1,
  55. 'port': lambda *a: 5038, # Default AMI port
  56. 'out_prefix': lambda *a: '0',
  57. 'national_prefix': lambda *a: '0',
  58. 'international_prefix': lambda *a: '00',
  59. 'extension_priority': lambda *a: 1,
  60. 'wait_time': lambda *a: 15,
  61. }
  62. def _check_validity(self, cr, uid, ids):
  63. for server in self.browse(cr, uid, ids):
  64. country_prefix = ('Country prefix', server.country_prefix)
  65. international_prefix = ('International prefix', server.international_prefix)
  66. out_prefix = ('Out prefix', server.out_prefix)
  67. national_prefix = ('National prefix', server.national_prefix)
  68. dialplan_context = ('Dialplan context', server.context)
  69. alert_info = ('Alert-Info SIP header', server.alert_info)
  70. login = ('AMI login', server.login)
  71. password = ('AMI password', server.password)
  72. for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
  73. if digit_prefix[1] and not digit_prefix[1].isdigit():
  74. raise osv.except_osv(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
  75. if server.wait_time < 1 or server.wait_time > 120:
  76. raise osv.except_osv(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
  77. if server.extension_priority < 1:
  78. raise osv.except_osv(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
  79. if server.port > 65535 or server.port < 1:
  80. raise osv.except_osv(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterik server '%s'" % server.name))
  81. for check_string in [dialplan_context, alert_info, login, password]:
  82. if check_string[1]:
  83. try:
  84. string = check_string[1].encode('ascii')
  85. except UnicodeEncodeError:
  86. raise osv.except_osv(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
  87. return True
  88. _constraints = [
  89. (_check_validity, "Error message in raise", ['out_prefix', 'country_prefix', 'national_prefix', 'international_prefix', 'wait_time', 'extension_priority', 'port', 'context', 'alert_info', 'login', 'password']),
  90. ]
  91. def reformat_number(self, cr, uid, ids, erp_number, ast_server, context=None):
  92. '''
  93. This function is dedicated to the transformation of the number
  94. available in OpenERP to the number that Asterisk should dial.
  95. You may have to inherit this function in another module specific
  96. for your company if you are not happy with the way I reformat
  97. the OpenERP numbers.
  98. '''
  99. error_title_msg = _("Invalid phone number")
  100. 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")
  101. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  102. invalid_format_msg = _("The phone number is not written in valid format.")
  103. # Let's call the variable tmp_number now
  104. tmp_number = erp_number
  105. _logger.debug('Number before reformat = %s' % tmp_number)
  106. # Check if empty
  107. if not tmp_number:
  108. raise osv.except_osv(error_title_msg, invalid_format_msg)
  109. # First, we remove all stupid caracters and spaces
  110. for char_to_remove in [' ', '.', '(', ')', '[', ']', '-', '/']:
  111. tmp_number = tmp_number.replace(char_to_remove, '')
  112. # Before starting to use prefix, we convert empty prefix whose value
  113. # is False to an empty string
  114. country_prefix = (ast_server.country_prefix or '')
  115. national_prefix = (ast_server.national_prefix or '')
  116. international_prefix = (ast_server.international_prefix or '')
  117. out_prefix = (ast_server.out_prefix or '')
  118. # International format
  119. if tmp_number[0] == '+':
  120. # Remove the starting '+' of the number
  121. tmp_number = tmp_number.replace('+','')
  122. _logger.debug('Number after removal of special char = %s' % tmp_number)
  123. # At this stage, 'tmp_number' should only contain digits
  124. if not tmp_number.isdigit():
  125. raise osv.except_osv(error_title_msg, invalid_format_msg)
  126. _logger.debug('Country prefix = %s' % country_prefix)
  127. if country_prefix == tmp_number[0:len(country_prefix)]:
  128. # If the number is a national number,
  129. # remove 'my country prefix' and add 'national prefix'
  130. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  131. _logger.debug('National prefix = %s - Number with national prefix = %s' % (national_prefix, tmp_number))
  132. else:
  133. # If the number is an international number,
  134. # add 'international prefix'
  135. tmp_number = international_prefix + tmp_number
  136. _logger.debug('International prefix = %s - Number with international prefix = %s' % (international_prefix, tmp_number))
  137. # National format, allowed
  138. elif ast_server.national_format_allowed:
  139. # No treatment required
  140. if not tmp_number.isdigit():
  141. raise osv.except_osv(error_title_msg, invalid_national_format_msg)
  142. # National format, disallowed
  143. elif not ast_server.national_format_allowed:
  144. raise osv.except_osv(error_title_msg, invalid_international_format_msg)
  145. # Add 'out prefix' to all numbers
  146. tmp_number = out_prefix + tmp_number
  147. _logger.debug('Out prefix = %s - Number to be sent to Asterisk = %s' % (out_prefix, tmp_number))
  148. return tmp_number
  149. def _parse_asterisk_answer(self, cr, uid, sock, context=None):
  150. '''Parse the answer of the Asterisk Manager Interface'''
  151. answer = ''
  152. data = ''
  153. while '\r\n\r\n' not in data:
  154. data = sock.recv(1024)
  155. if data:
  156. answer += data
  157. return answer
  158. def dial(self, cr, uid, ids, erp_number, context=None):
  159. '''
  160. Open the socket to the Asterisk Manager Interface (AMI)
  161. and send instructions to Dial to Asterisk. That's the important function !
  162. '''
  163. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  164. # Check if the number to dial is not empty
  165. if not erp_number:
  166. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  167. # Note : if I write 'Error' without ' :', it won't get translated...
  168. # I don't understand why !
  169. # We check if the user has an Asterisk server configured
  170. if user.asterisk_server_id.id:
  171. ast_server = user.asterisk_server_id
  172. else:
  173. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  174. # If no asterisk server is configured on the user, we take the first one
  175. if not asterisk_server_ids:
  176. raise osv.except_osv(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  177. else:
  178. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  179. # We check if the current user has a chan type
  180. if not user.asterisk_chan_type:
  181. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  182. # We check if the current user has an internal number
  183. if not user.internal_number:
  184. raise osv.except_osv(_('Error :'), _('No internal phone number configured for the current user'))
  185. # The user should also have a CallerID
  186. if not user.callerid:
  187. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  188. # Convert the phone number in the format that will be sent to Asterisk
  189. ast_number = self.reformat_number(cr, uid, ids, erp_number, ast_server, context=context)
  190. _logger.debug("User dialing : channel = %s/%s - Callerid = %s" % (user.asterisk_chan_type, user.internal_number, user.callerid))
  191. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  192. # Connect to the Asterisk Manager Interface, using IPv6-ready code
  193. try:
  194. res = socket.getaddrinfo(str(ast_server.ip_address), ast_server.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  195. except:
  196. _logger.warning("Can't resolve the DNS of the Asterisk server '%s'" % ast_server.ip_address)
  197. raise osv.except_osv(_('Error :'), _("Can't resolve the DNS of the Asterisk server : '%s'" % ast_server.ip_address))
  198. for result in res:
  199. af, socktype, proto, canonname, sockaddr = result
  200. sock = socket.socket(af, socktype, proto)
  201. try:
  202. sock.connect(sockaddr)
  203. header_received = sock.recv(1024)
  204. _logger.debug('Header received from Asterisk : %s' % header_received)
  205. # Login to Asterisk
  206. login_act = 'Action: login\r\n' + \
  207. 'Events: off\r\n' + \
  208. 'Username: ' + ast_server.login + '\r\n' + \
  209. 'Secret: ' + ast_server.password + '\r\n\r\n'
  210. sock.send(login_act.encode('ascii'))
  211. login_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  212. if 'Response: Success' in login_answer:
  213. _logger.debug("Successful authentification to Asterisk : %s" % login_answer)
  214. else:
  215. raise osv.except_osv(_('Error :'), _("Authentification to Asterisk failed :\n%s" % login_answer))
  216. # Dial with Asterisk
  217. originate_act = 'Action: originate\r\n' + \
  218. 'Channel: ' + user.asterisk_chan_type + '/' + user.internal_number + '\r\n' + \
  219. 'Priority: ' + str(ast_server.extension_priority) + '\r\n' + \
  220. 'Timeout: ' + str(ast_server.wait_time*1000) + '\r\n' + \
  221. 'CallerId: ' + user.callerid + '\r\n' + \
  222. 'Exten: ' + ast_number + '\r\n' + \
  223. 'Context: ' + ast_server.context + '\r\n'
  224. if ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  225. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + ast_server.alert_info + '\r\n'
  226. originate_act += '\r\n'
  227. sock.send(originate_act.encode('ascii'))
  228. originate_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  229. if 'Response: Success' in originate_answer:
  230. _logger.debug('Successfull originate command : %s' % originate_answer)
  231. else:
  232. raise osv.except_osv(_('Error :'), _("Click to dial with Asterisk failed :\n%s" % originate_answer))
  233. # Logout of Asterisk
  234. sock.send(('Action: Logoff\r\n\r\n').encode('ascii'))
  235. logout_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  236. if 'Response: Goodbye' in logout_answer:
  237. _logger.debug('Successfull logout from Asterisk : %s' % logout_answer)
  238. else:
  239. _logger.warning('Logout from Asterisk failed : %s' % logout_answer)
  240. # we catch only network problems here
  241. except socket.error:
  242. _logger.warning("Click2dial failed : unable to connect to Asterisk")
  243. raise osv.except_osv(_('Error :'), _("The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk."))
  244. finally:
  245. sock.close()
  246. _logger.info("Asterisk Click2Dial from %s/%s to %s" % (user.asterisk_chan_type, user.internal_number, ast_number))
  247. return True
  248. asterisk_server()
  249. # Parameters specific for each user
  250. class res_users(osv.osv):
  251. _name = "res.users"
  252. _inherit = "res.users"
  253. _columns = {
  254. 'internal_number': fields.char('Internal number', size=15,
  255. help="User's internal phone number."),
  256. 'callerid': fields.char('Caller ID', size=50,
  257. help="Caller ID used for the calls initiated by this user."),
  258. 'asterisk_chan_type': fields.selection([
  259. ('SIP', 'SIP'),
  260. ('IAX2', 'IAX2'),
  261. ('DAHDI', 'DAHDI'),
  262. ('Zap', 'Zap'),
  263. ('Skinny', 'Skinny'),
  264. ('MGCP', 'MGCP'),
  265. ('mISDN', 'mISDN'),
  266. ('H323', 'H323'),
  267. ], 'Asterisk channel type',
  268. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  269. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  270. 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."),
  271. }
  272. _defaults = {
  273. 'asterisk_chan_type': lambda *a: 'SIP',
  274. }
  275. def _check_validity(self, cr, uid, ids):
  276. for user in self.browse(cr, uid, ids):
  277. for check_string in [('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  278. try:
  279. plom = check_string[1].encode('ascii')
  280. except UnicodeEncodeError:
  281. raise osv.except_osv(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  282. return True
  283. _constraints = [
  284. (_check_validity, "Error message in raise", ['internal_number', 'callerid']),
  285. ]
  286. res_users()
  287. class res_partner_address(osv.osv):
  288. _name = "res.partner.address"
  289. _inherit = "res.partner.address"
  290. def action_dial_phone(self, cr, uid, ids, context=None):
  291. '''Function called by the button 'Dial' next to the 'phone' field
  292. in the partner address view'''
  293. erp_number = self.read(cr, uid, ids, ['phone'], context=context)[0]['phone']
  294. return self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context=context)
  295. def action_dial_mobile(self, cr, uid, ids, context=None):
  296. '''Function called by the button 'Dial' next to the 'mobile' field
  297. in the partner address view'''
  298. erp_number = self.read(cr, uid, ids, ['mobile'], context=context)[0]['mobile']
  299. return self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context=context)
  300. def get_name_from_phone_number(self, cr, uid, number, context=None):
  301. '''Function to get name from phone number. Usefull for use from Asterisk
  302. to add CallerID name to incoming calls.
  303. The "scripts/" subdirectory of this module has an AGI script that you can
  304. install on your Asterisk IPBX : the script will be called from the Asterisk
  305. dialplan via the AGI() function and it will use this function via an XML-RPC
  306. request.
  307. '''
  308. res = {}
  309. # We check that "number" is really a number
  310. if not isinstance(number, str):
  311. return False
  312. if not number.isdigit():
  313. return False
  314. _logger.debug(u"Call get_name_from_phone_number with number = %s" % number)
  315. # Get all the partner addresses :
  316. all_ids = self.search(cr, uid, [], context=context)
  317. # For each partner address, we check if the number matches on the "phone" or "mobile" fields
  318. for entry in self.browse(cr, uid, all_ids, context=context):
  319. if entry.phone:
  320. # We use a regexp on the phone field to remove non-digit caracters
  321. if re.sub(r'\D', '', entry.phone).endswith(number):
  322. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  323. return entry.name
  324. if entry.mobile:
  325. if re.sub(r'\D', '', entry.mobile).endswith(number):
  326. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  327. return entry.name
  328. _logger.debug(u"No match for phone number %s" % number)
  329. return False
  330. res_partner_address()
  331. # This module supports multi-company
  332. class res_company(osv.osv):
  333. _name = "res.company"
  334. _inherit = "res.company"
  335. _columns = {
  336. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  337. }
  338. res_company()