« Previous - Version 23/65 (diff) - Next » - Current version
Adrian Georgescu, 03/31/2009 05:13 pm


= MSRP API =

<acronym title="WikiStart, Sip*, depth=3">TOC</acronym>

Message Session Relay Protocol (MSRP) is a protocol for transmitting a series of related instant messages in the context of a session. Message sessions are treated like any other media stream when set up via a rendezvous or session creation protocol such as the Session Initiation Protocol (SIP).

The MSRP protocol is implemented by [http://devel.ag-projects.com/cgi-bin/darcsweb.cgi?r=python-msrplib;a=summary msrplib] Python package. On top of it, {{{sipsimple}}} provides higher level classes integrated into middleware notification and configuration systems:

  • {{{sipsimple.msrp.MSRPChat}}}
  • {{{sipsimple.msrp.MSRPFileTransfer}}}
  • {{{sipsimple.msrp.MSRPDesktopSharing}}}

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.

MSRPChat API

{{{sipsimple.msrp.MSRPChat}}} implements instant messaging (IM) over MSRP for the [wiki:SipMiddlewareApi middleware]. This class performs the following functions:

  • automatically wraps outgoing messages with Message/CPIM if that's necessary according to accept-types
  • unwraps incoming Message/CPIM messages; for each incoming message, {{{MSRPChatGotMessage}}} is posted
  • plays notification sounds on received/sent message

=== Methods === {{{
Failure-Report: partial
Success-Report: yes
}}}

'''!__init!__'''(''self'', ''account'', ''remote_uri'', ''outgoing'')::
Initialize MSRPChat instance.
'''initialize'''(''self'')::
Initialize the MSRP connection; connect to the relay if necessary. When done, fire MSRPChatDidInitialize (with 'sdpmedia' attribute, containing the appropriate 'SDPMedia' instance)
'''start'''(''self'', ''remote_media'')::
Complete the MSRP connection establishment; this includes binding the MSRP session. [[BR]]
When done, fire MSRPChatDidStart. At this point each incoming message is posted as a {{{MSRPChatGotMessage}}} notification
'''end'''(''self'')::
Close the MSRP connection or cleanup after initialize(), whatever is necessary. [[BR]]
Before doing anything post {{{MSRPChatWillEnd}}}.
When done, post {{{MSRPChatDidEnd}}}. If there was an error, post {{{MSRPChatDidFail}}}. {{{MSRPChatDidEnd}}} will be posted anyway.
'''send_message'''(''self'', ''content'', ''content_type''={{{'text/plain'}}}, ''to_uri''={{{None}}}, ''dt''={{{None}}})::
Send IM message. Prefer Message/CPIM wrapper if it is supported. If called before the connection was established, the messages will be
queued until MSRPChatDidStart notification.
Return generated MSRP chunk (MSRPData instance); to get Message-ID use its 'message_id' attribute.
''content'' str:[[BR]]
content of the message
''to_uri'' SIPURI:[[BR]]
"To" header of CPIM wrapper; use to override the default supplied to {{{__init__}}}.
May only differ from the one supplied in init if the remote party supports private messages. If it does not, {{{MSRPChatError}}} will be raised;
''content_type'' str:[[BR]]
Content-Type of wrapped message if Message/CPIM is used (Content-Type of MSRP message is always Message/CPIM in that case);
otherwise, Content-Type of MSRP message.
These MSRP headers are used to enable end-to-end success reports and to disable hop-to-hop successful responses:

=== Notifications ===

To communicate with the middleware, MSRPChat class uses the notification system provided by the [http://pypi.python.org/pypi/python-application python-application] package.

'''MSRPChatDidInitialize'''::
Sent when the {{{MSRPChat}}} instance is initialized, it includes the MSRP relay reservation when requested.
'''MSRPChatDidStart'''::
Sent when the {{{MSRPChat}}} instance is started.
'''MSRPChatWillEnd'''::
Sent when the {{{MSRPChat}}} is entering cleanup procedure initiated by calling end().
'''MSRPChatDidEnd'''::
Sent when the {{{MSRPChat}}} has finished the cleanup procedure initiated by end().
'''MSRPChatDidFail'''::
Sent whenever the {{{MSRPChat}}} instance fails.
[[BR]]''context'':[[BR]]
A text string identifying the context of the failure ('initialize', 'sdp_negotiation', 'start', 'reading').
[[BR]]''reason'':[[BR]]
A text string describing the reason of failure.
[[BR]]''failure'':[[BR]]
A Failure instance providing detailed traceback information.
'''MSRPChatGotMessage'''::
Sent whenever a new incoming message is received,
[[BR]]''content'':[[BR]]
The string that the remote user has typed.
[[BR]]''content_type'':[[BR]]
Content-Type of the user message.
[[BR]]''cpim_headers'':[[BR]]
A dictionary of CPIM headers. (Empty dictionary if no CPIM wrapper was used).
[[BR]]''message'':[[BR]]
A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the chunk.
'''MSRPChatDidDeliverMessage'''::
Sent when a successful report is received.
[[BR]]''message_id'':[[BR]]
Text identifier of the message.
[[BR]]''code'':[[BR]]
Integer result code.
[[BR]]''reason'':[[BR]]
Text comment.
[[BR]]''message'':[[BR]]
A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the report.
'''MSRPChatDidNotDeliverMessage'''::
Sent when a failure report of failure transaction response is received.
[[BR]]''message_id'':[[BR]]
Text identifier of the message.
[[BR]]''code'':[[BR]]
Integer result code.
[[BR]]''reason'':[[BR]]
Text comment.
[[BR]]''message'':[[BR]]
A {{{msrplib.protocol.MSRPData}}} instance providing all the MSRP information about the report.
MSRPFileTransfer

=== Methods === === Notifications ===

MSRPDesktopSharing

=== Methods === === Notifications ===


msrplib low level API

{{{msrplib}}} is based upon [http://twistedmatrix.com twisted] and [http://devel.ag-projects.com/~denis/eventlet/ eventlet] and provides a set of
classes for establishing and managing MSRP connection.

The library consist of the following modules:

'''msrplib.transport'''::
Defines {{{MSRPTransport}}} class, which provides low level control over MSRP connection.
'''msrplib.connect'''::
Defines means to establish a connection, bind it, and provide an initialized {{{MSRPTransport}}} instance.
'''msrplib.session'''::
Defines {{{MSRPSession}}} class, which provides high level control over a MSRP connection.
'''msrplib.protocol'''::
Provides representation and parsing of MSRP entities - chunks and URIs.
'''msrplib.trafficlog'''::
Defines {{{Logger}}} class that is used through out the library to log the connection state.

=== Usage ===

==== Establish a connection ====

{{{msrplib.connect}}} provides a number of classes to establish a connection, so the first
thing to do is to select which one applies to your situation:

1. Calling endpoint, not using a relay ({{{ConnectorDirect}}})
2. Answering endpoint, not using a relay ({{{AcceptorDirect}}})
3. Calling endpoint, using a relay ({{{ConnectorRelay}}})
4. Answering endpoint, using a relay ({{{AcceptorRelay}}})

The answering endpoint may skip using the relay if sure that it's accessible
directly. The calling endpoint is unlikely to need the relay.

Once you have an instance of the right class (use the convenience functions {{{get_connector()}}} and {{{get_acceptor()}}} to get one), the procedure to establish the
connection is the same:

{{{
full_local_path = connector.prepare()
try:
... put full_local_path in SDP 'a:path' attribute
... get full_remote_path from remote's 'a:path: attribute
... (the order of the above steps is reversed if you're the
... answering party, but that does not affect connector's usage)
msrptransport = connector.complete(full_remote_path)
finally:
connector.cleanup()
}}}

To customize connection's parameters, create a new {{{protocol.URI}}} object and pass
it to prepare() function, e.g. {{{
local_uri = protocol.URI
connector.prepare(local_uri)
}}}

{{{prepare()}}} may update {{{local_uri}}} in place with the actual connection parameters
used (e.g. if you specified port=0). 'port' attribute of {{{local_uri}}} is currently
only respected by {{{AcceptorDirect}}}.

Note that, acceptors and connectors are one-use only. Which means, that {{{AcceptorDirect}}}
will open a port just to handle one incoming connection and close it right after.
If your application behaves more like a server, i.e. opens a port and listens on it
constantly, use {{{MSRPServer}}} class.

=== Components ===

==== a connector or acceptor ====

{{{msrplib.connect}}} provides 2 connectors (with and without relay) and 2 acceptors (likewise, with or without relay). All of them have the exact same interface,
'''prepare'''(''self'', ''local_uri''={{{None}}})::
Depending on type of the connector, use local_uri to prepare the MSRP connection, which means:
  • connecting and authenticating at the relay if a relay is used ({{{ConnectorRelay}}} and {{{AcceptorRelay}}})
  • start listening on a local port for DirectAcceptor
''local_uri'' is used to specify the connection parameters, e.g. local port and local ip.
If not provided, suitable ''local_uri'' will be generated.
''local_uri'' maybe updated in place by {{{prepare()}}} method if the real settings used are different from those specified.
{{{prepare}}} returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
'''complete'''(''self'', ''full_remote_path'')::
Complete establishing the MSRP connection, which means
  • establishing the connection if it wasn't already established ({{{ConnectorDirect}}})
  • bind the connection, i.e. exchange empty chunk to verify each other's From-Path and To-Path
''full_remote_path'' should be a list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
{{{complete}}} returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
'''cleanup'''(''self'')::
Call this method to cleanup after {{{initialize()}}} if it's impossible to call {{{complete()}}}

==== transport.MSRPTransport ====

Low level access to MSRP connection.

'''make_chunk'''(''self'', ''transaction_id''={{{None}}}, ''method''={{{'SEND'}}}, ''code''={{{None}}}, ''comment''={{{None}}}, ''data''={{{''}}}, ''contflag''={{{None}}}, ''start''={{{1}}}, ''end''={{{None}}}, ''length''={{{None}}}, ''message_id''={{{None}}})::
Make a new chunk ({{{protocol.MSRPData}}} instance) with proper {{{From-Path}}}, {{{To-Path}}}, {{{Byte-Range}}} and {{{Message-ID}}} headers set up based on MSRPTransport's state and the parameters provided. Use ''data'' for payload, and ''start''/''end''/''length'' to generate {{{Byte-Range}}} header. Generate new random strings for default values of ''transaction_id'' and ''message_id''.
[[BR]]''contflag'':[[BR]]
MSRP chunk's continuation flag ({{{'$'}}}, {{{'+'}}} or {{{'#'}}}). Default is {{{'$'}}}, unless you have a partial {{{SEND}}} chunk, in which case it is {{{'+'}}}
'''write'''(''self'', ''bytes'', ''sync''={{{True}}})::
Write ''bytes'' to the socket. If ''sync'' is true, wait for an operation to complete.
'''read_chunk'''(''self'', ''size''={{{None}}})::
Wait for a new chunk and return it.
If there was an error, close the connection and raise {{{ChunkParseError}}}.
In case of unintelligible input, lose the connection and return {{{None}}}.
When the connection is closed, raise the reason of the closure (e.g. {{{ConnectionDone}}}).
If the data already read exceeds ''size'', stop reading the data and return
a "virtual" chunk, i.e. the one that does not actually correspond the the real
MSRP chunk. Such chunks have Byte-Range header changed to match the number of
bytes read and continuation that is {{{'+'}}}; they also possess {{{segment}}} attribute,
an integer, starting with 1 and increasing with every new segment of the chunk.
Note, that ''size'' only hints when to interrupt the segment but does not affect
how the data is read from socket. You may have segments bigger than ''size'' and it's
legal to set ''size'' to zero (which would mean return a chunk as long as you get
some data, regardless how small).
'''check_incoming_SEND_chunk'''(''self'', ''chunk'')::
Check the 'To-Path' and 'From-Path' of the incoming SEND chunk.
Return None is the paths are valid for this connection.
If an error is detected an MSRPError is created and returned.

==== session.MSRPSession ====

'''!__init!__'''(''self'', ''msrptransport'', ''accept_types''={{{['*']}}}, ''on_incoming_cb''={{{None}}})::
Initialize MSRPSession instance. Report the incoming chunks through ''on_incoming_cb'' callback.
'''send_chunk'''(''self'', ''chunk'', ''response_cb''={{{None}}})::
Send ''chunk''. Report the result via ''response_cb''.
When ''response_cb'' argument is present, it will be used to report
the transaction response to the caller. When a response is received or generated
locally, ''response_cb'' is called with one argument. The function must do something
quickly and must not block, because otherwise it would the reader greenlet.
If no response was received after {{{RESPONSE_TIMEOUT}}} seconds,
  • 408 response is generated if Failure-Report was {{{'yes'}}} or absent
  • 200 response is generated if Failure-Report was {{{'partial'}}} or {{{'no'}}}
Note that it's rather wasteful to provide ''response_cb'' argument other than {{{None}}}
for chunks with Failure-Report='no' since it will always fire 30 seconds later
with 200 result (unless the other party is broken and ignores Failure-Report header)
If sending is impossible raise {{{MSRPSessionError}}}.
'''deliver_chunk'''(''self'', ''chunk'', ''event''={{{None}}})::
Send chunk, wait for the transaction response (if Failure-Report header is not {{{'no'}}}).
Return the transaction response if it's a success, raise {{{MSRPTransactionError}}} if it's not.
If chunk's Failure-Report is {{{'no'}}}, return {{{None}}} immediately.
'''shutdown'''(''self'', ''sync''={{{True}}})::
Send the messages already in queue then close the connection.

==== session.GreenMSRPSession ====

A subclass of MSRPSession that delivers the incoming messages to the queue.
'''!__init!__'''(''self'', ''msrptransport'', ''accept_types''={{{['*']}}})::
Initialize GreenMSRPSession instance. The messages will be delivered to the queue (available as {{{incoming}}} attribute).
'''receive_chunk'''(''self'')::
Return a message from the queue.

==== connect.MSRPServer ====
Manage listening sockets. Bind incoming requests.

MSRPServer solves the problem with AcceptorDirect: concurrent using of 2
or more AcceptorDirect instances on the same non-zero port is not possible.
If you initialize() those instances, one after another, one will listen on
the socket and another will get BindError.
MSRPServer avoids the problem by sharing the listening socket between multiple connections.
It has a slightly different interface from AcceptorDirect, so it cannot be considered a drop-in
replacement.
'''prepare'''(''self'', ''local_uri''={{{None}}}, ''logger''={{{None}}})::
Start a listening port specified by ''local_uri'' if there isn't one on that port/interface already.
Add ''local_uri'' to the list of expected URIs, so that incoming connections featuring this URI won't be rejected.
If ''logger'' is provided use it for this connection instead of the default one.
'''complete'''(''self'', ''full_remote_path'')::
Wait until one of the incoming connections binds using provided ''full_remote_path''.
Return connected and bound {{{MSRPTransport}}} instance.
If no such binding was made within {{{MSRPBindSessionTimeout.seconds}}}, raise {{{MSRPBindSessionTimeout}}}.
''full_remote_path'' should be a list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
'''cleanup'''(''self'', ''local_uri'')::
Remove ''local_uri'' from the list of expected URIs.