Removed unused stuff from connection constructor params. Initiate config servers...
[ipypbx] / src / ipypbx / controllers.py
1 # Copyright (c) Stas Shtin, 2010
2
3 # This file is part of IPyPBX.
4
5 # IPyPBX is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # IPyPBX is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with IPyPBX.  If not, see <http://www.gnu.org/licenses/>.
17
18 """
19 GUI controllers.
20 """
21
22 from ipypbx import http
23 from PyQt4 import QtCore, QtGui, QtSql
24
25
26 class BaseController(QtCore.QObject):
27     """
28     Base class for other controllers.
29
30     Doesn't do anything useful on its own.
31     """
32     # TODO: possibly use a separate class for options and a meta-class.
33     fields = ()
34     view_list_fields = ()
35     view_display_fields = ()
36     view_display_fields_hidden = 'ID', 'Connection ID'
37     is_bound_to_connection = True
38     relations = ()
39     delegate = None
40     
41     def __init__(self, parent=None, views=None):
42         super(BaseController, self).__init__(parent=parent)
43
44         self.views = views
45         
46         # Find out base name.
47         classname = self.__class__.__name__
48         self.basename = (
49             classname[:-10] if classname.endswith('Controller')
50             else classname)
51         self.basename = self.basename[0].lower() + self.basename[1:]
52
53         # Initialize a new model.
54         self.model = QtSql.QSqlRelationalTableModel(parent)
55         self.model.setTable('ipypbxweb_%s' % self.basename.lower())
56         self.model.setEditStrategy(self.model.OnRowChange)
57
58         # Create model header from fields list.
59         for i, field in enumerate(self.fields):
60             self.model.setHeaderData(
61             i, QtCore.Qt.Horizontal,
62             QtCore.QVariant(QtGui.QApplication.translate(
63                 "MainWindow", field, None,
64                 QtGui.QApplication.UnicodeUTF8)))
65
66         # Fetch model data.
67         self.model.select()
68
69         # Otherwise get view list from the parent.            
70         self.view_list = getattr(views, self.basename + 'ViewList')
71         self.view_list.setModel(self.model)
72         self.view_list.setSelectionMode(self.view_list.SingleSelection)
73         
74         # Hide fields not meant for display.
75         for i, field in enumerate(self.fields):
76             if field not in self.view_list_fields:
77                 self.view_list.hideColumn(i)
78
79         # Stretch headers to fill all available width.
80         self.view_list.setSelectionMode(QtGui.QTableView.SingleSelection)
81         self.view_list.setSelectionBehavior(QtGui.QTableView.SelectRows)
82         self.view_list.resizeColumnsToContents()
83         self.view_list.resizeRowsToContents()
84         self.view_list.horizontalHeader().setStretchLastSection(True)
85
86         # Select first row.
87         self.view_list.selectRow(0)
88
89         # Get view display from the parent.
90         self.view_display = QtGui.QDataWidgetMapper(parent)
91         self.view_display.setModel(self.model)
92         
93         display_fields = self.getDisplayFields()
94         
95         for i, field in enumerate(self.fields):
96             if field in display_fields:
97                 field_widget = self.getFieldWidget(field)
98                 self.view_display.addMapping(field_widget, i)
99
100         # Set relations for model & view display.
101         if self.relations:
102             self.delegate = QtSql.QSqlRelationalDelegate(self)
103             self.view_display.setItemDelegate(self.delegate)
104
105             for data in self.relations:
106                 column, name, table, display = data                
107                 column_index = self.model.fieldIndex(column)
108
109                 # SetRelation screws table data filtering?
110                 self.model.setRelation(
111                     column_index,
112                     QtSql.QSqlRelation('ipypbxweb_%s' % table, 'id', display))
113                 #self.model.select()
114
115                 rel = self.model.relationModel(column_index)
116
117                 widget = self.getFieldWidget(name)
118                 widget.setModel(self.parent().controllers[table].model)
119                 widget.setModelColumn(rel.fieldIndex(display))
120                 #widget.setItemDelegate(self.delegate)
121
122
123         # Select first row in the view list.
124         self.view_display.toFirst()
125         
126         # Register signals for this controller.
127         for data in self.getSignalsData():
128             if len(data) == 3:
129                 sender, signal, receiver = data
130                 QtCore.QObject.connect(sender, QtCore.SIGNAL(signal), receiver)
131             elif len(data) == 4:
132                 sender, signal, receiver, slot = data
133                 QtCore.QObject.connect(
134                     sender, QtCore.SIGNAL(signal), receiver, QtCore.SLOT(slot))
135                                        
136     def getFieldWidget(self, field):
137         """
138         Return widget for given field name.
139         """
140         return getattr(
141             self.views,
142             self.basename + ''.join(word.capitalize()
143                                     for word in field.split(' ')))
144
145     def getDisplayFields(self):
146         """
147         Return list of display fields.
148         
149         If view_display_fields is not send, display all fields except
150         the first one that is usually the ID.
151         """
152         return [
153             field for field in self.fields
154             if not field in self.view_display_fields_hidden]        
155
156     def getSignalsData(self):
157         """
158         Default signals built from controller's base name.
159         """
160         # Default signals handle row selection, Add and Save buttons.
161         return [
162             (getattr(self.views, self.basename + 'Add'), 'clicked()', self.add),
163             (self.view_list.selectionModel(),
164              'currentRowChanged(QModelIndex,QModelIndex)',
165              self.view_display, 'setCurrentModelIndex(QModelIndex)'),
166             (getattr(self.views, self.basename + 'Save'), 'clicked()',
167              self.save),
168             ]
169
170     def add(self):
171         """
172         Add new object.
173         """
174         # Add a new row to list view.
175         num_rows = self.model.rowCount()
176         self.model.insertRows(num_rows, 1)
177         self.view_list.selectRow(num_rows)
178
179         # Disable adding more than one row.
180         self.getFieldWidget('Add').setEnabled(False)
181
182         # Focust to the first displayed field.
183         self.getFieldWidget(self.getDisplayFields()[0]).setFocus()
184
185     def save(self):
186         """
187         Save to database.
188         """
189         self.view_display.submit()
190         self.getFieldWidget('Add').setEnabled(True)
191
192
193 class ConnectionController(BaseController):
194     """
195     Connections controller.
196     """
197     fields = (
198         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
199         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
200         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Local IP Address'),
201         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Local Port'),
202         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Freeswitch IP Address'),
203         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Freeswitch Port'))
204     view_list_fields = 'Name', 'Freeswitch IP Address', 'Freeswitch Port'
205     servers = []
206
207     def __init__(self, parent=None, views=None):
208         super(ConnectionController, self).__init__(parent, views)
209         
210         self.last_row = -1
211
212         for row in range(self.model.rowCount()):
213             # Get local IP address and port from the table.
214             local_ip_address = self.model.record(row).value(
215                 'local_ip_address').toString()
216             local_port, _ok = self.model.record(row).value('local_port').toInt()
217             if not _ok:
218                 local_port = None
219
220             server = http.FreeswitchConfigServer()
221             server.setSocket(local_ip_address, local_port)
222             server.startServer()
223             self.servers.append(server)
224     
225     def connectionEdit(self, index):
226         """
227         Restart config server on connection change if necessary.
228         """        
229         current_row = index.row()
230         if current_row != -1:
231             self.last_row = current_row
232             # Select the new row.
233             connection_id, _ok = index.model().data(
234                 index.sibling(index.row(), 0)).toInt()
235             #self.connection_id = connection_id
236             #if not self.model.rowCount():
237             #    self.add()
238         
239
240     def connectionAdd(self):
241         """
242         New connection added.
243         """
244         num_rows = self.model.rowCount()
245         
246         
247     def addServer(self, host, port):
248         """
249         Add a new config server.
250         """
251
252         server = http.FreeswitchConfigServer(self)
253         server.setSocket(host, port)
254         server.startServer()
255         self.servers.append(server)
256
257
258 class ConnectionChangeListenerController(BaseController):
259     """
260     Mixin class for reacting on connection change.
261     """
262     def getSignalsData(self):
263         """
264         Listen to connection change signal.
265         """
266         # Find connection controller in controller registry.
267         connection_controller = self.parent().controllers['connection']
268         
269         signals = [
270             (self.model, 'primeInsert(int,QSqlRecord&)', self.setConnectionId),
271             (connection_controller.view_list.selectionModel(),
272              'currentRowChanged(QModelIndex,QModelIndex)',
273              self.connectionChange)]
274         signals.extend(super(
275             ConnectionChangeListenerController, self).getSignalsData())
276         return signals
277         
278     def connectionChange(self, index):
279         """
280         Connection change handler.
281
282         Filters table by a new connection ID and stores last connection ID
283         locally.
284         """
285         if index.row() != -1:
286             connection_id, _ok = index.model().data(
287                 index.sibling(index.row(), 0)).toInt()
288             self.connection_id = connection_id
289             self.model.setFilter(
290                 'ipypbxweb_%s.connection_id = %i' %
291                 (self.basename, connection_id))
292             self.view_list.selectRow(0)
293             if not self.model.rowCount():
294                 self.add()
295
296     def setConnectionId(self, row, record):
297         """
298         Set connection_id from currently selected connection.
299         """
300         record.setValue('connection_id', self.connection_id)
301
302         
303 class SipProfileController(ConnectionChangeListenerController):
304     """
305     SIP Profile controller.
306     """
307     fields = (
308         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
309         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
310         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
311         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'External RTP IP'),
312         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'External SIP IP'),
313         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'RTP IP'),
314         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP IP'),
315         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Port'),
316         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Accept Blind Registration'),
317         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Authenticate Calls'),
318         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
319     view_list_fields = 'Name', 'SIP IP', 'SIP Port'
320     
321
322 class DomainController(ConnectionChangeListenerController):
323     """
324     Domain controller.
325     """
326     fields = (
327         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
328         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
329         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Profile ID'),
330         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Host Name'),
331         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
332     view_list_fields = 'SIP Profile ID', 'Host Name'
333     relations = (('sip_profile_id', 'SIP Profile ID', 'sipprofile', 'name'),)
334     
335
336 class GatewayController(ConnectionChangeListenerController):
337     """
338     Gateway controller.
339     """
340     fields = (
341         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
342         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
343         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Profile ID'),
344         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
345         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Username'),
346         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Password'),
347         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Realm'),
348         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'From Domain'),
349         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Expire In Seconds'),
350         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Retry In Seconds'),
351         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Caller ID In From Field'),
352         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
353     view_list_fields = 'SIP Profile ID', 'Name'
354     relations = (('sip_profile_id', 'SIP Profile ID', 'sipprofile', 'name'),)
355     
356
357 class EndpointController(ConnectionChangeListenerController):
358     """
359     Endpoint controller.
360     """
361     fields = (
362         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
363         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
364         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'User ID'),
365         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Password'),
366         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Domain ID'),
367         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
368     view_list_fields = 'User ID', 'Domain ID'
369     relations = (('domain_id', 'Domain ID', 'domain', 'host_name'),)
370     
371
372 class ExtensionController(ConnectionChangeListenerController):
373     """
374     Extension controller.
375     """
376     fields = (
377         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
378         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
379         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Destination Match'),
380         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'XML Dialplan'),
381         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Domain ID'),
382         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Endpoint ID'),
383         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Authenticate Calls'),
384         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
385     view_list_fields = 'Destination Match',
386     relations = (
387         ('domain_id', 'Domain ID', 'domain', 'host_name'),
388         ('endpoint_id', 'Endpoint ID', 'endpoint', 'user_id'))
389