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.

344 lines
19 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Asterisk Click2dial module for OpenERP
  5. # Copyright (C) 2010 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 netsvc
  26. # Lib to translate error messages
  27. from tools.translate import _
  28. # Lib for regexp
  29. import re
  30. class asterisk_server(osv.osv):
  31. '''Asterisk server object, to store all 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, help="Asterisk server name."),
  36. 'active': fields.boolean('Active', help="The active field allows you to hide the Asterisk server without deleting it."),
  37. 'ip_address': fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IPv4 address or DNS name of the Asterisk server."),
  38. 'port': fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  39. '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."),
  40. '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'."),
  41. 'international_prefix': fields.char('International prefix', 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'."),
  42. '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'."),
  43. '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 ?"),
  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 Asterisk 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=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."),
  50. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  51. }
  52. _defaults = {
  53. 'active': lambda *a: 1,
  54. 'port': lambda *a: 5038, # Default AMI port
  55. 'out_prefix': lambda *a: '0',
  56. 'national_prefix': lambda *a: '0',
  57. 'international_prefix': lambda *a: '00',
  58. 'extension_priority': lambda *a: 1,
  59. 'wait_time': lambda *a: 15,
  60. }
  61. def _only_digits(self, cr, uid, ids, prefix, can_be_empty):
  62. for i in ids:
  63. prefix_to_check = self.read(cr, uid, i, [prefix])[prefix]
  64. if not prefix_to_check:
  65. if can_be_empty:
  66. return True
  67. else:
  68. return False
  69. else:
  70. if not prefix_to_check.isdigit():
  71. return False
  72. return True
  73. def _only_digits_out_prefix(self, cr, uid, ids):
  74. return self._only_digits(cr, uid, ids, 'out_prefix', True)
  75. def _only_digits_country_prefix(self, cr, uid, ids):
  76. return self._only_digits(cr, uid, ids, 'country_prefix', False)
  77. def _only_digits_national_prefix(self, cr, uid, ids):
  78. return self._only_digits(cr, uid, ids, 'national_prefix', True)
  79. def _only_digits_international_prefix(self, cr, uid, ids):
  80. return self._only_digits(cr, uid, ids, 'international_prefix', False)
  81. def _check_wait_time(self, cr, uid, ids):
  82. for i in ids:
  83. wait_time_to_check = self.read(cr, uid, i, ['wait_time'])['wait_time']
  84. if wait_time_to_check < 1 or wait_time_to_check > 120:
  85. return False
  86. return True
  87. def _check_extension_priority(self, cr, uid, ids):
  88. for i in ids:
  89. extension_priority_to_check = self.read(cr, uid, i, ['extension_priority'])['extension_priority']
  90. if extension_priority_to_check < 1:
  91. return False
  92. return True
  93. def _check_port(self, cr, uid, ids):
  94. for i in ids:
  95. port_to_check = self.read(cr, uid, i, ['port'])['port']
  96. if port_to_check > 65535 or port_to_check < 1:
  97. return False
  98. return True
  99. _constraints = [
  100. (_only_digits_out_prefix, "Only use digits for the 'out prefix' or leave empty", ['out_prefix']),
  101. (_only_digits_country_prefix, "Only use digits for the 'country prefix'", ['country_prefix']),
  102. (_only_digits_national_prefix, "Only use digits for the 'national prefix' or leave empty", ['national_prefix']),
  103. (_only_digits_international_prefix, "Only use digits for 'international prefix'", ['international_prefix']),
  104. (_check_wait_time, "You should enter a 'Wait time' value between 1 and 120 seconds", ['wait_time']),
  105. (_check_extension_priority, "The 'extension priority' must be a positive value", ['extension_priority']),
  106. (_check_port, 'TCP ports range from 1 to 65535', ['port']),
  107. ]
  108. def reformat_number(self, cr, uid, ids, erp_number, ast_server, context=None):
  109. '''
  110. This function is dedicated to the transformation of the number
  111. available in OpenERP to the number that Asterisk should dial.
  112. You may have to inherit this function in another module specific
  113. for your company if you are not happy with the way I reformat
  114. the OpenERP numbers.
  115. '''
  116. logger = netsvc.Logger()
  117. error_title_msg = _("Invalid phone number")
  118. 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")
  119. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  120. invalid_format_msg = _("The phone number is not written in valid format.")
  121. # Let's call the variable tmp_number now
  122. tmp_number = erp_number
  123. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Number before reformat = ' + tmp_number)
  124. # Check if empty
  125. if not tmp_number:
  126. raise osv.except_osv(error_title_msg, invalid_format_msg)
  127. # First, we remove all stupid caracters and spaces
  128. for i in [' ', '.', '(', ')', '[', ']', '-', '/']:
  129. tmp_number = tmp_number.replace(i, '')
  130. # Before starting to use prefix, we convert empty prefix whose value
  131. # is False to an empty string
  132. country_prefix = (ast_server.country_prefix or '')
  133. national_prefix = (ast_server.national_prefix or '')
  134. international_prefix = (ast_server.international_prefix or '')
  135. out_prefix = (ast_server.out_prefix or '')
  136. # International format
  137. if tmp_number[0] == '+':
  138. # Remove the starting '+' of the number
  139. tmp_number = tmp_number.replace('+','')
  140. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Number after removal of special char = ' + tmp_number)
  141. # At this stage, 'tmp_number' should only contain digits
  142. if not tmp_number.isdigit():
  143. raise osv.except_osv(error_title_msg, invalid_format_msg)
  144. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Country prefix = ' + country_prefix)
  145. if country_prefix == tmp_number[0:len(country_prefix)]:
  146. # If the number is a national number,
  147. # remove 'my country prefix' and add 'national prefix'
  148. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  149. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'National prefix = ' + national_prefix + ' - Number with national prefix = ' + tmp_number)
  150. else:
  151. # If the number is an international number,
  152. # add 'international prefix'
  153. tmp_number = international_prefix + tmp_number
  154. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'International prefix = ' + international_prefix + ' - Number with international prefix = ' + tmp_number)
  155. # National format, allowed
  156. elif ast_server.national_format_allowed:
  157. # No treatment required
  158. if not tmp_number.isdigit():
  159. raise osv.except_osv(error_title_msg, invalid_national_format_msg)
  160. # National format, disallowed
  161. elif not ast_server.national_format_allowed:
  162. raise osv.except_osv(error_title_msg, invalid_international_format_msg)
  163. # Add 'out prefix' to all numbers
  164. tmp_number = out_prefix + tmp_number
  165. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Out prefix = ' + out_prefix + ' - Number to be sent to Asterisk = ' + tmp_number)
  166. return tmp_number
  167. def dial(self, cr, uid, ids, erp_number, context=None):
  168. '''
  169. Open the socket to the Asterisk Manager Interface (AMI)
  170. and send instructions to Dial to Asterisk. That's the important function !
  171. '''
  172. logger = netsvc.Logger()
  173. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  174. # Check if the number to dial is not empty
  175. if not erp_number:
  176. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  177. # Note : if I write 'Error' without ' :', it won't get translated...
  178. # I don't understand why !
  179. # We check if the user has an Asterisk server configured
  180. if not user.asterisk_server_id.id:
  181. raise osv.except_osv(_('Error :'), _('No Asterisk server configured for the current user.'))
  182. else:
  183. ast_server = user.asterisk_server_id
  184. # We check if the current user has a chan type
  185. if not user.asterisk_chan_type:
  186. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  187. # We check if the current user has an internal number
  188. if not user.internal_number:
  189. raise osv.except_osv(_('Error :'), _('No internal phone number configured for the current user'))
  190. # The user should also have a CallerID
  191. if not user.callerid:
  192. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  193. # Convert the phone number in the format that will be sent to Asterisk
  194. ast_number = self.reformat_number(cr, uid, ids, erp_number, ast_server, context=context)
  195. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'User dialing : channel = ' + user.asterisk_chan_type + '/' + user.internal_number + ' - Callerid = ' + user.callerid)
  196. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Asterisk server = ' + ast_server.ip_address + ':' + str(ast_server.port))
  197. # Connect to the Asterisk Manager Interface
  198. try:
  199. ast_ip = socket.gethostbyname(str(ast_server.ip_address))
  200. except:
  201. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, "Can't resolve the DNS of the Asterisk server : " + str(ast_server.ip_address))
  202. raise osv.except_osv(_('Error :'), _("Can't resolve the DNS of the Asterisk server : ") + str(ast_server.ip_address))
  203. try:
  204. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  205. sock.connect((ast_ip, ast_server.port))
  206. sock.send('Action: login\r\n')
  207. sock.send('Events: off\r\n')
  208. sock.send('Username: '+str(ast_server.login)+'\r\n')
  209. sock.send('Secret: '+str(ast_server.password)+'\r\n\r\n')
  210. sock.send('Action: originate\r\n')
  211. sock.send('Channel: ' + str(user.asterisk_chan_type) + '/' + str(user.internal_number)+'\r\n')
  212. sock.send('Timeout: '+str(ast_server.wait_time*1000)+'\r\n')
  213. sock.send('CallerId: '+str(user.callerid)+'\r\n')
  214. sock.send('Exten: '+str(ast_number)+'\r\n')
  215. sock.send('Context: '+str(ast_server.context)+'\r\n')
  216. if not ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  217. sock.send('Variable: SIPAddHeader=Alert-Info: '+str(ast_server.alert_info)+'\r\n')
  218. sock.send('Priority: '+str(ast_server.extension_priority)+'\r\n\r\n')
  219. sock.send('Action: Logoff\r\n\r\n')
  220. sock.close()
  221. except:
  222. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_WARNING, "Click2dial failed : unable to connect to Asterisk")
  223. raise osv.except_osv(_('Error :'), _("The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk."))
  224. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_INFO, "Asterisk Click2Dial from " + user.internal_number + ' to ' + ast_number)
  225. asterisk_server()
  226. # Parameters specific for each user
  227. class res_users(osv.osv):
  228. _name = "res.users"
  229. _inherit = "res.users"
  230. _columns = {
  231. 'internal_number': fields.char('Internal number', size=15, help="User's internal phone number."),
  232. 'callerid': fields.char('Caller ID', size=50, help="Caller ID used for the calls initiated by this user."),
  233. 'asterisk_chan_type': fields.selection([('SIP', 'SIP'), ('IAX2', 'IAX2'), ('DAHDI', 'DAHDI'), ('Zap', 'Zap'), ('Skinny', 'Skinny'), ('MGCP', 'MGCP'), ('mISDN', 'mISDN'), ('H323', 'H323')], 'Asterisk channel type', help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  234. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server', help="Asterisk server on which the user's phone is connected."),
  235. }
  236. _defaults = {
  237. 'asterisk_chan_type': lambda *a: 'SIP',
  238. }
  239. res_users()
  240. class res_partner_address(osv.osv):
  241. _name = "res.partner.address"
  242. _inherit = "res.partner.address"
  243. def action_dial_phone(self, cr, uid, ids, context=None):
  244. '''Function called by the button 'Dial' next to the 'phone' field
  245. in the partner address view'''
  246. erp_number = self.read(cr, uid, ids, ['phone'], context=context)[0]['phone']
  247. self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context=context)
  248. def action_dial_mobile(self, cr, uid, ids, context=None):
  249. '''Function called by the button 'Dial' next to the 'mobile' field
  250. in the partner address view'''
  251. erp_number = self.read(cr, uid, ids, ['mobile'], context=context)[0]['mobile']
  252. self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context=context)
  253. def get_name_from_phone_number(self, cr, uid, number, context=None):
  254. '''Function to get name from phone number. Usefull for use from Asterisk
  255. to add CallerID name to incoming calls.
  256. The "scripts/" subdirectory of this module has an AGI script that you can
  257. install on your Asterisk IPBX : the script will be called from the Asterisk
  258. dialplan via the AGI() function and it will use this function via an XML-RPC
  259. request.
  260. '''
  261. res = {}
  262. logger = netsvc.Logger()
  263. # We check that "number" is really a number
  264. if not isinstance(number, str):
  265. return False
  266. if not number.isdigit():
  267. return False
  268. netsvc.Logger().notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, u"Call get_name_from_phone_number with number = %s" % number)
  269. # Get all the partner addresses :
  270. all_ids = self.search(cr, uid, [], context=context)
  271. # For each partner address, we check if the number matches on the "phone" or "mobile" fields
  272. for entry in self.browse(cr, uid, all_ids, context=context):
  273. if entry.phone:
  274. # We use a regexp on the phone field to remove non-digit caracters
  275. if re.sub(r'\D', '', entry.phone).endswith(number):
  276. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, u"Answer get_name_from_phone_number with name = %s" % entry.name)
  277. return entry.name
  278. if entry.mobile:
  279. if re.sub(r'\D', '', entry.mobile).endswith(number):
  280. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, u"Answer get_name_from_phone_number with name = %s" % entry.name)
  281. return entry.name
  282. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, u"No match for phone number %s" % number)
  283. return False
  284. res_partner_address()
  285. # This module supports multi-company
  286. class res_company(osv.osv):
  287. _name = "res.company"
  288. _inherit = "res.company"
  289. _columns = {
  290. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  291. }
  292. res_company()