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.

288 lines
16 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. class asterisk_server(osv.osv):
  27. _name = "asterisk.server"
  28. _description = "Asterisk Servers"
  29. _columns = {
  30. 'name' : fields.char('Asterisk server name', size=50, required=True, help="Asterisk server name."),
  31. 'ip_address' : fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IPv4 address or DNS name of the Asterisk server."),
  32. 'port' : fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  33. '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."),
  34. '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'."),
  35. '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'."),
  36. 'country_prefix' : fields.char('My country prefix', 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'."),
  37. '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 ?"),
  38. '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."),
  39. '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."),
  40. '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."),
  41. '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."),
  42. '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."),
  43. '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."),
  44. 'company_id' : fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  45. }
  46. _defaults = {
  47. 'port': lambda *a: 5038, # Default AMI port
  48. 'out_prefix': lambda *a: '0',
  49. 'national_prefix': lambda *a: '0',
  50. 'international_prefix': lambda *a: '00',
  51. 'extension_priority': lambda *a: 1,
  52. 'wait_time': lambda *a: 15,
  53. }
  54. def _only_digits(self, cr, uid, ids, prefix, can_be_empty):
  55. for i in ids:
  56. prefix_to_check = self.read(cr, uid, i, [prefix])[prefix]
  57. if prefix_to_check == False:
  58. if can_be_empty:
  59. return True
  60. else:
  61. return False
  62. else:
  63. if not prefix_to_check.isdigit():
  64. return False
  65. return True
  66. def _only_digits_out_prefix(self, cr, uid, ids):
  67. return self._only_digits(cr, uid, ids, 'out_prefix', True)
  68. def _only_digits_country_prefix(self, cr, uid, ids):
  69. return self._only_digits(cr, uid, ids, 'country_prefix', False)
  70. def _only_digits_national_prefix(self, cr, uid, ids):
  71. return self._only_digits(cr, uid, ids, 'national_prefix', True)
  72. def _only_digits_international_prefix(self, cr, uid, ids):
  73. return self._only_digits(cr, uid, ids, 'international_prefix', False)
  74. def _check_wait_time(self, cr, uid, ids):
  75. for i in ids:
  76. wait_time_to_check = self.read(cr, uid, i, ['wait_time'])['wait_time']
  77. if wait_time_to_check < 1 or wait_time_to_check > 120:
  78. return False
  79. return True
  80. def _check_extension_priority(self, cr, uid, ids):
  81. for i in ids:
  82. extension_priority_to_check = self.read(cr, uid, i, ['extension_priority'])['extension_priority']
  83. if extension_priority_to_check < 1:
  84. return False
  85. return True
  86. def _check_port(self, cr, uid, ids):
  87. for i in ids:
  88. port_to_check = self.read(cr, uid, i, ['port'])['port']
  89. if port_to_check > 65535 or port_to_check < 1:
  90. return False
  91. return True
  92. _constraints = [
  93. (_only_digits_out_prefix, "Only use digits for the 'out prefix' or leave empty", ['out_prefix']),
  94. (_only_digits_country_prefix, "Only use digits for the 'country prefix'", ['country_prefix']),
  95. (_only_digits_national_prefix, "Only use digits for the 'national prefix' or leave empty", ['national_prefix']),
  96. (_only_digits_international_prefix, "Only use digits for 'international prefix'", ['international_prefix']),
  97. (_check_wait_time, "You should enter a 'Wait time' value between 1 and 120 seconds", ['wait_time']),
  98. (_check_extension_priority, "The 'extension priority' must be a positive value", ['extension_priority']),
  99. (_check_port, 'TCP ports range from 1 to 65535', ['port']),
  100. ]
  101. # This function is dedicated to the transformation of the number
  102. # available in OpenERP to the number that Asterisk should dial.
  103. # You may have to inherit this function in another module specific
  104. # for your company if you are not happy with the way I reformat
  105. # the OpenERP numbers.
  106. def reformat_number(self, cr, uid, ids, erp_number, ast_server, context):
  107. logger = netsvc.Logger()
  108. error_title_msg = "Invalid phone number"
  109. 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"
  110. invalid_national_format_msg = "The phone number is not written in valid national format."
  111. invalid_format_msg = "The phone number is not written in valid format."
  112. # Let's call the variable tmp_number now
  113. tmp_number = erp_number
  114. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Number before reformat = ' + tmp_number)
  115. # Check if empty
  116. if not tmp_number:
  117. raise osv.except_osv(error_title_msg, invalid_format_msg)
  118. # First, we remove all stupid caracters and spaces
  119. for i in [' ', '.', '(', ')', '[', ']', '-', '/']:
  120. tmp_number = tmp_number.replace(i, '')
  121. # Before starting to use prefix, we convert empty prefix whose value
  122. # is False to an empty string
  123. country_prefix = (ast_server.country_prefix or '')
  124. national_prefix = (ast_server.national_prefix or '')
  125. international_prefix = (ast_server.international_prefix or '')
  126. out_prefix = (ast_server.out_prefix or '')
  127. # International format
  128. if tmp_number[0]=='+':
  129. # Remove the starting '+' of the number
  130. tmp_number = tmp_number.replace('+','')
  131. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Number after removal of special char = ' + tmp_number)
  132. # At this stage, 'tmp_number' should only contain digits
  133. if not tmp_number.isdigit():
  134. raise osv.except_osv(error_title_msg, invalid_format_msg)
  135. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Country prefix = ' + 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.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'National prefix = ' + national_prefix + ' - Number with 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.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'International prefix = ' + international_prefix + ' - Number with international prefix = ' + tmp_number)
  146. # National format, allowed
  147. elif ast_server.national_format_allowed:
  148. # No treatment required
  149. if not tmp_number.isdigit():
  150. raise osv.except_osv(error_title_msg, invalid_national_format_msg)
  151. # National format, disallowed
  152. elif not ast_server.national_format_allowed:
  153. raise osv.except_osv(error_title_msg, invalid_international_format_msg)
  154. # Add 'out prefix' to all numbers
  155. tmp_number = out_prefix + tmp_number
  156. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Out prefix = ' + out_prefix + ' - Number to be sent to Asterisk = ' + tmp_number)
  157. return tmp_number
  158. # Open the socket to the Asterisk Manager Interface
  159. # and send instructions to Dial to Asterisk
  160. def dial(self, cr, uid, ids, erp_number, context):
  161. logger = netsvc.Logger()
  162. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  163. # Check if the number to dial is not empty
  164. if not erp_number:
  165. raise osv.except_osv('Error', 'There is no phone number !')
  166. # We check if the user has an Asterisk server configured
  167. if not user.asterisk_server_id.id:
  168. raise osv.except_osv('No Asterisk server configured for the current user', "You must associate an Asterisk server to the current user.")
  169. else:
  170. ast_server = user.asterisk_server_id
  171. # We check if the current user has a chan type
  172. if not user.asterisk_chan_type:
  173. raise osv.except_osv('No channel type configured for the current user', "You must configure an Asterisk channel type for the current user.")
  174. # We check if the current user has an internal number
  175. if not user.internal_number:
  176. raise osv.except_osv('No internal phone number configured for the current user', "You must configure an internal phone number for the current user.")
  177. # Convert the phone number in the format that will be sent to Asterisk
  178. ast_number = self.reformat_number(cr, uid, ids, erp_number, ast_server, context=context)
  179. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'User dialing : channel = ' + user.asterisk_chan_type + '/' + user.internal_number + ' - Callerid = ' + user.callerid)
  180. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, 'Asterisk server = ' + ast_server.ip_address + ':' + str(ast_server.port))
  181. # Connect to the Asterisk Manager Interface
  182. try:
  183. ast_ip = socket.gethostbyname(str(ast_server.ip_address))
  184. except:
  185. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_DEBUG, "Can't resolve the Asterisk server's DNS : " + str(ast_server.ip_address))
  186. raise osv.except_osv('Wrong DNS', "Can't resolve the DNS name of the Asterisk server.")
  187. try:
  188. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  189. sock.connect((ast_ip, ast_server.port))
  190. sock.send('Action: login\r\n')
  191. sock.send('Events: off\r\n')
  192. sock.send('Username: '+str(ast_server.login)+'\r\n')
  193. sock.send('Secret: '+str(ast_server.password)+'\r\n\r\n')
  194. sock.send('Action: originate\r\n')
  195. sock.send('Channel: ' + str(user.asterisk_chan_type) + '/' + str(user.internal_number)+'\r\n')
  196. sock.send('Timeout: '+str(ast_server.wait_time*1000)+'\r\n')
  197. sock.send('CallerId: '+str(user.callerid)+'\r\n')
  198. sock.send('Exten: '+str(ast_number)+'\r\n')
  199. sock.send('Context: '+str(ast_server.context)+'\r\n')
  200. if not ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  201. sock.send('Variable: SIPAddHeader=Alert-Info: '+str(ast_server.alert_info)+'\r\n')
  202. sock.send('Priority: '+str(ast_server.extension_priority)+'\r\n\r\n')
  203. sock.send('Action: Logoff\r\n\r\n')
  204. sock.close()
  205. except:
  206. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_WARNING, "Click2dial failed : unable to connect to Asterisk")
  207. raise osv.except_osv('Asterisk server unreachable', "The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk.")
  208. logger.notifyChannel('asterisk_click2dial', netsvc.LOG_INFO, "Asterisk Click2Dial from " + user.internal_number + ' to ' + ast_number)
  209. asterisk_server()
  210. # Parameters specific for each user
  211. class res_users(osv.osv):
  212. _name = "res.users"
  213. _inherit = "res.users"
  214. _columns = {
  215. 'internal_number' : fields.char('Internal number', size=15, help="User's internal phone number."),
  216. 'callerid' : fields.char('Caller ID', size=50, help="Caller ID used for the calls initiated by this user."),
  217. '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'."),
  218. 'asterisk_server_id' : fields.many2one('asterisk.server', 'Asterisk server', help="Asterisk server on which the user's phone is connected."),
  219. }
  220. _defaults = {
  221. 'asterisk_chan_type': lambda *a: 'SIP',
  222. }
  223. res_users()
  224. class res_partner_address(osv.osv):
  225. _name = "res.partner.address"
  226. _inherit ="res.partner.address"
  227. # Functions called by the button "Dial" in the partner address view
  228. def action_dial_phone(self, cr, uid, ids, context):
  229. erp_number = self.read(cr, uid, ids, ['phone'], context=context)[0]['phone']
  230. self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context)
  231. def action_dial_mobile(self, cr, uid, ids, context):
  232. erp_number = self.read(cr, uid, ids, ['mobile'], context=context)[0]['mobile']
  233. self.pool.get('asterisk.server').dial(cr, uid, ids, erp_number, context)
  234. res_partner_address()
  235. # This module supports multi-company
  236. class res_company(osv.osv):
  237. _name = "res.company"
  238. _inherit = "res.company"
  239. _columns = {
  240. 'asterisk_server_ids' : fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  241. }
  242. res_company()