Project

General

Profile

SipMiddlewareApi » History » Version 64

Luci Stanescu, 03/26/2010 11:56 AM

1 1 Adrian Georgescu
= Middleware API =
2
3
[[TOC(WikiStart, Sip*, depth=3)]]
4
5 60 Adrian Georgescu
This chapter describes the event driven ''Middleware API'' that can be used by a developer to build a user interface for SIP SIMPLE client SDK.  
6 14 Adrian Georgescu
7 54 Adrian Georgescu
 * For sub-systems communications the Middleware uses the [http://pypi.python.org/pypi/python-application/ Notification Bus] provided by [http://pypi.python.org/pypi/python-application/ python-application]
8 49 Adrian Georgescu
 * For configuration the Middleware uses the [wiki:SipConfigurationAPI Configuration API] to access General and SIP account  settings
9 1 Adrian Georgescu
10 59 Adrian Georgescu
To see a working example for how to use Middleware, see the [http://sipsimpleclient.com/wiki/SipTesting#TestingGuide Command Line Tools] provided with the library.
11
12 53 Adrian Georgescu
[[Image(sipsimple-middleware.png, align=center, width=800)]]
13 1 Adrian Georgescu
14 64 Luci Stanescu
== Lookup support ==
15
16
The SIP SIMPLE middleware offers the {{{sipsimple.lookup}}} module which contains an implementation for doing DNS lookups for SIP proxies, MSRP relays and STUN servers. The interface offers both an asynchronous and synchronous interface. The asynchronous interface is based on notifications, while the synchronous one on green threads. In order to call the methods in a asynchronous manner, you just need to call the method and wait for the notification which is sent on behalf of the DNSLookup instance. The notifications sent by the DNSLookup object are DNSLookupDidSucceed and DNSLookupDidFail. In order to call the methods in a synchronous manner, you need to call the wait method on the object returned by the methods of DNSLookup. This wait method needs to be called from a green thread and will either return the result of the lookup or raise an exception.
17
18
=== DNS Lookup ===
19
20
This object implements DNS lookup support for SIP proxies according to RFC3263 and MSRP relay and STUN server lookup using SRV records. The object initially does NS record queries in order to determine the authoritative nameservers for the domain requested; these authoritative nameservers will then be used for NAPTR, SRV and A record queries. If this fails, the locally configured nameservers are used. The reason for doing this is that some home routers have broken NAPTR and/or SRV query support.
21
22
==== methods ====
23
24
 '''!__init!__'''(''self'')::
25
  Instantiate a new DNSLookup object.
26
 '''lookup_service'''(''self'', '''uri''', '''service''', '''timeout'''={{{3.0}}}, '''lifetime'''={{{15.0}}})::
27
  Perform an SRV lookup followed by A lookups for MSRP relays or STUN servers depending on the {{{service}}} parameter. If SRV queries on the {{{uri.host}}} domain fail, an A lookup is performed on it and the default port for the service is returned. Only the {{{uri.host}}} attribute is used. The return value is a list of (host, port) tuples.
28
  [[BR]]uri:[[BR]]
29
  A {{{(Frozen)SIPURI}}} from which the {{{host}}} attribute is used for the query domain.
30
  [[BR]]service:[[BR]]
31
  The service to lookup servers for, {{{"msrprelay"}}} or {{{"stun"}}}.
32
  [[BR]]timeout:[[BR]]
33
  How many seconds to wait for a response from a nameserver.
34
  [[BR]]lifetime:[[BR]]
35
  How many seconds to wait for a response from all nameservers in total.
36
 '''lookup_sip_proxy'''(''self'', '''uri''', '''supported_transports''', '''timeout'''={{{3.0}}}, '''lifetime'''={{{15.0}}})::
37
  Perform a RFC3263 compliant DNS lookup for a SIP proxy using the URI which is considered to point to a host if either the {{{host}}} attribute is an IP address, or the {{{port}}} is present. Otherwise, it is considered a domain for which NAPTR, SRV and A lookups are performed. If NAPTR or SRV queries fail, they fallback to using SRV and A queries. If the transport parameter is present in the URI, this will be used as far as it is part of the supported transports. If the URI has a {{{sips}}} schema, then only the TLS transport will be used as far as it doesn't conflict with the supported transports or the transport parameter. The return value is a list of {{{Route}}} objects containing the IP address, port and transport to use for routing in the order of preference given by the supported_transports argument.
38
  [[BR]]uri:[[BR]]
39
  A {{{(Frozen)SIPURI}}} from which the {{{host}}}, {{{port}}}, {{{parameters}}} and {{{secure}}} attributes are used.
40
  [[BR]]supported_transports:[[BR]]
41
  A sublist of {{{['udp', 'tcp', 'tls']}}} in the application's order of preference.
42
  [[BR]]timeout:[[BR]]
43
  How many seconds to wait for a response from a nameserver.
44
  [[BR]]lifetime:[[BR]]
45
  How many seconds to wait for a response from all nameservers in total.
46
47
==== notifications ====
48
49
 '''DNSLookupDidSucceed'''::
50
  This notification is sent when one of the lookup methods succeeds in finding a result.
51
  [[BR]]timestamp:[[BR]]
52
  A {{{datetime.datetime}}} object indicating when the notification was sent.
53
  [[BR]]result:[[BR]]
54
  The result of the DNS lookup in the format described in each method.
55
 '''DNSLookupDidFail'''::
56
  This notification is sent when one of the lookup methods fails in finding a result.
57
  [[BR]]timestamp:[[BR]]
58
  A {{{datetime.datetime}}} object indicating when the notification was sent.
59
  [[BR]]error:[[BR]]
60
  A {{{str}}} object describing the error which resulted in the DNS lookup failure.
61
 '''DNSLookupTrace'''::
62
  This notification is sent several times during a lookup process for each individual DNS query.
63
  [[BR]]timestamp:[[BR]]
64
  A {{{datetime.datetime}}} object indicating when the notification was sent.
65
  [[BR]]query_type:[[BR]]
66
  The type of the query, {{{"NAPTR"}}}, {{{"SRV"}}}, {{{"A"}}}, {{{"NS"}}} etc.
67
  [[BR]]query_name:[[BR]]
68
  The name which was queried.
69
  [[BR]]answer:[[BR]]
70
  The answer returned by dnspython, or {{{None}}} if an error occurred.
71
  [[BR]]error:[[BR]]
72
  The exception which caused the query to fail, or {{{None}}} if no error occurred.
73
  [[BR]]context:[[BR]]
74
  The name of the method which was called on the {{{DNSLookup}}} object.
75
  [[BR]]service:[[BR]]
76
  The service which was queried for, only available when context is {{{"lookup_service"}}}.
77
  [[BR]]uri:[[BR]]
78
  The uri which was queried for. 
79
80
=== Route ===
81
82
This is a convinience object which contains sufficient information to identify a route to a SIP proxy. This object is returned by {{{DNSLookup.lookup_sip_proxy}}} and can be used with the {{{Session}}} or a {{{(Frozen)RouteHeader}}} can be easily constructed from it to pass to one of the objects in the SIP core handling SIP dialogs/transactions ({{{Invitation}}}, {{{Subscription}}}, {{{Request}}}, {{{Registration}}}, {{{Message}}}, {{{Publication}}}). This object has three attributes which can be set in the constructor or after it was instantiated. They will only be documented as arguments to the constructor.
83
84
==== methods ====
85
86
 '''!__init!__'''(''self'', '''address''', '''port'''=None, '''transport'''={{{'udp'}}})::
87
  Creates the Route object with the specified parameters as attributes.
88
  Each of these attributes can be accessed on the object once instanced.
89
  [[BR]]''address'':[[BR]]
90
  The IPv4 address that the request in question should be sent to as a string.
91
  [[BR]]''port'':[[BR]]
92
  The port to send the requests to, represented as an int, or None if the default port is to be used.
93
  [[BR]]''transport'':[[BR]]
94
  The transport to use, this can be a string of either "udp", "tcp" or "tls" (case insensitive).
95
 '''get_uri'''(''self'')::
96
  Returns a {{{SIPURI}}} object which contains the adress, port and transport as parameter. This can be used to easily construct a {{{RouteHeader}}}:
97
  {{{
98
    route = Route("1.2.3.4", port=1234, transport="tls")
99
    route_header = RouteHeader(route.get_uri())
100
  }}}
101
102 62 Luci Stanescu
== High-level audio API ==
103
104
The high-level audio API hides the complexity of using the low-level PJMEDIA interface. This is implemented in the {{{sipsimple.audio}}} module and contains the following components:
105
 * IAudioPort: an interface describing an object capable of producing and/or consuming audio data.
106
 * AudioDevice: an object conforming to the IAudioPort interface which describes a physical audio device.
107
 * AudioBridge: a collection of objects conforming to IAudioPort which connects all of them in a full mesh.
108
 * WavePlayer: an object conforming to the IAudioPort interface which can playback the audio data from a {{{.wav}}} file.
109
 * WaveRecorder: an object conforming to the IAudioPort interface which can record audio data to a {{{.wav}}} file.
110
111
=== IAudioPort ===
112
113
The IAudioPort interface describes an object capable of producing and/or consuming audio data. This can be a dynamic object, which changes its role during its lifetime and notifies such changes using a notification, which is part of the interface.
114
115
==== attributes ====
116
117
 '''mixer'''::
118
  The {{{AudioMixer}}} this audio object is connected to. Only audio objects connected to the same mixer will be able to send audio data from one to another.
119
 '''consumer_slot'''::
120
  An integer representing the slot (see [wiki:SipCoreApiDocumentation#AudioMixer AudioMixer]) which this object uses to consume audio data, or {{{None}}} if this object is not a consumer.
121
 '''producer_slot'''::
122
  An integer representing the slot (see [wiki:SipCoreApiDocumentation#AudioMixer AudioMixer]) which this object uses to produce audio data, or {{{None}}} if this object is not a producer.
123
124
==== notifications ====
125
 
126
 '''AudioPortDidChangeSlots'''::
127
  This notification needs to be sent by implementations of this interface when the slots it has change, so as to let the {{{AudioBridges}}} it is part of know that reconnections need to be made.
128
  [[BR]]consumer_slot_changed:[[BR]]
129
  A bool indicating whether the consumer slot was changed.
130
  [[BR]]producer_slot_changed:[[BR]]
131
  A bool indicating whether the producer slot was changed.
132
  [[BR]]old_consumer_slot:[[BR]]
133
  The old slot for consuming audio data. Only required if consumer_slot_changed is {{{True}}}.
134
  [[BR]]new_consumer_slot:[[BR]]
135
  The new slot for consuming audio data. Only required if consumer_slot_changed is {{{True}}}.
136
  [[BR]]old_producer_slot:[[BR]]
137
  The old slot for producing audio data. Only required if producer_slot_changed is {{{True}}}.
138
  [[BR]]new_producer_slot:[[BR]]
139
  The new slot for producing audio data. Only required if producer_slot_changed is {{{True}}}.
140
141
=== AudioDevice ===
142
143
The AudioDevice represents the physical audio device which is part of a {{{AudioMixer}}}, implementing the {{{IAudioPort}}} interface. As such, it can be uniquely identified by the mixer it represents.
144
145
==== methods ====
146
147
 '''!__init!__'''(''self'', '''mixer''', '''input_muted'''={{{False}}}, '''output_muted'''={{{False}}}):
148
  Instantiates a new AudioDevice which represents the physical device associated with the specified {{{AudioMixer}}}.
149
  [[BR]]mixer:[[BR]]
150
  The {{{AudioMixer}}} whose physical device this object represents.
151
  [[BR]]input_muted:[[BR]]
152
  A boolean which indicates whether this object should act as a producer of audio data.
153
  [[BR]]output_muted:[[BR]]
154
  A boolean which indicates whether this object should act as a consumer of audio data.
155
156
==== attributes ====
157
158
 '''input_muted'''::
159
  A writable property which controls whether this object should act as a producer of audio data. An {{{AudioPortDidChange}}} slots notification is sent when this attribute is changed to force connections to be reconsidered within the {{{AudioBridges}}} this object is part of.
160
 '''output_muted'''::
161
  A writable property which controls whether this object should act as a consumer of audio data. An {{{AudioPortDidChange}}} slots notification is sent when this attribute is changed to force connections to be reconsidered within  the {{{AudioBridges}}} this object is part of.
162
163
=== AudioBridge ===
164
165
The {{{AudioBridge}}} is the basic component which is able to connect {{{IAudioPort}}} implementations. It acts as a container which connects as the producers to all the consumers which are part of it. An object which is both a producer and a consumer of audio data will not be connected to itself. Being an implementation of {{{IAudioPort}}} itself, an {{{AudioBridge}}} can be part of another {{{AudioBridge}}}. The {{{AudioBridge}}} does not keep strong references to the ports it contains and once the port's reference count reaches 0, it is automatically removed from the {{{AudioBridge}}}.
166
> Note: although this is not enforced, there should never be any cycles when connecting {{{AudioBridges}}}.
167
168
==== methods ====
169
170
 '''!__init!__'''(''self'', '''mixer''')::
171
  Instantiate a new {{{AudioBridge}}} which uses the specified {{{AudioMixer}}} for mixing.
172
 '''add'''(''self'', '''port''')::
173
  Add an implementation of {{{IAudioPort}}} to this AudioBridge. This will connect the new port to all the existing ports of the bridge. A port cannot be added more than once to an {{{AudioBridge}}}; thus, this object acts like a set.
174
 '''remove'''(''self'', '''port''')::
175
  Remove a port from this {{{AudioBridge}}}. The port must have previously been added to the {{{AudioBridge}}}, otherwise a {{{ValueError}}} is raised.
176
177
=== WavePlayer ===
178
179
A {{{WavePlayer}}} is an implementation of {{{IAudioPort}}} which is capable of producing audio data read from a {{{.wav}}} file. This object is completely reusable, as it can be started and stopped any number of times.
180
181
==== methods ====
182
183
 '''!__init!__'''(''self'', '''mixer''', '''filename''', '''volume'''={{{100}}}, '''loop_count'''={{{1}}}, '''pause_time'''={{{0}}}, '''initial_play'''={{{True}}})::
184
  Instantiate a new {{{WavePlayer}}} which is capable of playing a {{{.wav}}} file repeatedly. All the parameters are available as attributes of the object, but should not be changed once the object has been started.
185
  [[BR]]mixer:[[BR]]
186
  The {{{AudioMixer}}} this object is connected to.
187
  [[BR]]filename:[[BR]]
188
  The full path to the {{{.wav}}} file from which audio data is to be read.
189
  [[BR]]volume:[[BR]]
190
  The volume at which the file should be played.
191
  [[BR]]loop_count:[[BR]]
192
  The number of times the file should be played, or {{{0}}} for infinity.
193
  [[BR]]pause_time:[[BR]]
194
  How many seconds to wait between successive plays of the file. 
195
  [[BR]]initial_play:[[BR]]
196
  Whether or not the file to play once the {{{WavePlayer}}} is started, or to wait {{{pause_time}}} seconds before the first play.
197
 '''start'''(''self'')::
198
  Start playing the {{{.wav}}} file.
199
 '''stop'''(''self'')::
200
  Stop playuing the {{{.wav}}} file immediately.
201
202
==== attributes ====
203
204
 '''is_active'''::
205
  A boolean indicating whether or not this {{{WavePlayer}}} is currently playing.
206
207
==== notifications ====
208
209
 '''WavePlayerDidStart'''::
210
  This notification is sent when the {{{WavePlayer}}} starts playing the file the first time after the {{{start()}}} method has been called.
211
  [[BR]]timestamp:[[BR]]
212
  A {{{datetime.datetime}}} object indicating when the notification was sent.
213
 '''WavePlayerDidEnd'''::
214
  This notification is sent when the {{{WavePlayer}}} is done playing either as a result of playing the number of times it was told to, or because the {{{stop()}}} method has been called.
215
  [[BR]]timestamp:[[BR]]
216
  A {{{datetime.datetime}}} object indicating when the notification was sent.
217
 '''WavePlayerDidFail'''::
218
  This notification is sent when the {{{WavePlayer}}} is not capable of playing the {{{.wav}}} file.
219
  [[BR]]timestamp:[[BR]]
220
  A {{{datetime.datetime}}} object indicating when the notification was sent.
221
  [[BR]]error:[[BR]]
222
  The exception raised by the {{{WaveFile}}} which identifies the cause for not being able to play the {{{.wav}}} file.
223
224
=== WaveRecorder ===
225
226
A {{{WaveRecorder}}} is an implementation of {{{IAudioPort}}} is is capable of consuming audio data and writing it to a {{{.wav}}} file. Just like {{{WavePlayer}}}, this object is reusable: once stopped it can be started again, but if the filename attribute is not changed, the previously written file will be overwritten.
227
228
==== methods ====
229
230
 '''!__init!__'''(''self'', '''mixer''', '''filename''')::
231
  Instantiate a new {{{WaveRecorder}}}.
232
  [[BR]]mixer:[[BR]]
233
  The {{{AudioMixer}}} this {{{WaveRecorder}}} is connected to.
234
  [[BR]]filename:[[BR]]
235
  The full path to the {{{.wav}}} file where this object should write the audio data. The file must be writable. The directories up to the file will be created if possible when the {{{start()}}} method is called.
236
 '''start'''(''self'')::
237
  Start consuming audio data and writing it to the {{{.wav}}} file. If this object is not part of an {{{AudioBridge}}}, not audio data will be written.
238
 '''stop'''(''self'')::
239
  Stop consuming audio data and close the {{{.wav}}} file.
240
241
==== attributes ====
242
243
 '''is_active'''::
244
  A boolean indicating whether or not this {{{WaveRecorder}}} is currently recording audio data.
245
246 1 Adrian Georgescu
== SIPApplication ==
247
248 62 Luci Stanescu
Implemented in [browser:sipsimple/application.py]
249 1 Adrian Georgescu
250 62 Luci Stanescu
Implements a high-level application responsable for starting and stopping various sub-systems required to implement a fully featured SIP User Agent application. The SIPApplication class is a Singleton and can be instantiated from any part of the code, obtaining a reference to the same object. The SIPApplication takes care of initializing the following components:
251
 * the twisted thread
252
 * the configuration system, via the [wiki:SipConfigurationAPI#ConfigurationManager ConfigurationManager].
253
 * the core [wiki:SipCoreApiDocumentation#Engine Engine] using the settings in the configuration
254
 * the [wiki:SipMiddlewareApi#AccountManager AccountManager], using the accounts in the configuration
255 63 Luci Stanescu
 * the [wiki:SipMiddlewareApi#SessionManager SessionManager], in order to handle incoming sessions
256 62 Luci Stanescu
 * two [wiki:SipMiddlewareApi#AudioBridge AudioBridges], using the settings in the configuration
257 1 Adrian Georgescu
258 62 Luci Stanescu
The attributes in this class can be set and accessed on both this class and its subclasses, as they are implemented using descriptors which keep single value for each attribute, irrespective of the class from which that attribute is set/accessed. Usually, all attributes should be considered read-only.
259 1 Adrian Georgescu
260 62 Luci Stanescu
=== Methods  ===
261
262
 '''!__init!__'''(''self'')::
263
  Instantiates a new SIPApplication.
264
 '''start'''(''self'', '''config_backend''')::
265
  Starts the {{{SIPApplication}}} which initializes all the components in the correct order. The {{{config_backend}}} is used to start the {{{ConfigurationManager}}}. If any error occurs with loading the configuration, the exception raised by the {{{ConfigurationManager}}} is propagated by this method and {{{SIPApplication}}} can be started again. After this, any fatal errors will result in the SIPApplication being stopped and unusable, which means the whole application will need to stop. This method returns as soon as the twisted thread has been started, which means the application must wait for the {{{SIPApplicationDidStart}}} notification in order to know that the application started.
266
 '''stop'''(''self'')::
267
  Stop all the components started by the SIPApplication. This method returns immediately, but a {{{SIPApplicationDidEnd}}} notification is sent when all the components have been stopped.
268
269 1 Adrian Georgescu
=== Attributes ===
270
271 62 Luci Stanescu
 '''running'''::
272
  {{{True}}} if the SIPApplication is running (it has been started and it has not been told to stop), {{{False}}} otherwise.
273
 '''alert_audio_mixer'''::
274
  The {{{AudioMixer}}} object created on the alert audio device as defined by the configuration (by SIPSimpleSettings.audio.alert_device).
275
 '''alert_audio_bridge'''::
276
  An {{{AudioBridge}}} where {{{IAudioPort}}} objects can be added to playback sound to the alert device.
277
 '''alert_audio_device'''::
278
  An {{{AudioDevice}}} which corresponds to the alert device as defined by the configuration. This will always be part of the alert_audio_bridge.
279
 '''voice_audio_mixer'''::
280
  The {{{AudioMixer}}} object created on the voice audio device as defined by the configuration (by SIPSimpleSettings.audio.input_device and SIPSimpleSettings.audio.output_device).
281
 '''voice_audio_bridge'''::
282
  An {{{AudioBridge}}} where {{{IAudioPort}}} objects can be added to playback sound to the output device or record sound from the input device.
283
 '''voice_audio_device'''::
284
  An {{{AudioDevice}}} which corresponds to the voice device as defined by the configuration. This will always be part of the voice_audio_bridge.
285 1 Adrian Georgescu
286
=== Notifications  ===
287 62 Luci Stanescu
288
 '''SIPApplicationWillStart'''::
289
  This notification is sent just after the configuration has been loaded and the twisted thread started, but before any other components have been initialized.
290
  [[BR]]timestamp:[[BR]]
291
  A {{{datetime.datetime}}} object indicating when the notification was sent.
292
 '''SIPApplicationDidStart'''::
293
  This notification is sent when all the components have been initialized. Note: it doesn't mean that all components have succeeded, for example, the account might not have registered by this time, but the registration process will have started.
294
  [[BR]]timestamp:[[BR]]
295
  A {{{datetime.datetime}}} object indicating when the notification was sent.
296
 '''SIPApplicationWillEnd'''::
297
  This notification is sent as soon as the {{{stop()}}} method has been called.
298
  [[BR]]timestamp:[[BR]]
299
  A {{{datetime.datetime}}} object indicating when the notification was sent.
300
 '''SIPApplicationDidEnd'''::
301
  This notification is sent when all the components have been stopped. All components have been given reasonable time to shutdown gracefully, such as the account unregistering. However, because of factors outside the control of the middleware, such as network problems, some components might not have actually shutdown gracefully; this is needed because otherwise the SIPApplication could hang indefinitely (for example because the system is no longer connected to a network and it cannot be determined when it will be again).
302
  [[BR]]timestamp:[[BR]]
303
  A {{{datetime.datetime}}} object indicating when the notification was sent.
304
 '''SIPApplicationFailedToStartTLS'''::
305
  This notification is sent when a problem arises with initializing the TLS transport. In this case, the Engine will be started without TLS support and this notification contains the error which identifies the cause for not being able to start the TLS transport.
306
  [[BR]]timestamp:[[BR]]
307
  A {{{datetime.datetime}}} object indicating when the notification was sent.
308
  [[BR]]error:[[BR]]
309
  The exception raised by the Engine which identifies the cause for not being able to start the TLS transport.
310 50 Adrian Georgescu
311 1 Adrian Georgescu
312 63 Luci Stanescu
== SIP Sessions ==
313 1 Adrian Georgescu
314 63 Luci Stanescu
SIP sessions are supported by the {{{sipsimple.session.Session}}} class and independent stream classes, which need to implement the {{{sipsimple.streams.IMediaStream}}} interface. The {{{Session}}} class takes care of the signalling, while the streams offer the actual media support which is negotiated by the {{{Session}}}. The streams which are implemented in the SIP SIMPLE middleware are provided in modules within the {{{sipsimple.streams}}} package, but they are accessible for import directly from {{{sipsimple.streams}}}. Currently, the middleware implements two types of streams, one for RTP data, with a concrete implementation in the {{{AudioStream}}} class, and one for MSRP sessions, with concrete implementations in the {{{ChatStream}}}, {{{FileTransferStream}}} and {{{DesktopSharingStream}}} classes. However, the application can provide its own stream implementation, provided they respect the {{{IMediaStream}}} interface.
315
316
=== Session ===
317 51 Adrian Georgescu
318 44 Adrian Georgescu
[[Image(sipsimple-session-state-machine.png, align=right, width=400)]]
319 1 Adrian Georgescu
320
Implemented in [browser:sipsimple/session.py]
321 26 Luci Stanescu
322 1 Adrian Georgescu
A {{{sipsimple.session.Session}}} object represents a complete SIP session between the local and a remote endpoints. Both incoming and outgoing sessions are represented by this class.
323
324
A {{{Session}}} instance is a stateful object, meaning that it has a {{{state}}} attribute and that the lifetime of the session traverses different states, from session creation to termination.
325 2 Adrian Georgescu
State changes are triggered by methods called on the object by the application or by received network events.
326 1 Adrian Georgescu
These states and their transitions are represented in the following diagram:
327 63 Luci Stanescu
328 1 Adrian Georgescu
Although these states are crucial to the correct operation of the {{{Session}}} object, an application using this object does not need to keep track of these states, as a set of notifications is also emitted, which provide all the necessary information to the application.
329 63 Luci Stanescu
330
The {{{Session}}} is completely independent of the streams it contains, which need to be implementations of the {{{sipsimple.streams.IMediaStream}}} interface. This interface provides the API by which the {{{Session}}} communicates with the streams. This API should not be used by the application, unless it also provides stream implementations or a SIP INVITE session implementation.
331
332
==== methods ====
333
334
 '''!__init!__'''(''self'', '''account''')::
335
  Creates a new {{{Session}}} object in the {{{None}}} state.
336
  [[BR]]''account'':[[BR]]
337
  The local account to be associated with this {{{Session}}}.
338
 '''connect'''(''self'', '''to_header''', '''routes''', '''streams''')::
339
  Will set up the {{{Session}}} as outbound and propose the new session to the specified remote party and move the state machine to the {{{outgoing}}} state.
340
  Before contacting the remote party, a {{{SIPSessionNewOutgoing}}} notification will be emitted.
341
  If there is a failure or the remote party rejected the offer, a {{{SIPSessionDidFail}}} notification will be sent.
342
  Any time a ringing indication is received from the remote party, a {{{SIPSessionGotRingIndication}}} notification is sent.
343
  If the remote party accepted the session, a {{{SIPSessionWillStart}}} notification will be sent, followed by a {{{SIPSessionDidStart}}} notification when the session is actually established.
344
  This method may only be called while in the {{{None}}} state.
345
  [[BR]]''to_header'':[[BR]]
346
  A {{{sipsimple.core.ToHeader}}} object representing the remote identity to initiate the session to.
347
  [[BR]]''routes'':[[BR]]
348
  An iterable of {{{sipsimple.util.Route}}} objects, specifying the IP, port and transport to the outbound proxy.
349
  These routes will be tried in order, until one of them succeeds.
350
  [[BR]]''streams'':[[BR]]
351
  A list of stream objects which will be offered to the remote endpoint.
352
 '''send_ring_indication'''(''self'')::
353
  Sends a 180 provisional response in the case of an incoming session.
354
 '''accept'''(''self'', '''streams''')::
355
  Calling this methods will accept an incoming session and move the state machine to the {{{accepting}}} state.
356
  When there is a new incoming session, a {{{SIPSessionNewIncoming}}} notification is sent, after which the application can call this method on the sender of the notification.
357
  After this method is called, {{{SIPSessionWillStart}}} followed by {{{SIPSessionDidStart}}} will be emitted, or {{{SIPSessionDidFail}}} on an error.
358
  This method may only be called while in the {{{incoming}}} state.
359
  [[BR]]''streams'':[[BR]]
360
  A list of streams which needs to be a subset of the proposed streams which indicates which streams are to be accepted. All the other proposed streams will be rejected.
361
 '''reject'''(''self'', '''code'''={{{603}}}, '''reason'''={{{None}}})::
362
  Reject an incoming session and move it to the {{{terminaing}}} state, which eventually leads to the {{{terminated}}} state.
363
  Calling this method will cause the {{{Session}}} object to emit a {{{SIPSessionDidFail}}} notification once the session has been rejected.
364
  This method may only be called while in the {{{incoming}}} state.
365
  [[BR]]''code'':[[BR]]
366
  An integer which represents the SIP status code in the response which is to be sent. Usually, this is either 486 (Busy) or 603 (Decline/Busy Everywhere).
367
  [[BR]]''reason'':[[BR]]
368
  The string which is to be sent as the SIP status reason in the response, or None if PJSIP's default reason for the specified code is to be sent.
369
 '''accept_proposal'''(''self'', '''streams''')::
370
  When the remote party proposes to add some new streams, signaled by the {{{SIPSessionGotProposal}}} notification, the application can use this method to accept the stream(s) being proposed.
371
  After calling this method a {{{SIPSessionGotAcceptProposal}}} notification is sent, unless an error occurs while setting up the new stream, in which case a {{{SIPSessionHadProposalFailure}}} notification is sent and a rejection is sent to the remote party. As with any action which causes the streams in the session to change, a {{{SIPSessionDidRenegotiateStreams}}} notification is also sent.
372
  This method may only be called while in the {{{received_proposal}}} state.
373
  [[BR]]''streams'':[[BR]]
374
  A list of streams which needs to be a subset of the proposed streams which indicates which streams are to be accepted. All the other proposed streams will be rejected.
375
 '''reject_proposal'''(''self'', '''code'''={{{488}}}, '''reason'''={{{None}}})::
376
  When the remote party proposes new streams that the application does not want to accept, this method can be used to reject the proposal, after which a {{{SIPSessionGotRejectProposal}}} or {{{SIPSessionHadProposalFailure}}} notification is sent.
377
  This method may only be called while in the {{{received_proposal}}} state.
378
  [[BR]]''code'':[[BR]]
379
  An integer which represents the SIP status code in the response which is to be sent. Usually, this is 488 (Not Acceptable Here).
380
  [[BR]]''reason'':[[BR]]
381
  The string which is to be sent as the SIP status reason in the response, or None if PJSIP's default reason for the specified code is to be sent.
382
 '''add_stream'''(''self'', '''stream''')::
383
  Proposes a new stream to the remote party.
384
  Calling this method will cause a {{{SIPSessionGotProposal}}} notification to be emitted.
385
  After this, the state machine will move into the {{{sending_proposal}}} state until either a {{{SIPSessionGotAcceptProposal}}}, {{{SIPSessionGotRejectProposal}}} or {{{SIPSessionHadProposalFailure}}} notification is sent, informing the application if the remote party accepted the proposal. As with any action which causes the streams in the session to change, a {{{SIPSessionDidRenegotiateStreams}}} notification is also sent.
386
  This method may only be called while in the {{{connected}}} state.
387
 '''remove_stream'''(''self'', '''stream''')::
388
  Stop the stream and remove it from the session, informing the remote party of this. Although technically this is also done via an SDP negotiation which may fail, the stream will always get remove (if the remote party refuses the re-INVITE, the result will be that the remote party will have a different view of the active streams than the local party).
389
  This method may only be called while in the {{{connected}}} state.
390
 '''cancel_proposal'''(''self'')::
391
  This method cancels a proposal of adding a stream to the session by sending a CANCEL request. A {{{SIPSessionGotRejectProposal}}} notification will be sent with code 487.
392
 '''hold'''(''self'')::
393
  Put the streams of the session which support the notion of hold on hold.
394
  This will cause a {{{SIPSessionDidChangeHoldState}}} notification to be sent.
395
  This method may be called in any state and will send the re-INVITE as soon as it is possible.
396
 '''unhold'''(''self'')::
397
  Take the streams of the session which support the notion of hold out of hold.
398
  This will cause a {{{SIPSessionDidChangeHoldState}}} notification to be sent.
399
  This method may be called in any state and will send teh re-INVITE as soon as it is possible.
400
 '''end'''(''self'')::
401
  This method may be called any time after the {{{Session}}} has started in order to terminate the session by sending a BYE request.
402 1 Adrian Georgescu
  Right before termination a {{{SIPSessionWillEnd}}} notification is sent, after termination {{{SIPSessionDidEnd}}} is sent.
403
404 64 Luci Stanescu
==== attributes ====
405 1 Adrian Georgescu
406
 '''state'''::
407
  The state the object is currently in, being one of the states from the diagram above.
408
 '''account'''::
409 19 Ruud Klaver
  The {{{sipsimple.account.Account}}} or {{{sipsimple.account.BonjourAccount}}} object that the {{{Session}}} is associated with.
410 1 Adrian Georgescu
  On an outbound session, this is the account the application specified on object instantiation.
411
 '''direction'''::
412 32 Adrian Georgescu
  A string indicating the direction of the initial negotiation of the session.
413 63 Luci Stanescu
  This can be either {{{None}}}, "incoming" or "outgoing".
414
 '''transport'''::
415 1 Adrian Georgescu
  A string representing the transport this {{{Session}}} is using: {{{"udp"}}}, {{{"tcp"}}} or {{{"tls"}}}.
416
 '''start_time'''::
417
  The time the session started as a {{{datetime.datetime}}} object, or {{{None}}} if the session was not yet started.
418
 '''stop_time'''::
419
  The time the session stopped as a {{{datetime.datetime}}} object, or {{{None}}} if the session has not yet terminated.
420
 '''on_hold'''::
421
  Boolean indicating whether the session was put on hold, either by the local or the remote party.
422
 '''remote_user_agent'''::
423
  A string indicating the remote user agent, if it provided one.
424 63 Luci Stanescu
  Initially this will be {{{None}}}, it will be set as soon as this information is received from the remote party (which may be never).
425
 '''local_identity'''::
426
  The {{{sipsimple.core.FrozenFromHeader}}} or {{{sipsimple.core.FrozenToHeader}}} identifying the local party, if the session is active, {{{None}}} otherwise.
427
 '''remote_identity'''::
428
  The {{{sipsimple.core.FrozenFromHeader}}} or {{{sipsimple.core.FrozenToHeader}}} identifying the remote party, if the session is active, {{{None}}} otherwise.
429
 '''streams'''::
430
  A list of the currently active streams in the {{{Session}}}.
431
 '''proposed_streams'''::
432 1 Adrian Georgescu
  A list of the currently proposed streams in the {{{Session}}}, or {{{None}}} if there is no proposal in progress.
433
434 64 Luci Stanescu
==== notifications ====
435 1 Adrian Georgescu
436
 '''SIPSessionNewIncoming'''::
437 26 Luci Stanescu
  Will be sent when a new incoming {{{Session}}} is received.
438 63 Luci Stanescu
  The application should listen for this notification to get informed of incoming sessions.
439 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
440
  A {{{datetime.datetime}}} object indicating when the notification was sent.
441
  [[BR]]''streams'':[[BR]]
442 63 Luci Stanescu
  A list of streams that were proposed by the remote party.
443 1 Adrian Georgescu
 '''SIPSessionNewOutgoing'''::
444
  Will be sent when the applcation requests a new outgoing {{{Session}}}.
445
  [[BR]]''timestamp'':[[BR]]
446
  A {{{datetime.datetime}}} object indicating when the notification was sent.
447
  [[BR]]''streams'':[[BR]]
448 63 Luci Stanescu
  A list of streams that were proposed to the remote party.
449 1 Adrian Georgescu
 '''SIPSessionGotRingIndication'''::
450
  Will be sent when an outgoing {{{Session}}} receives an indication that a remote device is ringing.
451
  [[BR]]''timestamp'':[[BR]]
452 26 Luci Stanescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
453 63 Luci Stanescu
 '''SIPSessionGotProvisionalResponse'''::
454
  Will be sent whenever the {{{Session}}} receives a provisional response as a result of sending a (re-)INVITE.
455
  [[BR]]''timestamp'':[[BR]]
456
  A {{{datetime.datetime}}} object indicating when the notification was sent.
457
  [[BR]]''code'':[[BR]]
458
  The SIP status code received.
459
  [[BR]]''reason'':[[BR]]
460
  The SIP status reason received.
461 1 Adrian Georgescu
 '''SIPSessionWillStart'''::
462
  Will be sent just before a {{{Session}}} completes negotiation.
463
  In terms of SIP, this is sent after the final response to the {{{INVITE}}}, but before the {{{ACK}}}.
464
  [[BR]]''timestamp'':[[BR]]
465
  A {{{datetime.datetime}}} object indicating when the notification was sent.
466
 '''SIPSessionDidStart'''::
467 63 Luci Stanescu
  Will be sent when a {{{Session}}} completes negotiation and all the streams have started.
468 26 Luci Stanescu
  In terms of SIP this is sent after the {{{ACK}}} was sent or received.
469 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
470
  A {{{datetime.datetime}}} object indicating when the notification was sent.
471 63 Luci Stanescu
  [[BR]]''streams'':[[BR]]
472
  The list of streams which now form the active streams of the {{{Session}}}.
473 1 Adrian Georgescu
 '''SIPSessionDidFail'''::
474 63 Luci Stanescu
  This notification is sent whenever the session fails before it starts.
475 5 Redmine Admin
  The failure reason is included in the data attributes.
476 63 Luci Stanescu
  This notification is never followed by {{{SIPSessionDidEnd}}}.
477 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
478 26 Luci Stanescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
479 1 Adrian Georgescu
  [[BR]]''originator'':[[BR]]
480 63 Luci Stanescu
  A string indicating the originator of the {{{Session}}}. This will either be "local" or "remote".
481 1 Adrian Georgescu
  [[BR]]''code'':[[BR]]
482
  The SIP error code of the failure.
483
  [[BR]]''reason'':[[BR]]
484 63 Luci Stanescu
  A SIP status reason.
485
  [[BR]]''failure_reason'':[[BR]]
486
  A string which represents the reason for the failure, such as {{{"user_request"}}}, {{{"missing ACK"}}}, {{{"SIP core error..."}}}.
487 1 Adrian Georgescu
 '''SIPSessionWillEnd'''::
488 63 Luci Stanescu
  Will be sent just before terminating a {{{Session}}}.
489 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
490
  A {{{datetime.datetime}}} object indicating when the notification was sent.
491
 '''SIPSessionDidEnd'''::
492 63 Luci Stanescu
  Will be sent always when a {{{Session}}} ends as a result of remote or local session termination.
493 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
494 19 Ruud Klaver
  A {{{datetime.datetime}}} object indicating when the notification was sent.
495
  [[BR]]''originator'':[[BR]]
496 63 Luci Stanescu
  A string indicating who originated the termination. This will either be "local" or "remote".
497
  [[BR]]''end_reason'':[[BR]]
498
  A string representing the termination reason, such as {{{"user_request"}}}, {{{"SIP core error..."}}}.
499
 '''SIPSessionDidChangeHoldState'''::
500
  Will be sent when the session got put on hold or removed from hold, either by the local or the remote party.
501 1 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
502
  A {{{datetime.datetime}}} object indicating when the notification was sent.
503
  [[BR]]''originator'':[[BR]]
504
  A string indicating who originated the hold request, and consequently in which direction the session got put on hold.
505 63 Luci Stanescu
  [[BR]]''on_hold'':[[BR]]
506
  {{{True}}} if there is at least one stream which is on hold and {{{False}}} otherwise.
507
  [[BR]]''partial'':[[BR]]
508
  {{{True}}} if there is at least one stream which is on hold and one stream which supports hold but is not on hold and {{{False}}} otherwise.
509
 '''SIPSessionGotProposal'''::
510
  Will be sent when either the local or the remote party proposes to add streams to the session.
511 26 Luci Stanescu
  [[BR]]''timestamp'':[[BR]]
512 23 Ruud Klaver
  A {{{datetime.datetime}}} object indicating when the notification was sent.
513
  [[BR]]''originator'':[[BR]]
514 63 Luci Stanescu
  The party that initiated the stream proposal, can be either "local" or "remote".
515
  [[BR]]''streams'':[[BR]]
516
  A list of streams that were proposed.
517
 '''SIPSessionGotRejectProposal'''::
518
  Will be sent when either the local or the remote party rejects a proposal to have streams added to the session.
519 6 Ruud Klaver
  [[BR]]''timestamp'':[[BR]]
520
  A {{{datetime.datetime}}} object indicating when the notification was sent.
521 63 Luci Stanescu
  [[BR]]''originator'':[[BR]]
522
  The party that initiated the stream proposal, can be either "local" or "remote".
523 6 Ruud Klaver
  [[BR]]''code'':[[BR]]
524 63 Luci Stanescu
  The code with which the proposal was rejected.
525 1 Adrian Georgescu
  [[BR]]''reason'':[[BR]]
526 63 Luci Stanescu
  The reason for rejecting the stream proposal.
527
  [[BR]]''streams'':[[BR]]
528
  The list of streams which were rejected.
529
 '''SIPSessionGotAcceptProposal'''::
530
  Will be sent when either the local or the remote party accepts a proposal to have stream( added to the session.
531 24 Ruud Klaver
  [[BR]]''timestamp'':[[BR]]
532 1 Adrian Georgescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
533 63 Luci Stanescu
  [[BR]]''originator'':[[BR]]
534
  The party that initiated the stream proposal, can be either "local" or "remote".
535 1 Adrian Georgescu
  [[BR]]''streams'':[[BR]]
536 63 Luci Stanescu
  The list of streams which were accepted.
537
 '''SIPSessionHadProposalFailure'''::
538 24 Ruud Klaver
  Will be sent when a re-INVITE fails because of an internal reason (such as a stream not being able to start).
539
  [[BR]]''timestamp'':[[BR]]
540 63 Luci Stanescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
541
  [[BR]]''failure_reason'':[[BR]]
542
  The error which caused the proposal to fail.
543
  [[BR]]''streams'':[[BR]]
544
  THe streams which were part of this proposal.
545 24 Ruud Klaver
 '''SIPSessionDidRenegotiateStreams'''::
546 6 Ruud Klaver
  Will be sent when a media stream is either activated or deactivated.
547 26 Luci Stanescu
  An application should listen to this notification in order to know when a media stream can be used.
548 63 Luci Stanescu
  [[BR]]''timestamp'':[[BR]]
549 6 Ruud Klaver
  A {{{datetime.datetime}}} object indicating when the notification was sent.
550 63 Luci Stanescu
  [[BR]]''action'':[[BR]]
551
  A string which is either {{{"add"}}} or {{{"remove"}}} which specifies what happened to the streams the notificaton referes to
552
  [[BR]]''streams'':[[BR]]
553
  A list with the streams which were added or removed.
554
 '''SIPSessionDidProcessTransaction'''::
555
  Will be sent whenever a SIP transaction is complete in order to provide low-level details of the progress of the INVITE dialog.
556 37 Luci Stanescu
  [[BR]]''timestamp'':[[BR]]
557
  A {{{datetime.datetime}}} object indicating when the notification was sent.
558
  [[BR]]''originator'':[[BR]]
559
  The initiator of the transaction, {{{"local"}}} or {{{"remote"}}}.
560
  [[BR]]''method'':[[BR]]
561
  The method of the request.
562
  [[BR]]''code'':[[BR]]
563
  The SIP status code of the response.
564
  [[BR]]''reason'':[[BR]]
565
  The SIP status reason of the response.
566
  [[BR]]''ack_received'':[[BR]]
567
  This attribute is only present for INVITE transactions and has one of the values {{{True}}}, {{{False}}} or {{{"unknown"}}}. The last value may occur then PJSIP does not let us know whether the ACK was received or not.
568 1 Adrian Georgescu
569 37 Luci Stanescu
As an example for how to use the {{{Session}}} object, the following provides a basic Python program that initiates an outgoing SIP session request:
570
571
{{{
572
from threading import Event
573 50 Adrian Georgescu
574 48 Adrian Georgescu
from application.notification, NotificationCenter
575 37 Luci Stanescu
576
from sipsimple.core import SIPURI, ToHeader
577 50 Adrian Georgescu
578 38 Luci Stanescu
from sipsimple.account import AccountManager
579
from sipsimple.application import SIPApplication
580
from sipsimple.session import Session
581 50 Adrian Georgescu
from sipsimple.streams import AudioStream
582 38 Luci Stanescu
from sipsimple.util import Route
583 1 Adrian Georgescu
584 38 Luci Stanescu
585
class SimpleCallApplication(SIPApplication):
586 1 Adrian Georgescu
    def __init__(self, callee, route):
587
        SIPApplication.__init__(self)
588
        self.ended = Event()
589
        self.callee = calee
590 38 Luci Stanescu
        self.route = route
591
        self.session = None
592
        notification_center = NotificationCenter()
593
        notification_center.add_observer(self)
594 1 Adrian Georgescu
595
    def _NH_SIPApplicationDidStart(self, notification):
596
        account = AccountManager().default_account
597 38 Luci Stanescu
        self.session = Session(account)
598
        self.session.connect(self.callee, self.route, AudioStream(account))
599 1 Adrian Georgescu
600 38 Luci Stanescu
    def _NH_SIPSessionGotRingIndication(self, notification):
601
        print 'Ringing!'
602
603
    def _NH_SIPSessionDidStart(self, notification):
604
        print 'Session started!'
605
606
    def _NH_SIPSessionDidFail(self, notification):
607
        print 'Failed to connect'
608 1 Adrian Georgescu
        self.stop()
609 38 Luci Stanescu
610
    def _NH_SIPSessionDidEnd(self, notification):
611
        print 'Session ended'
612 1 Adrian Georgescu
        self.stop()
613
614 39 Luci Stanescu
    def _NH_SIPApplicationDidEnd(self, notification):
615 50 Adrian Georgescu
        self.ended.set()
616 39 Luci Stanescu
617
# place an audio call from the specified account to the specified URI, through
618
# the specified SIP proxy
619
application = SimpleCallApplication(ToHeader(SIPURI(user="bob", host="example.com")), Route("1.2.3.4"))
620
# block waiting for user input
621
print "Placing call, press enter to quit program"
622
raw_input()
623
application.session.end()
624
# block until the SIPApplication has stopped
625 1 Adrian Georgescu
application.ended.wait()
626 50 Adrian Georgescu
}}}
627 48 Adrian Georgescu
628 64 Luci Stanescu
=== SessionManager ===
629 39 Luci Stanescu
630
Implemented in [browser:sipsimple/session.py]
631
632 1 Adrian Georgescu
The {{{sipsimple.session.SessionManager}}} class is a singleton, which acts as the central aggregation point for sessions within the middleware.
633 50 Adrian Georgescu
Although it is mainly used internally, the application can use it to query information about all active sessions.
634 39 Luci Stanescu
The SessionManager is implemented as a singleton, meaning that only one instance of this class exists within the middleware. The SessionManager is started by the SIPApplication and takes care of handling incoming sessions.
635
636 64 Luci Stanescu
==== attributes ====
637 39 Luci Stanescu
638
 '''sessions'''::
639
  A property providing a copy of the list of all active {{{Sesssion}}} objects within the application, meaning any {{{Session}}} object that exists globally within the application and is not in the {{{NULL}}} or {{{TERMINATED}}} state.
640
641 64 Luci Stanescu
==== methods ====
642 39 Luci Stanescu
643
 '''!__init!__'''(''self'')::
644
  Instantiate a new {{{SessionManager}}} object.
645
646
 '''start'''(''self'')::
647
  Start the {{{SessionManager}}} in order to be able to handle incoming sessions.
648
649
== IMediaStream ==
650
651
Implemented in [browser:sipsimple/streams/__init__.py]
652
653
This module automatically registers media streams to a stream registry
654
allowing for a plug and play mechanism of various types of media negoticated
655
in a SIP session that can be added to this library by using a generic API.
656
657
For actual usage see rtp.py and msrp.py that implement media streams based
658
on their respective RTP and MSRP protocols.
659 55 Adrian Georgescu
660
661
=== Atributes ===
662
663
 '''type''' (class attribute)::
664
 A string identifying the stream type (ex: audio, video, ...)
665
 '''priority'''::
666
 An integer value indicating the stream priority relative to the other streams types (higher numbers have higher priority)
667
 '''hold_supported'''::
668
 True if the stream supports hold
669
 '''on_hold_by_local'''::
670
 True if the stream is on hold by the local party
671
 '''on_hold_by_remote'''::
672
 True if the stream is on hold by the remote
673
 '''on_hold'''::
674
 True if either on_hold_by_local or on_hold_by_remote is true
675
676
=== Methods ===
677
678
 '''!__init!__'''(''self'', ''account'')::
679
 Initializes the generic stream instance.
680
 '''new_from_sdp'''(''cls'', ''account'', ''remote_sdp'', ''stream_index'')::
681
 '''get_local_media'''(''self'', ''for_offer'')::
682
 '''initialize'''(''self'', ''session'', ''direction'')::
683
 Initializes the stream 
684
 '''start'''(''self'', ''local_sdp'', ''remote_sdp'', ''stream_index'')::
685
 Completes the stream related connection. [[BR]]
686
 When done, must fire StreamChatDidStart notification. 
687
 '''end'''(''self'')::
688
 Ends the stream.  When done, must fire StreamChatDidEnd notification. 
689
 '''validate_update'''(''self'', ''remote_sdp'', ''stream_index'')::
690
 '''update'''(''self'', ''local_sdp'', ''remote_sdp'', ''stream_index'')::
691
 '''deactivate'''(''self'')::
692
 '''hold'''(''self'')::
693
 Puts the stream on hold if supported by the stream. Typically used by audio and video streams.
694
 '''unhold'''(''self'')::
695
 Takes the stream off hold.
696
697
=== Notifications ===
698
699
These notifications must be generated by all streams in order for the upper layer (SIP session) to perform the right decissions.
700 1 Adrian Georgescu
701 55 Adrian Georgescu
 '''MediaStreamDidInitialize'''::
702 58 Adrian Georgescu
 Sent when the {{{Stream}}} instance is initialized
703 55 Adrian Georgescu
 '''MediaStreamDidStart'''::
704
 Sent when the {{{Stream}}} instance has started.
705
 '''MediaStreamDidFail'''::
706
 Sent when the {{{Stream}}} instance has failed.
707
 '''MediaStreamWillEnd'''::
708
 Sent before the {{{Stream}}} instance will end.
709
 '''MediaStreamDidEnd'''::
710
 Sent when the {{{Stream}}} instance did ended.
711
712
== MediaStreamRegistry ==
713
714
The MediaStream registry is used to register streams that can be automatically dealt with by the SIP session layer.
715
716
There are several pre-built streams based on the '''iMediaStream''' API:
717
718
 * {{{sipsimple.streams.msrp.MSRPStreamBase}}}  - MSRP base stream, all MSRP derived streams inherit this
719
 * {{{sipsimple.streams.msrp.ChatStream}}} - Chat stream based on MSRP 
720
 * {{{sipsimple.streams.msrp.FileSelector}}} - Helper for selecting a file for FileTransferStream
721
 * {{{sipsimple.streams.msrp.FileTransferStream}}} - File Transfer stream based on MSRP 
722
 * {{{sipsimple.streams.msrp.VNCConnectionError}}} - Helper class for DesktopSharingStream
723
 * {{{sipsimple.streams.msrp.DesktopSharingHandlerBase}}}  - Helper class for DesktopSharingStream
724
 * {{{sipsimple.streams.msrp.InternalVNCViewerHandler}}} - Helper class for DesktopSharingStream
725
 * {{{sipsimple.streams.msrp.InternalVNCViewerHandler}}}  - Helper class for DesktopSharingStream
726
 * {{{sipsimple.streams.msrp.ExternalVNCViewerHandler}}}  - Helper class for DesktopSharingStream
727
 * {{{sipsimple.streams.msrp.ExternalVNCServerHandler}}}  - Helper class for DesktopSharingStream
728
 * {{{sipsimple.streams.msrp.DesktopSharingStream}}} -  Desktop Sharing stream based on VNC over MSRP 
729
 * {{{sipsimple.streams.msrp.NotificationProxyLogger}}} - Helper class for handling MSRP library logs
730
731
These classes are used internally by [wiki:SipMiddlewareApi#Session Session], which provides the necessary methods to access their features. The notifications posted by these classes are also handled internally by [wiki:SipMiddlewareApi#Session Session]. The notifications that are relevant to the user are then reposted by the Session instance. Refer to [wiki:SipMiddlewareApi#Session Session documentation] for details on the Session API. 
732
733
== AudioStream ==
734
735
Implemented in [browser:sipsimple/streams/rtp.py]
736
737
=== SDP Example ===
738
739
{{{
740
Content-Type: application/sdp
741
Content-Length:  1093
742
743
v=0
744
o=- 3467525278 3467525278 IN IP4 192.168.1.6
745
s=blink-0.10.7-beta
746
c=IN IP4 80.101.96.20
747
t=0 0
748 57 Adrian Georgescu
m=audio 55328 RTP/AVP 104 103 102 3 9 0 8 101
749
a=rtcp:55329 IN IP4 80.101.96.20
750
a=rtpmap:104 speex/32000
751
a=rtpmap:103 speex/16000
752
a=rtpmap:102 speex/8000
753
a=rtpmap:3 GSM/8000
754
a=rtpmap:9 G722/8000
755
a=rtpmap:0 PCMU/8000
756
a=rtpmap:8 PCMA/8000
757
a=rtpmap:101 telephone-event/8000
758
a=fmtp:101 0-15
759
a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:esI6DbLY1+Aceu0JNswN9Z10DcFx5cZwqJcu91jb
760
a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:SHuEMm1BYJqOF4udKl73EaCwnsI57pO86bYKsg70
761
a=ice-ufrag:2701ed80
762
a=ice-pwd:6f8f8281
763
a=candidate:S 1 UDP 31 80.101.96.20 55328 typ srflx raddr 192.168.1.6 rport 55328
764
a=candidate:H 1 UDP 23 192.168.1.6 55328 typ host
765
a=candidate:H 1 UDP 23 10.211.55.2 55328 typ host
766
a=candidate:H 1 UDP 23 10.37.129.2 55328 typ host
767
a=candidate:S 2 UDP 30 80.101.96.20 55329 typ srflx raddr 192.168.1.6 rport 55329
768
a=candidate:H 2 UDP 22 192.168.1.6 55329 typ host
769
a=candidate:H 2 UDP 22 10.211.55.2 55329 typ host
770
a=candidate:H 2 UDP 22 10.37.129.2 55329 typ host
771
a=sendrecv
772
}}}
773
774
=== Atributes ===
775
776 63 Luci Stanescu
 '''sample_rate'''::
777
  If the audio stream was started, this attribute contains the sample rate of the audio negotiated.
778
 '''codec'''::
779
  If the audio stream was started, this attribute contains the name of the audio codec that was negotiated.
780
 '''srtp_active'''::
781
  If the audio stream was started, this boolean attribute indicates if SRTP is currently being used on the stream.
782
 '''local_rtp_address'''::
783
  If an audio stream is present within the session, this attribute contains the local IP address used for the audio stream.
784
 '''local_rtp_port'''::
785
  If an audio stream is present within the session, this attribute contains the local UDP port used for the audio stream.
786
 '''remote_rtp_address_sdp'''::
787
  If the audio stream was started, this attribute contains the IP address that the remote party gave to send audio to.
788
 '''remote_rtp_port_sdp'''::
789
  If the audio stream was started, this attribute contains the UDP port that the remote party gave to send audio to.
790
 '''remote_rtp_address_received'''::
791
  If the audio stream was started, this attribute contains the remote IP address from which the audio stream is being received.
792
 '''remote_rtp_port_received'''::
793
  If the audio stream was started, this attribute contains the remote UDP port from which the audio stream is being received.
794
 '''recording_file_name'''::
795
  If the audio stream is currently being recorded to disk, this property contains the name of the {{{.wav}}} file being recorded to.
796 58 Adrian Georgescu
797
=== Methods ===
798
799 63 Luci Stanescu
 '''start_recording'''(''self'', '''filename'''={{{None}}})::
800
  If an audio stream is present within this session, calling this method will record the audio to a {{{.wav}}} file.
801
  Note that when the session is on hold, nothing will be recorded to the file.
802
  Right before starting the recording a {{{SIPSessionWillStartRecordingAudio}}} notification will be emitted, followed by a {{{SIPSessionDidStartRecordingAudio}}}.
803
  This method may only be called while in the {{{ESTABLISHED}}} state.
804
  [[BR]]''file_name'':[[BR]]
805
  The name of the {{{.wav}}} file to record to.
806
  If this is set to {{{None}}}, a default file name including the session participants and the timestamp will be generated.
807
 '''stop_recording'''(''self'')::
808
  This will stop a previously started recording.
809
  Before stopping, a {{{SIPSessionWillStopRecordingAudio}}} notification will be sent, followed by a {{{SIPSessionDidStopRecordingAudio}}}.
810
  This method may only be called while in the {{{ESTABLISHED}}} state.
811
 '''send_dtmf'''(''self'', '''digit''')::
812
  If this session currently has an active audio stream, send a DTMF digit to the remote party over it.
813
  This method may only be called while in the {{{ESTABLISHED}}} state and if the session has an active audio stream.
814
  [[BR]]''digit'':[[BR]]
815
  This should a string of length 1, containing a valid DTMF digit value.
816 55 Adrian Georgescu
 
817
=== Notifications ===
818
819
 '''AudioStreamDidChangeHoldState'''::
820 63 Luci Stanescu
 '''AudioStreamWillStartRecordingAudio''::
821
  Will be sent when the application requested that the audio stream active within the session be record to a {{{.wav}}} file, just before recording starts.
822
  [[BR]]''timestamp'':[[BR]]
823
  A {{{datetime.datetime}}} object indicating when the notification was sent.
824
  [[BR]]''file_name'':[[BR]]
825
  The name of the recording {{{.wav}}} file, including full path.
826 55 Adrian Georgescu
 '''AudioStreamDidStartRecordingAudio'''::
827 63 Luci Stanescu
  Will be sent when the application requested that the audio stream active within the session be record to a {{{.wav}}} file, just after recording starts.
828
  [[BR]]''timestamp'':[[BR]]
829
  A {{{datetime.datetime}}} object indicating when the notification was sent.
830
  [[BR]]''file_name'':[[BR]]
831
  The name of the recording {{{.wav}}} file, including full path.
832
 '''AudioStreamWillStopRecordingAudio'''::
833
  Will be sent when the application requested ending the recording to a {{{.wav}}} file, just before recording stops.
834
  [[BR]]''timestamp'':[[BR]]
835
  A {{{datetime.datetime}}} object indicating when the notification was sent.
836
  [[BR]]''file_name'':[[BR]]
837
  The name of the recording {{{.wav}}} file, including full path.
838 57 Adrian Georgescu
 '''AudioStreamDidStopRecordingAudio'''::
839 63 Luci Stanescu
  Will be sent when the application requested ending the recording to a {{{.wav}}} file, just before recording stops.
840
  [[BR]]''timestamp'':[[BR]]
841
  A {{{datetime.datetime}}} object indicating when the notification was sent.
842
  [[BR]]''file_name'':[[BR]]
843
  The name of the recording {{{.wav}}} file, including full path.
844
 '''SIPSessionGotNoAudio'''::
845
  This notification will be sent if 5 seconds after the audio stream starts, no audio was received from the remote party.
846
  [[BR]]''timestamp'':[[BR]]
847 1 Adrian Georgescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
848 63 Luci Stanescu
 '''AudioStreamGotDTMF'''::
849 1 Adrian Georgescu
  Will be send if there is a DMTF digit received from the remote party on the audio stream. 
850 57 Adrian Georgescu
  [[BR]]''timestamp'':[[BR]]
851 1 Adrian Georgescu
  A {{{datetime.datetime}}} object indicating when the notification was sent.
852 63 Luci Stanescu
  [[BR]]''digit'':[[BR]]
853 1 Adrian Georgescu
  The DTMF digit that was received, in the form of a string of length 1.
854 63 Luci Stanescu
 
855 1 Adrian Georgescu
== MSRPStreamBase ==
856
857
Implemented in [browser:sipsimple/streams/msrp.py]
858
859
=== Atributes ===
860
861
 '''media_type'''::
862
 '''accept_types'''::
863
 '''accept_wrapped_types'''::
864
 '''use_msrp_session'''::
865
866
=== Notifications ===
867
868
 '''MSRPLibraryLog'''::
869
 '''MSRPTransportTrace'''::
870
871
== ChatStream ==
872
873
Implemented in [browser:sipsimple/streams/msrp.py]
874
875
{{{sipsimple.streams.msrp.ChatStream}}} implements Instant Messaging (IM) over MSRP for the [wiki:SipMiddlewareApi middleware]. This class performs the following functions:
876
877
 * automatically wraps outgoing messages with Message/CPIM if that's necessary according to accept-types
878
 * unwraps incoming Message/CPIM messages; for each incoming message, {{{ChatStreamGotMessage}}} is posted
879
 * plays notification sounds on received/sent message
880
 * reacts to and composes iscomposing payloads
881
882
=== SDP Example ===
883
884
{{{
885
Content-Type: application/sdp
886
Content-Length:   283
887
888
v=0
889
o=- 3467525214 3467525214 IN IP4 192.168.1.6
890
s=blink-0.10.7-beta
891
c=IN IP4 192.168.1.6
892
t=0 0
893
m=message 2855 TCP/TLS/MSRP *
894
a=path:msrps://192.168.1.6:2855/ca7940f12ddef14c3c32;tcp
895
a=accept-types:message/cpim text/* application/im-iscomposing+xml
896
a=accept-wrapped-types:*
897
}}}
898
899
=== Methods ===
900
901
 '''!__init!__'''(''self'', ''account'', ''direction'')::
902
 Initializes the ChatStream instance.
903
904
 '''initialize'''(''self'')::
905
 Initializes the MSRP connection; connects to the relay if necessary. When done, fires ChatStreamDidInitialize (with 'sdpmedia' attribute, containing the appropriate 'SDPMedia' instance)
906
907
 '''start'''(''self'', ''remote_media'')::
908
 Completes the MSRP connection establishment; this includes binding the MSRP session. [[BR]]
909
 When done, fires MSRPChatDidStart notification. At this point each incoming message is posted as a {{{ChatStreamGotMessage}}} notification
910
911
 '''end'''(''self'')::
912
 Closes the MSRP connection or cleans up after initialize(), whatever is necessary. [[BR]]
913
 Before doing anything posts {{{ChatStreamWillEnd}}} notification.
914
 When done, posts {{{ChatStreamDidEnd}}} notification. If there was an error, posts {{{ChatStreamDidFail}}} notification. 
915
 {{{ChatStreamDidEnd}}} notification will be posted anyway.
916
917
 '''send_message'''(''self'', ''content'', ''content_type''={{{'text/plain'}}}, ''to_uri''={{{None}}}, ''dt''={{{None}}})::
918
 Sends IM message. Prefer Message/CPIM wrapper if it is supported. If called before the connection was established, the messages will be
919
 queued until ChatStreamDidStart notification.
920
 Returns the generated MSRP chunk (MSRPData instance); to get Message-ID use its 'message_id' attribute.
921
 [[BR]]''content'':[[BR]]
922
 content of the message
923
924
 ''content_type'' str:[[BR]]
925
 Content-Type of wrapped message if Message/CPIM is used (Content-Type of MSRP message is always Message/CPIM in that case);
926
 otherwise, Content-Type of MSRP message.
927
928
 ''to_uri'' SIPURI:[[BR]]
929
 "To" header of CPIM wrapper; use to override the default supplied to {{{__init__}}}.
930
 May only differ from the one supplied in __init__ if the remote party supports private messages. If it does not, {{{MSRPChatError}}} will be raised;
931
932
  [[BR]]''dt'':[[BR]]
933
  A {{{datetime.datetime}}} object representing the timestamp to put on the CPIM wrapper of the message.
934
  When set to {{{None}}}, this defaults to now.
935
936
 These MSRP headers are used to enable end-to-end success reports and to disable hop-to-hop successful responses:
937
{{{
938
Failure-Report: partial
939
Success-Report: yes
940
}}}
941
942
 '''send_composing_indication'''(''self'', ''state'', ''refresh'', ''last_active=None'', ''remote_identity=None'')::
943
 Send is composing notification.
944
945
=== Notifications ===
946
947
To communicate with the middleware, MSRPChat class uses the notification system provided by the [http://pypi.python.org/pypi/python-application python-application] package.
948
949
 '''ChatStreamGotMessage'''::
950
 Sent whenever a new incoming message is received,
951
  [[BR]]''content'':[[BR]]
952
  The string that the remote user has typed.
953
  [[BR]]''content_type'':[[BR]]
954
  Content-Type of the user message.
955
  [[BR]]''cpim_headers'':[[BR]]
956
  A dictionary of CPIM headers. (Empty dictionary if no CPIM wrapper was used).
957
  [[BR]]''message'':[[BR]]
958
  A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the chunk.
959
 '''ChatStreamDidDeliverMessage'''::
960
 Sent when a successful report is received.
961
  [[BR]]''message_id'':[[BR]]
962
  Text identifier of the message.
963
  [[BR]]''code'':[[BR]]
964
  Integer result code.
965
  [[BR]]''reason'':[[BR]]
966
  Text comment.
967
  [[BR]]''message'':[[BR]]
968
  A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the report.
969
 '''ChatStreamDidNotDeliverMessage'''::
970
 Sent when a failure report of failure transaction response is received.
971
  [[BR]]''message_id'':[[BR]]
972
  Text identifier of the message.
973
  [[BR]]''code'':[[BR]]
974
  Integer result code.
975
  [[BR]]''reason'':[[BR]]
976
  Text comment.
977
  [[BR]]''message'':[[BR]]
978
  A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the report.
979
 '''ChatStreamDidSendMessage'''::
980
 Sent when an outgoing message has been sent.
981
 '''ChatStreamGotComposingIndication'''::
982
 Sent when a iscomposing payload is received.
983
984
985
== FileTransferStream ==
986
987
Implemented in [browser:sipsimple/streams/msrp.py]
988
989
=== SDP Example ===
990
991
{{{
992
Content-Type: application/sdp
993
Content-Length:   383
994
995
v=0
996
o=- 3467525166 3467525166 IN IP4 192.168.1.6
997
s=blink-0.10.7-beta
998
c=IN IP4 192.168.1.6
999
t=0 0
1000
m=message 2855 TCP/TLS/MSRP *
1001
a=path:msrps://192.168.1.6:2855/e593357dc9abe90754bd;tcp
1002
a=sendonly
1003
a=accept-types:*
1004
a=accept-wrapped-types:*
1005
a=file-selector:name:"reblink.pdf" type:com.adobe.pdf size:268759 hash:sha1:60:A1:BE:8D:71:DB:E3:8E:84:C9:2C:62:9E:F2:99:78:9D:68:79:F6
1006
}}}
1007
1008
=== Methods ===
1009
=== Notifications ===
1010
1011
 '''FileTransferStreamDidDeliverChunk'''::
1012
 '''FileTransferStreamDidFinish'''::
1013
 '''FileTransferStreamDidNotDeliverChunk'''::
1014
 '''FileTransferStreamGotChunk'''::
1015 63 Luci Stanescu
1016
== DesktopSharingStream ==
1017
1018 57 Adrian Georgescu
Implemented in [browser:sipsimple/streams/msrp.py]
1019 55 Adrian Georgescu
1020
There is no standard defining this usage but is fairly easy to implement in clients that already support MSRP. To traverse a NAT-ed router, a [http://msrprelay.org MSRP relay] configured for the called party domain is needed. Below is an example of the Session Description Protocol used for establishing a Desktop sharing session. 
1021
1022
=== SDP Example ===
1023
1024
{{{
1025
m=application 2855 TCP/TLS/MSRP *
1026
a=path:msrps://10.0.1.19:2855/b599b22d1b1d6a3324c8;tcp
1027
a=accept-types:application/x-rfb
1028
a=setup:active
1029
}}}
1030
1031
1032
=== Methods ===
1033
1034
=== Notifications ===
1035
1036
 '''DesktopSharingHandlerDidFail'''::
1037
 '''DesktopSharingStreamGotData'''::
1038
1039 64 Luci Stanescu
== Account ==
1040 55 Adrian Georgescu
1041 64 Luci Stanescu
Implemented in [browser:sipsimple/account.py]
1042 55 Adrian Georgescu
1043 64 Luci Stanescu
The {{{sipsimple.account.Account}}} objects represent the SIP accounts which are used by the middleware. It has a dual purpose: it acts as both a container for account-related settings and as a complex object which can be used to interact with various per-account functions, such as presence, registration etc. This page documents the latter case, while the former is explained in the [wiki:SipConfigurationAPI#Account Configuration API].
1044 55 Adrian Georgescu
1045 64 Luci Stanescu
There is exactly one instance of {{{Account}}} per SIP account used and it is uniquely identifiable by its SIP ID, in the form ''user@domain''. It is a singleton, in the sense that instantiating {{{Account}}} using an already used SIP ID will return the same object. However, this is not the recommended way of accessing accounts, as this can lead to creation of new ones; the recommended way is by using the [wiki:SipMiddlewareApi#AccountManager AccountManager]. The next sections will use a lowercase, monospaced {{{account}}} to represent an instance of {{{Account}}}.
1046 55 Adrian Georgescu
1047 64 Luci Stanescu
=== States ===
1048
1049
The {{{Account}}} objects have a setting flag called {{{enabled}}} which, if set to {{{False}}} will deactivate it: none of the internal functions will work in this case; in addition, the application using the middleware should not do anything with a disabled account. After changing it's value, the {{{save()}}} method needs to be called, as the flag is a setting and will not be used until this method is called:
1050
{{{
1051
account.enabled = True
1052
account.save()
1053
}}}
1054
1055
The {{{Account}}} objects will activate automatically when they are loaded/created if the {{{enabled}}} flag is set to {{{True}}} and the {{{sipsimple.engine.Engine}}} is running; if it is not running, the accounts will activate after the engine starts.
1056
1057
In order to create a new account, just create a new instance of {{{Account}}} with an id which doesn't belong to any other account.
1058
1059
The other functions of {{{Account}}} which run automatically have other enabled flags as well. They will only be activated when both the global enabled flag is set and the function-specific one. These are:
1060
1061
 '''Account.registration.enabled'''::
1062
  This flag controls the automatic registration of the account. The notifications '''SIPAccountRegistrationDidSucceed''', '''SIPAccountRegistrationDidFail''' and '''SIPAccountRegistrationDidEnd''' are used to inform the status of this registration.
1063
 '''Account.presence.enabled'''::
1064
  This flag controls the automatic subscription to buddies for the ''presence'' event and the publication of data in this event. (Not implemented yet)
1065
 '''Account.dialog_event.enabled'''::
1066
  This flag controls the automatic subscription to buddies for the ''dialog-info'' event and the publication of data in this event. (Not implemented yet)
1067
 '''Account.message_summary.enabled'''::
1068
  This flag controls the automatic subscription to the ''message-summary'' event in order to find out about voicemail messages. (Not implemented yet)
1069
1070
The {{{save()}}} method needs to be called after changing these flags in order for them to take effect. The methods available on {{{Account}}} objects are inherited from [wiki:SipConfigurationAPI#SettingsObject SettingsObject].
1071
1072
=== Attributes ===
1073
1074
The following attributes can be used on an Account object and need to be considered read-only.
1075
1076
 '''id'''::
1077
  This attribute is of type {{{sipsimple.configuration.datatypes.SIPAddress}}} (a subclass of {{{str}}}) and contains the SIP id of the account. It can be used as a normal string in the form ''user@domain'', but it also allows access to the components via the attributes {{{username}}} and {{{domain}}}.
1078
  {{{
1079
  account.id # 'alice@example.com'
1080
  account.id.username # 'alice'
1081
  account.id.domain # 'example.com'
1082
  }}}
1083
 '''contact'''::
1084
  This attribute can be used to construct the Contact URI for SIP requests sent on behalf of this account. It's type is {{{sipsimple.account.ContactURI}}} which is a subclass of {{{sipsimple.configuration.datatypes.SIPAddress}}}. In addition to the attributes defined in {{{SIPAddress}}}, it can be indexed by a string representing a transport ({{{'udp'}}}, {{{'tcp'}}} or {{{'tls'}}}) which will return a {{{sipsimple.core.SIPURI}}} object with the appropriate port and transport parameter. The username part is a randomly generated 8 character string consisting of lowercase letters; the domain part is the IP address on which the {{{Engine}}} is listening (as specified by the SIPSimpleSettings.local_ip setting).
1085
  {{{
1086
  account.contact # 'hnfkybrt@10.0.0.1'
1087
  account.contact.username # 'hnfkybrt'
1088
  account.contact.domain # '10.0.0.1'
1089
  account.contact['udp'] # <SIPURI "sip:hnfkybrt@10.0.0.1:53024">
1090
  account.contact['tls'] # <SIPURI "sip:hnfkybrt@10.0.0.1:54478;transport=tls">
1091
  }}}
1092
 '''credentials'''::
1093
  This attribute is of type {{{sipsimple.core.Credentials}}} object which is built from the {{{id}}} attribute and {{{display_name}}} and {{{password}}} settings of the Account. Whenever one of these settings are changed, this attribute is updated.
1094
  {{{
1095
  account.credentials # <Credentials for '"Alice" <sip:alice@example.com>'>
1096
  }}}
1097
1098
=== Notifications ===
1099
1100
 '''CFGSettingsObjectDidChange'''::
1101
  This notification is sent when the {{{save()}}} method is called on the account after some of the settings were changed. As the notification belongs to the {{{SettingsObject}}} class, it is exaplained in detail in [wiki:SipConfigurationAPI#SettingsObjectNotifications SettingsObject Notifications].
1102
 '''SIPAccountDidActivate'''::
1103
  This notification is sent when the {{{Account}}} activates. This can happen when the {{{Account}}} is loaded if it's enabled flag is set and the Engine is running, and at any later time when the status of the Engine changes or the enabled flag is modified. The notification does not contain any data.
1104
 '''SIPAccountDidDeactivate'''::
1105
  This notification is sent when the {{{Account}}} deactivates. This can happend when the {{{Engine}}} is stopped or when the enabled flag of the account is set to {{{False}}}. The notification does not contain any data.
1106
 '''SIPAccountRegistrationDidSucceed'''::
1107
  This notification is sent when a REGISTER request sent for the account succeeds (it is also sent for each refresh of the registration). The data contained in this notification is:
1108
  [[BR]]''code'':[[BR]]
1109
   The status code of the response for the REGISTER request.
1110
  [[BR]]''reason'':[[BR]]
1111
   The reason of the response for the REGISTER request.
1112
  [[BR]]''contact_uri'':[[BR]]
1113
   The Contact URI which was registered.
1114
  [[BR]]''contact_uri_list'':[[BR]]
1115
   A list containing all the contact URIs registered for this SIP account.
1116
  [[BR]]''expires'':[[BR]]
1117
   The amount in seconds in which this registration will expire.
1118
  [[BR]]''registration'':[[BR]]
1119
   The {{{sipsimple.core.Registration}}} object used to register this account.
1120
 '''SIPAccountRegistrationDidFail'''::
1121
  This notification is sent when a REGISTER request sent for the account fails. It can fail either because a negative response was returned or because PJSIP considered the request failed (e.g. on timeout). The data contained in this notification is:
1122
  [[BR]]''code'':[[BR]]
1123
   The status code of the response for the REGISTER request. This is only present if the notification is sent as a result of a response being received.
1124
  [[BR]]''reason'':[[BR]]
1125
   The reason for the failure of the REGISTER request.
1126
  [[BR]]''registration'':[[BR]]
1127
   The {{{sipsimple.core.Registration}}} object which failed.
1128
  [[BR]]''next_route'':[[BR]]
1129
   A {{{sipsimple.core.Route}}} object which will be tried next for registering the account, or {{{None}}} if a new DNS lookup needs to be performed.
1130
  [[BR]]''delay'':[[BR]]
1131
   The amount in seconds as a {{{float}}} after which the next route will be tried for registering the account.
1132
 '''SIPAccountRegistrationDidEnd'''::
1133
  This notification is sent when a registration is ended (the account is unregistered). The data contained in this notification is:
1134
  [[BR]]''code'':[[BR]]
1135
   The status code of the response for the REGISTER with {{{Expires: 0}}} request. This is only present if a response was received.
1136
  [[BR]]''reason'':[[BR]]
1137
   The reason returned in the response for the Register with {{{Expires: 0}}} request. This is only present if a response was received
1138
  [[BR]]''registration'':[[BR]]
1139
   The {{{sipsimple.core.Registration}}} object which ended.
1140
1141
== BonjourAccount ==
1142
1143
Implemented in [browser:sipsimple/account.py]
1144
1145
The {{{sipsimple.account.BonjourAccount}}} represents the SIP account used for P2P mode; it does not interact with any server. The class is a singleton, as there can only be one such account on a system. Similar to the {{{Account}}}, it is used both as a complex object, which implements the functions for bonjour mode, as well as a container for the related settings.
1146
1147
=== States ===
1148
1149
The {{{BonjourAccount}}} has an {{{enabled}}} flags which controls whether this account will be used or not. If it is set to {{{False}}}, none of the internal functions will be activated and, in addition, the account should not be used by the application. The bonjour account can only activated if the Engine is running; once it is started, if the enabled flag is set, the account will activate. When the {{{BonjourAccount}}} is activated, it will broadcast the contact address on the LAN. (Not implemented yet)
1150
1151
=== Attributes ===
1152
1153
The following attributes can be used on an BonjourAccount object and need to be considered read-only.
1154
1155
 '''id'''::
1156
  This attribute is of type {{{sipsimple.configuration.datatypes.SIPAddress}}} (a subclass of {{{str}}}) and contains the SIP id of the account, which is {{{'bonjour@local'}}}. It can be used as a normal string, but it also allows access to the components via the attributes {{{username}}} and {{{domain}}}.
1157
  {{{
1158
  bonjour_account.id # 'bonjour@local'
1159
  bonjour_account.id.username # 'bonjour'
1160
  bonjour_account.id.domain # 'local'
1161
  }}}
1162
 '''contact'''::
1163
  This attribute can be used to construct the Contact URI for SIP requests sent on behalf of this account. It's type is {{{sipsimple.account.ContactURI}}} which is a subclass of {{{sipsimple.configuration.datatypes.SIPAddress}}}. In addition to the attributes defined in {{{SIPAddress}}}, it can be indexed by a string representing a transport ({{{'udp'}}}, {{{'tcp'}}} or {{{'tls'}}}) which will return a {{{sipsimple.core.SIPURI}}} object with the appropriate port and transport parameter. The username part is a randomly generated 8 character string consisting of lowercase letters; the domain part is the IP address on which the {{{Engine}}} is listening (as specified by the SIPSimpleSettings.local_ip setting).
1164
  {{{
1165
  account.contact # 'lxzvgack@10.0.0.1'
1166
  account.contact.username # 'lxzvgack'
1167
  account.contact.domain # '10.0.0.1'
1168
  account.contact['udp'] # <SIPURI "sip:lxzvgack@10.0.0.1:53024">
1169
  account.contact['tls'] # <SIPURI "sip:lxzvgack@10.0.0.1:54478;transport=tls">
1170
  }}}
1171
 '''credentials'''::
1172
  This attribute is of type {{{sipsimple.core.Credentials}}} object which is built from the {{{contact}}} attribute and {{{display_name}}} setting of the BonjourAccount; the password is set to the empty string. Whenever the display_name setting is changed, this attribute is updated.
1173
  {{{
1174
  account.credentials # <Credentials for '"Alice" <sip:lxzvgack@10.0.0.1>'>
1175
  }}}
1176
1177
=== Notifications ===
1178
1179
 '''CFGSettingsObjectDidChange'''::
1180
  This notification is sent when the {{{save()}}} method is called on the account after some of the settings were changed. As the notification belongs to the {{{SettingsObject}}} class, it is exaplained in detail in [wiki:SipConfigurationAPI#SettingsObjectNotifications SettingsObject Notifications].
1181
 '''SIPAccountDidActivate'''::
1182
  This notification is sent when the {{{BonjourAccount}}} activates. This can happen when the {{{BonjourAccount}}} is loaded if it's enabled flag is set and the Engine is running, and at any later time when the status of the Engine changes or the enabled flag is modified. The notification does not contain any data.
1183
 '''SIPAccountDidDeactivate'''::
1184
  This notification is sent when the {{{BonjourAccount}}} deactivates. This can happend when the {{{Engine}}} is stopped or when the enabled flag of the account is set to {{{False}}}. The notification does not contain any data.
1185
1186
1187
== AccountManager ==
1188
1189
Implemented in [browser:sipsimple/account.py]
1190
1191
The {{{sipsimple.account.AccountManager}}} is the entity responsible for loading and keeping track of the existing accounts. It is a singleton and can be instantiated anywhere, obtaining the same instance. It cannot be used until its {{{start}}} method has been called.
1192
1193
=== Methods ===
1194
1195
 '''!__init!__'''(''self'')::
1196
  The {{{__init__}}} method allows the {{{AccountManager}}} to be instantiated without passing any parameters. A reference to the {{{AccountManager}}} can be obtained anywhere before it is started.
1197
 '''start'''(''self'')::
1198
  This method will load all the existing accounts from the configuration. If the Engine is running, the accounts will also activate. This method can only be called after the [wiki:SipConfigurationAPI#ConfigurationManager ConfigurationManager] has been started. A '''SIPAccountManagerDidAddAccount''' will be sent for each account loaded.
1199
 '''stop'''(''self'')::
1200
  Calling this method will deactivate all accounts managed by the {{{AccountManager}}}.
1201
 '''has_account'''(''self'', '''id''')::
1202
  This method returns {{{True}}} if an account which has the specifed SIP ID (must be a string) exists and {{{False}}} otherwise.
1203
 '''get_account'''(''self'', '''id''')::
1204
  Returns the account (either an {{{Account}}} instance or the {{{BonjourAccount}}} instance) with the specified SIP ID. Will raise a {{{KeyError}}} if such an account does not exist.
1205
 '''get_accounts'''(''self'')::
1206
  Returns a list containing all the managed accounts.
1207
 '''iter_accounts'''(''self'')::
1208
  Returns an iterator through all the managed accounts.
1209
 '''find_account'''(''self'', '''contact_uri''')::
1210
  Returns an account with matches the specified {{{contact_uri}}} which must be a {{{sipsimple.core.SIPURI}}} instance. Only the accounts with the enabled flag set will be considered. Returns None if such an account does not exist.
1211
1212
=== Notifications ===
1213
1214
 '''SIPAccountManagerDidAddAccount'''::
1215
  This notification is sent when a new account becomes available to the {{{AccountManager}}}. The notification is also sent when the accounts are loaded from the configuration. The data contains a single attribute, {{{account}}} which is the account object which was added.
1216
 '''SIPAccountManagerDidRemoveAccount'''::
1217
  This notification is sent when an account is deleted using the {{{delete}}} method. The data contains a single attribute, {{{account}}} which is the account object which was deleted.
1218
 '''SIPAccountManagerDidChangeDefaultAccount'''::
1219
  This notification is sent when the default account changes. The notification contains two attributes:
1220
  [[BR]]''old_account'':[[BR]]
1221
   This is the account object which used to be the default account.
1222
  [[BR]]''account'':[[BR]]
1223
   This is the account object which is the new default account.