Commits

Jay Yu committed 3e50983

Comments (0)

Files changed (14)

+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
+Metadata-Version: 1.0
+Name: msnp.py
+Version: 0.4.1
+Summary: An implementation of the MSN Messenger Protocol
+Home-page: http://msnp.sf.net/
+Author: Manish Jethani
+Author-email: manish_jethani AT yahoo.com
+License: GNU General Public License (Version 2)
+Description: UNKNOWN
+Platform: UNKNOWN
+README for msnp.py 0.4.1
+
+INSTALLATION
+
+  Python 2.3+
+
+    msnp.py requires Python 2.3, or higher.  If that it not available on your
+    system, please consider downloading it:
+
+      http://www.python.org/2.3/
+
+  msnp.py
+
+    Untar/unzip the archive into a temporary directory.  Then go to the
+    directory containing the file setup.py, and run the following commands:
+
+      python setup.py build
+      python setup.py install
+
+DOCUMENTATION/RESOURCES
+
+  See tutorial.html for a quick intro.
+
+  Visit the project home page:
+
+    http://msnp.sf.net/
+
+  Join the mailing list:
+
+    http://lists.sourceforge.net/lists/listinfo/msnp-devel
+
+  Report bugs:
+
+    https://sourceforge.net/tracker/?group_id=81726&atid=563849
+
+CHANGES
+
+  Implemented new friend list management of MSNP 8.
+
+vim: set tw=79 ts=2 sw=2 ai et :
+
+# msnp.py -- An implementation of the MSN Messenger Protocol
+#
+# Version 0.4 (for Python 2.3)
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+"""An implementation of the MSN Messenger Protocol
+
+msnp is a library, written in object-oriented Python, for accessing the MSN
+instant messaging service.
+
+To use this module for instant messaging, an instance of the msnp.Session class
+must be created.  The msnp.SessionCallbacks interface must be implemented by
+the client.  For example:
+
+    import msnp
+
+    class MyCallbacks(msnp.SessionCallbacks):
+        def state_changed(self, state):
+            print 'New state:', state
+
+    im = msnp.Session(MyCallbacks())
+    im.login('gill_bates@hotmail.com', 'microshaft')
+
+If the login succeeds, the state_changed method of the MyCallbacks instance
+will be called, and 'New state: NLN' will get printed.
+
+For more information, visit:
+http://msnp.sourceforge.net/
+"""
+
+# Note about documentation:  All public objects (classes, methods, globals,
+# etc.) have been documented with Python docstrings; private code has been
+# sprinkled with terse comments.
+
+from error import Error
+from friend import Group, Friend, FriendList
+
+from chat import Chat, ChatCallbacks
+from session import Session, SessionCallbacks
+
+from protocol import States, Lists, PrivacyModes
+
+import protocol
+
+__all__ = [
+    'Error',
+    'Group', 'Friend', 'FriendList',
+    'Chat', 'ChatCallbacks',
+    'Session', 'SessionCallbacks',
+    'States', 'Lists', 'PrivacyModes',
+]
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# chat.py -- Chat, ChatCallbacks classes
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+import select
+
+import email
+import email.Message
+import email.Charset
+
+from string import split, join
+
+from session import _Session
+from command import Command, Msg
+from codec import url_codec
+
+import protocol
+
+class ChatCallbacks:
+    """Callback interface for MSN chat
+
+    The client must implement some or all of these methods to receive
+    notifications on chat events.  The value of Chat.callbacks must be set
+    after receiving the Chat instance in SessionCallbacks.chat_started
+    """
+
+    def friend_joined(self, passport_id, display_name):
+        """Friend has joined the chat
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+        """
+
+    def friend_left(self, passport_id):
+        """Friend has left the chat
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+        """
+
+    def message_received(self, passport_id, display_name, text, charset):
+        """Message received
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+            text -- message text
+            charset -- character set of text (usu. utf-8)
+        """
+
+    def typing_received(self, passport_id, display_name):
+        """Friend is typing
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+        """
+
+class Chat(_Session):
+    """MSN chat conversation
+
+    When a conversation is started, an instance of Chat is created and passed
+    on to the SessionCallbacks.chat_started method.
+    """
+    def __init__(self, session, server, hash, passport_id, display_name,
+        session_id = None, invitee = None):
+
+        _Session.__init__(self, ChatCallbacks())
+
+        self.session = session
+        self.hash = hash
+        self.passport_id = passport_id
+        self.display_name = display_name
+        self.session_id = session_id
+        self.transaction_id = 1
+        self.initial_members = []
+
+        self.http_proxy = session.http_proxy
+        conn = self.conn = self._connect(server)
+
+        if passport_id != session.passport_id:  # invited to chat
+            ans = Command('ANS', self.transaction_id,
+                (session.passport_id, hash, session_id))
+            self._send_cmd(ans, conn)
+
+            while 1:
+                resp = self._receive_cmd(conn)
+                if resp.cmd == 'ANS':
+                    break
+                elif resp.cmd != 'IRO':
+                    raise Error(int(resp.cmd), protocol.errors[resp.cmd])
+                self.initial_members.append((resp.args[2],
+                    url_codec.decode(resp.args[3])))
+
+        else:  # hosting chat
+            usr = Command('USR', self.transaction_id,
+                (passport_id, hash))
+            resp = self._sync_command(usr, conn)
+            if resp.cmd != 'USR':
+                raise Error(int(resp.cmd), protocol.errors[resp.cmd])
+
+            cal = Command('CAL', self.transaction_id, (invitee,))
+            resp = self._sync_command(cal, conn)
+            if resp.cmd != 'CAL':
+                raise Error(int(resp.cmd), protocol.errors[resp.cmd])
+            self.session_id = resp.args[1]
+
+    def leave(self):
+        """Leave a chat conversation
+
+        This should be the last method called on a Chat instance.
+        """
+        del self.session.active_chats[self.session_id]
+        self.process()
+        self.conn.break_()
+        self.conn = None
+
+    def __send_mime_message(self, mime_message, flag):
+        msg = Msg()
+        msg.trn = self.transaction_id
+
+        msg.msg_buf = ''
+        for hdr in mime_message.items():
+            msg.msg_buf = msg.msg_buf + join(hdr, ': ') + '\r\n'
+        msg.msg_buf = msg.msg_buf + '\r\n'
+        if mime_message.get_payload() != None:
+            msg.msg_buf = msg.msg_buf + mime_message.get_payload()
+
+        msg.args = (flag, str(len(msg.msg_buf)))
+
+        self._async_command(msg)
+        self.process()
+
+    def send_message(self, text, charset = 'utf-8'):
+        """Send message
+
+        Keyword arguments:
+            text -- message text
+            charset -- character set of text (default utf-8)
+        """
+        mime_message = email.Message.Message()
+        mime_message['MIME-Version'] = '1.0'
+        mime_message['Content-Type'] = 'text/plain; charset=' + charset
+        mime_message.set_payload(text)
+        self.__send_mime_message(mime_message, 'N')
+
+    def send_typing(self):
+        """Send typing notification"""
+        mime_message = email.Message.Message()
+        mime_message['MIME-Version'] = '1.0'
+        mime_message['Content-Type'] = 'text/x-msmsgscontrol'
+        mime_message['TypingUser'] = self.session.passport_id
+        self.__send_mime_message(mime_message, 'U')
+
+    def process(self):
+        """Process events
+
+        This method must be called periodically, preferably in the client
+        application's main loop.
+        """
+        while 1:
+            if self.conn == None:
+                break
+            fd = self.conn.socket.fileno()
+            r = select.select([fd], [], [], 0)
+            if len(r[0]) > 0:
+                buf = self.conn.receive_data_line()
+                if buf == None:  # connection closed?!
+                    break
+                self.__process_command_buf(buf)
+            elif len(self.send_queue) > 0:
+                cmd = self.send_queue.pop(0)
+                cmd.send(self.conn)
+            else:
+                break
+
+    def __process_command_buf(self, buf):
+        cmd = buf[:3]
+        if cmd == 'MSG':
+            self.__process_msg(buf)
+        elif cmd == 'JOI':
+            self.__process_joi(buf)
+        elif cmd == 'BYE':
+            self.__process_bye(buf)
+        # TODO error handling
+
+    def __process_msg(self, buf):
+        msg = Msg()
+        msg.parse(buf)
+        msg.receive(self.conn)
+        mime_message = email.message_from_string(msg.msg_buf)
+
+        if mime_message.get_content_type() == 'text/plain':
+            self.callbacks.message_received(msg.passport_id,
+                msg.display_name,
+                mime_message.get_payload(),
+                mime_message.get_content_charset())
+
+        elif mime_message.get_content_type() == 'text/x-msmsgscontrol':
+            self.callbacks.typing_received(msg.passport_id,
+            msg.display_name)
+
+    def __process_joi(self, buf):
+        joi = split(buf)
+        self.callbacks.friend_joined(joi[1], url_codec.decode(joi[2]))
+
+    def __process_bye(self, buf):
+        bye = split(buf)
+        self.callbacks.friend_left(bye[1])
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# codec.py -- UrlCodec class, url_codec global
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+from string import split, join
+from binascii import hexlify, unhexlify
+
+class UrlCodec:  # url-encoding (rfc 1738)
+    def encode(self, str):
+        if str == None:
+            return None
+        buf = []
+        for c in str:
+            h = hexlify(c)
+            i = ord(c)
+            if 0x00 <= i <= 0x20 or i == 0x7f or 0x80 <= i <= 0xff:
+                buf.append('%')
+                buf.append(h)
+            else:
+                buf.append(c)
+        return join(buf, '')
+
+    def decode(self, str):
+        if str == None:
+            return None
+        buf = []
+        p = hex = None
+        for c in str:
+            if c == '%':
+                p = '%'
+            elif p != None:
+                (hex, p) = (c, None)
+            elif hex != None:
+                hex = hex + c
+                buf.append(unhexlify(hex))
+                hex = None
+            else:
+                buf.append(c)
+        return join(buf, '')
+url_codec = UrlCodec()
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# command.py -- Command class, and subclasses
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+import md5
+import email
+import email.Message
+import email.Charset
+
+from string import split, join
+from binascii import hexlify, unhexlify
+
+from codec import url_codec
+
+class Command:
+    def __init__(self, cmd = None, trn = None, args = None):
+        self.cmd = cmd
+        self.trn = trn
+        self.args = args
+
+    def parse(self, str):
+        s = split(str)
+        pos = 0
+        if s == None or len(s) <= 0: return
+        self.cmd, pos = s[pos], pos + 1
+        if len(s) <= pos: return
+        if self.cmd in ('NLN', 'FLN',
+            'GTC', 'BLP', 'PRP', 'LSG', 'LST',
+            'BPR'):
+            self.trn = 0
+        else:
+            self.trn, pos = int(s[pos]), pos + 1
+        if len(s) <= pos: return
+        self.args, pos = tuple(s[pos:]), pos + 1
+
+    def __str__(self):
+        cmd_trn = join((self.cmd, str(self.trn)))
+        if self.args != None:
+            args = join(self.args)
+        else:
+            args = ''
+        return join((cmd_trn, args))
+
+    def send(self, conn):
+        conn.send_data_line(str(self))
+
+class Msg(Command):
+    def __init__(self):
+        Command.__init__(self, 'MSG')
+        self.passport_id = None
+        self.display_name = None
+        self.msg_len = -1
+        self.msg_buf = None
+
+    def parse(self, str):
+        s = split(str)
+        self.cmd = s[0]
+        self.passport_id = s[1]
+        self.display_name = url_codec.decode(s[2])
+        self.msg_len = int(s[3])
+
+    # for fetching the message part, after the command's '\r\n'
+    def receive(self, conn):
+        self.msg_buf = conn.receive_data(self.msg_len)
+
+    def send(self, conn):
+        conn.send_data_line(str(self))
+        conn.send_data_all(self.msg_buf)
+
+class Png(Command):
+    def __init__(self):
+        self.cmd = 'PNG'
+        self.trn = 0
+        self.args = None
+
+    def parse(self, str):
+        pass
+
+    def __str__(self):
+        return self.cmd
+
+class Qry(Command):  # response to server's CHL (challenge)
+    def __init__(self, trn, hash):
+        Command.__init__(self, 'QRY', trn, ('msmsgs@msnmsgr.com 32',))
+        self.hash = hash
+
+    def parse(self, str):
+        pass
+
+    def __str__(self):
+        s = Command.__str__(self)
+        m = md5.new()
+        m.update(self.hash)
+        m.update('Q1P7W2E4J9R8U3S5')
+        digest = hexlify(m.digest())
+        return s + '\n' + digest
+
+    def send(self, conn):
+        conn.send_data_all(str(self))
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# error.py -- Error class(es)
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+class Error:
+    """Generic exception type"""
+    def __init__(self, code, message):
+        self.code = code
+        self.message = message
+    def __str__(self):
+        return str(self.code) + ':' + self.message
+
+class HttpError(Error):
+    """Error returned from HTTP server"""
+    def __init__(self, code, message, http_status, http_reason):
+        Error.__init__(self, code, message)
+        self.http_status = http_status
+        self.http_reason = http_reason
+    def __str__(self):
+        return Error.__str__(self) \
+        + '[%s:%s]' % (str(self.http_status), self.http_reason)
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# friend.py -- Group, Friend, FriendList classes
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+from protocol import States, Lists, PrivacyModes
+from time import time
+
+class Group:
+    """A group in the friend list"""
+    def __init__(self, id, name, friends = None):
+        self.id = id
+        self.name = name
+        if friends == None:
+            friends = {}
+        self.friends = friends
+
+    def size(self):
+        """Return number of friends in this group"""
+        return len(self.friends)
+
+    def get_id(self):
+        """Return ID of this group"""
+        return self.id
+
+    def get_name(self):
+        """Return name of this group"""
+        return self.name
+
+    def get_friend(self, passport_id):
+        """Return friend in this group
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+        """
+        if self.friends.has_key(passport_id):
+            return self.friends[passport_id]
+        else:
+            return None
+
+    def get_friends(self):
+        """Return all friends in this group"""
+        return self.friends.values()
+
+    def get_online_friends(self):
+        """Return all online friends in this group"""
+        return filter(lambda f: f.state != States.OFFLINE, self.friends)
+
+class Friend:
+    """A friend in the friend list"""
+    def __init__(self, passport_id, display_name,
+        state = States.OFFLINE, groups = None):
+
+        self.passport_id = passport_id
+        self.display_name = display_name
+        self.state = state
+        self.groups = {}
+
+        if groups == None:
+            groups = ()
+        for g in groups:
+            self.add_to_group(g)
+
+    def get_passport_id(self):
+        """Return friend's passport ID"""
+        return self.passport_id
+
+    def get_display_name(self):
+        """Return friend's display name"""
+        return self.display_name
+
+    def get_state(self):
+        """Return friend's presence state"""
+        return self.state
+
+    def get_groups(self):
+        """Return msnp.Group instances representing friend's groups"""
+        return self.groups.values()
+
+    def add_to_group(self, group):
+        """Add friend to given group"""
+        group.friends[self.passport_id] = self
+        self.groups[group.id] = group
+
+    def remove_from_group(self, group):
+        """Remove friend from given group"""
+        del group.friends[self.passport_id]
+        del self.groups[group.id]
+
+class FriendList:
+    """Friend list
+    
+    Includes groups, all types of lists (forward, reverse, allow, block), and
+    some other book-keeping information.  msnp.Session.friend_list is an
+    instance of this class.
+    """
+    def __init__(self):
+        self.ver = 0
+        self.groups = {}
+        self.lists = {
+            Lists.FORWARD: {},
+            Lists.REVERSE: {},
+            Lists.ALLOW: {},
+            Lists.BLOCK: {},
+        }
+        self.privacy_mode = PrivacyModes.BLOCK
+        self.notify_on_add_ = True
+        self.dirty = True
+        self.updated = time()
+        self.temp_iln = {}
+
+    def is_dirty(self):
+        """If this list is dirty (needs update from server)"""
+        return self.dirty
+
+    def get_group(self, id):
+        """Return msnp.Group instance corresponding to the given group ID"""
+        if self.groups.has_key(id):
+            return self.groups[id]
+        else:
+            return None
+
+    def get_groups(self):
+        """Return all groups in this list"""
+        return self.groups.values()
+
+    def get_friend(self, passport_id, list_ = Lists.FORWARD):
+        """Return msnp.Friend instance for given passport ID and list type"""
+        if self.lists[list_].has_key(passport_id):
+            return self.lists[list_][passport_id]
+        else:
+            return None
+
+    def get_friends(self, list_ = Lists.FORWARD):
+        """Return all friends from given list type"""
+        return self.lists[list_].values()
+
+    def size(list_):
+        """Return size (no. of members) of given list"""
+        return len(self.lists[list_])
+
+    def get_online_friends(self):
+        """Return all online friends from forward list"""
+        return filter(lambda f: f.state != States.OFFLINE,
+            self.lists[Lists.FORWARD])
+
+    def get_privacy_mode(self):
+        """Return privacy mode (see msnp.PrivacyModes)"""
+        return self.privacy_mode
+
+    def notify_on_add(self):
+        """Whether or not to be notified on being added to someone's list"""
+        return self.notify_on_add_
+
+    def last_updated(self):
+        """Last updated timestamp, in seconds since the epoch"""
+        return self.updated
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# net.py -- Connection, HttpProxyConnection classes
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+import socket
+import httplib
+
+from string import split, join
+
+class Connection:  # generic tcp connection wrapper
+    def __init__(self, server):
+        self.socket = None
+        self.server = server
+
+    def establish(self):
+        if self.socket == None:
+            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+            server = (self.server[0], int(self.server[1]))
+            s.connect(server)
+            self.socket = s
+        return self.socket
+
+    def send_data(self, buf):
+        return self.socket.send(buf)
+
+    def receive_data(self, bufsize):
+        return self.socket.recv(bufsize)
+
+    def send_data_all(self, buf):
+        total = len(buf)
+        sent = 0
+        while sent < total:
+            sent = sent + self.send_data(buf[sent:])
+        return sent
+
+    def send_data_line(self, line):
+        # print "C:" + line #XXX
+        return self.send_data_all(line) + self.send_data_all('\r\n')
+
+    def receive_data_line(self):
+        cnt = 0
+        buf = ''
+        while 1:
+            in_byte = self.receive_data(1)
+            if in_byte == '':
+                return None
+            if in_byte == '\r':
+                cnt = 1
+            elif in_byte == '\n' and cnt == 1:
+                cnt = 2
+            else:
+                cnt = 0
+            buf = buf + in_byte
+            if cnt == 2:
+                # print "S:" + buf #XXX
+                return buf
+
+    def break_(self):
+        self.socket.shutdown(2)
+        self.socket.close()
+        self.socket = None
+
+class HttpProxyConnection(Connection):  # http tunnelling
+    def __init__(self, server, proxy):
+        Connection.__init__(self, server)
+        self.proxy = proxy
+
+    def establish(self):
+        tmp = self.server
+        self.server = self.proxy
+        try:
+            Connection.establish(self)
+        finally:
+            self.server = tmp
+
+        connect_str = 'CONNECT ' + self.server[0] \
+            + ':' + str(self.server[1]) \
+            + ' HTTP/1.0\r\n'
+        self.send_data_all(connect_str)
+        self.send_data_all('User-Agent: msnp.py\r\n')
+        self.send_data_all('Host: ' + self.server[0] + '\r\n')
+        self.send_data_all('\r\n')
+
+        status = -1
+        while 1:
+            buf = self.receive_data_line()
+            if status == -1:
+                resp = split(buf, ' ', 2)
+                if len(resp) > 1:
+                    status = int(resp[1])
+                else:
+                    status = 0
+            if buf == '\r\n':
+                break
+
+        if status != 200:
+            self.socket = None
+        return self.socket
+
+class HTTPSConnection(httplib.HTTPSConnection):
+    # httplib.HTTPSConnection with HTTP proxy support
+    def __init__(self, host, port = None, key_file = None, cert_file = None,
+                 strict = None, http_proxy = None):
+        httplib.HTTPSConnection.__init__(self, host, port, key_file, cert_file,
+                                         strict)
+        self.http_proxy = http_proxy
+
+    def connect(self):
+        if self.http_proxy:
+            conn = HttpProxyConnection((self.host, self.port), self.http_proxy)
+            conn.establish()
+            sock = conn.socket
+            ssl = socket.ssl(sock, self.key_file, self.cert_file)
+            self.sock = httplib.FakeSocket(sock, ssl)
+        else:
+            httplib.HTTPSConnection.connect(self)
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# protocol.py -- States, Lists, PrivacyModes classes, and errors global
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+class States:
+    """Presence states"""
+    ONLINE = 'NLN'
+    OFFLINE = 'FLN'
+    INVISIBLE = 'HDN'
+    BUSY = 'BSY'
+    IDLE = 'IDL'
+    BE_RIGHT_BACK = 'BRB'
+    AWAY = 'AWY'
+    ON_THE_PHONE = 'PHN'
+    OUT_TO_LUNCH = 'LUN'
+
+class Lists:
+    """Types of friend lists"""
+    FORWARD = 'FL'
+    REVERSE = 'RL'
+    ALLOW = 'AL'
+    BLOCK = 'BL'
+
+class PrivacyModes:
+    """Privacy modes"""
+    ALLOW = 'AL'
+    BLOCK = 'BL'
+
+list_flags = {
+    Lists.FORWARD : 1,
+    Lists.ALLOW   : 2,
+    Lists.BLOCK   : 4,
+    Lists.REVERSE : 8,
+}
+
+errors = {
+    '200': 'Syntax error',
+    '201': 'Invalid parameter',
+    '205': 'Invalid user',
+    '206': 'Domain name missing',
+    '207': 'Already logged in',
+    '208': 'Invalid username',
+    '209': 'Invalid fusername',
+    '210': 'User list full',
+    '215': 'User already there',
+    '216': 'User already on list',
+    '217': 'User not online',
+    '218': 'Already in mode',
+    '219': 'User is in the opposite list',
+    '219': 'User is in the opposite list',
+    '231': 'Tried to add a contact to a group that doesn\'t exist',
+    '280': 'Switchboard failed',
+    '281': 'Transfer to switchboard failed',
+
+    '300': 'Required field missing',
+    '302': 'Not logged in',
+
+    '500': 'Internal server error',
+    '501': 'Database server error',
+    '510': 'File operation failed',
+    '520': 'Memory allocation failed',
+    '540': 'Wrong CHL value sent to server',
+
+    '600': 'Server is busy',
+    '601': 'Server is unavaliable',
+    '602': 'Peer nameserver is down',
+    '603': 'Database connection failed',
+    '604': 'Server is going down',
+
+    '707': 'Could not create connection',
+    '710': 'CVR parameters either unknown or not allowed',
+    '711': 'Write is blocking',
+    '712': 'Session is overloaded',
+    '713': 'Too many active users',
+    '714': 'Too many sessions',
+    '715': 'Not expected',
+    '717': 'Bad friend file',
+
+    '911': 'Authentication failed',
+    '913': 'Not allowed when offline',
+    '920': 'Not accepting new users',
+    '924': 'Passport account not yet verified',
+}
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+# session.py -- Session, SessionCallbacks classes
+#
+# Copyright (C) 2003 Manish Jethani (manish_jethani AT yahoo.com)
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+import select
+import md5
+
+from string import split, join
+from binascii import hexlify, unhexlify
+from time import time
+
+from protocol import States, Lists, PrivacyModes
+from error import Error, HttpError
+from friend import Group, Friend, FriendList
+from net import Connection, HttpProxyConnection
+from command import Command, Msg, Png, Qry
+from codec import url_codec
+
+import protocol
+import chat
+
+class _Session:  # common base for Session and Chat
+    def __init__(self, callbacks):
+        self.callbacks = callbacks
+        self.transaction_id = 0
+        self.http_proxy = None
+        self.conn = None
+        self.send_queue = []
+
+    def _connect(self, server):
+        conn = None
+        if self.http_proxy:
+            conn = HttpProxyConnection(server, self.http_proxy)
+        else:
+            conn = Connection(server)
+        conn.establish()
+        return conn
+
+    def _increment_transaction_id(self):
+        self.transaction_id = self.transaction_id + 1
+        return self.transaction_id
+
+    def _send_cmd(self, cmd, conn):
+        conn.send_data_line(str(cmd))
+        self._increment_transaction_id()
+
+    def _receive_cmd(self, conn):
+        buf = conn.receive_data_line()
+        if buf == None:  # connection closed
+            raise Error(1, 'Connection closed.')
+        cmd = Command()
+        cmd.parse(buf)
+        return cmd
+
+    def _sync_command(self, cmd, conn):
+        # synchronous command (receive response immediately)
+        self._send_cmd(cmd, conn)
+        return self._receive_cmd(conn)
+
+    def _async_command(self, cmd):
+        self.send_queue.append(cmd)
+        self._increment_transaction_id()
+
+class SessionCallbacks:  # callback interface
+    """Callback interface for MSN instant messaging session
+
+    To receive notification on various protocol events, the client must
+    implement some or all of the methods in this callback interface.
+    """
+
+    def ping(self):
+        """Ping received from server"""
+
+    def state_changed(self, state):
+        """User's presence state has changed
+
+        Keyword arguments:
+            state -- any of the msnp.States members
+        """
+
+    def friend_online(self, state, passport_id, display_name):
+        """Friend is online
+
+        Keyword arguments:
+            state -- any of the msnp.States members
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+        """
+
+    def friend_offline(self, passport_id):
+        """Friend is offline
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+        """
+
+    def friend_list_updated(self, friend_list):
+        """Friend list has been updated
+
+        Keyword arguments:
+            friend_list -- same as msnp.Session.friend_list
+        """
+
+    def logged_out(self):
+        """User has been logged out"""
+
+    def group_added(self, id, name):
+        """Group has been added
+
+        Keyword arguments:
+            id -- group ID
+            name -- name of group
+        """
+
+    def group_removed(self, id):
+        """Group has been removed
+
+        Keyword arguments:
+            id -- group ID
+        """
+
+    def group_renamed(self, id, name):
+        """Group has been renamed
+
+        Keyword arguments:
+            id -- group ID
+            name -- new name of group
+        """
+
+    def friend_added(self, list_, passport_id, display_name, group_id = -1):
+        """Friend has been added
+
+        If list_ is msnp.Lists.REVERSE, it means that the user has been added
+        to someone's list.  In that case, the passport_id and display_name
+        parameters contain information about that someone.
+
+        Keyword arguments:
+            list_ -- type of list (allow, block, etc.)
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+            group_id -- group ID of group to which friend has been added
+        """
+
+    def friend_removed(self, list_, passport_id, group_id = -1):
+        """Friend has been removed
+
+        Keyword arguments:
+            list_ -- type of list (allow, block, etc.)
+            passport_id -- string representing friend's passport ID
+            group_id -- group ID of group from which friend has been removed
+        """
+
+    def display_name_changed(self, display_name):
+        """Display name changed
+
+        Keyword arguments:
+            display_name -- user's new display name
+        """
+
+    def display_name_received(self, passport_id, display_name):
+        """Display name received
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+            display_name -- friend's display name
+        """
+
+    def chat_started(self, chat):
+        """Chat started
+
+        Keyword arguments:
+            chat -- Chat instance representing new chat started
+        """
+
+class Session(_Session):
+    """MSN instant messaging session
+
+    To get into an instant messaging session, an instance of msnp.Session must
+    be created.  The session can be started by calling the login method.  After
+    logging in, the process method must be called periodically to process the
+    server's commands.
+    """
+
+    class __ChatRequest:
+        def __init__(self, invitee):
+            self.invitee = invitee
+
+    def __init__(self, callbacks = None, dispatch_server = None):
+        """Constructor for msnp.Session
+
+        Keyword arguments:
+            callbacks -- callback interface
+            dispatch_server -- dispatch server host, port
+        """
+
+        if callbacks == None:
+            callbacks = SessionCallbacks()
+        _Session.__init__(self, callbacks)
+
+        if dispatch_server == None:
+            self.dispatch_server = ('messenger.hotmail.com', 1863)
+
+        self.logged_in = 0
+        self.passport_id = None
+        self.display_name = None
+        self.chat_requests = {}
+        self.friend_list = FriendList()
+        self.active_chats = {}
+
+    def __get_twn_ticket(self, twn_string, username, password):
+        from net import HTTPSConnection
+        from urllib import urlencode
+        debuglevel = 0
+
+        # step 1: get address of login server
+        con = HTTPSConnection('nexus.passport.com',
+            http_proxy = self.http_proxy)
+        con.set_debuglevel(debuglevel)
+        con.request('GET', '/rdr/pprdr.asp')
+        res = con.getresponse()
+        con.close()
+        if res.status != 200:
+            raise HttpError(0, 'Bad response from passport nexus server.',
+                res.status, res.reason)
+        hdr = res.getheader('PassportURLs')
+        url = {}
+        for u in hdr.split(','):
+            k, v = u.split('=')
+            url[k] = v
+        dalogin = url['DALogin'].split('/', 1)
+
+        # step 2: get "ticket" to notification server
+        while True:
+            con = HTTPSConnection(dalogin[0], http_proxy = self.http_proxy)
+            con.set_debuglevel(debuglevel)
+            auth = 'Passport1.4 OrgVerb=GET,%s,%s,%s,%s' \
+                % (urlencode({'OrgURL': 'http://messenger.msn.com'}),
+                    urlencode({'sign-in': username}),
+                    urlencode({'pwd': password}),
+                    twn_string)
+            con.request('GET', '/%s' % (dalogin[1]), '',
+                {'Authorization': auth})
+            res = con.getresponse()
+            con.close()
+            if res.status != 200:
+                raise HttpError(0, 'Bad response from login server.',
+                    res.status, res.reason) # XXX handle redirection?
+            else:
+                break
+        hdr = res.getheader('Authentication-Info') or \
+              res.getheader('WWW-Authenticate')
+        hdr = hdr[len('Passport1.4 '):]
+        auth = {}
+        for u in hdr.split(','):
+            k, v = u.split('=', 1)
+            if v[0] == '\'' and v[-1] == '\'':
+                v = v[1:-1]
+            auth[k] = v
+        ticket = auth['from-PP']
+
+        return ticket
+        # TODO code cleanup
+
+    def __handshake(self, server, username, password):
+        conn = self._connect(server)
+        try:
+            ver = Command('VER', self.transaction_id, ('MSNP8', 'CVR0'))
+            resp = self._sync_command(ver, conn)
+            if resp.cmd != 'VER' or resp.args[0] == '0':
+                raise Error(0, 'Bad response for VER command.')
+
+            cvr = Command('CVR', self.transaction_id,
+                ('0x0409', 'win', '4.10', 'i386', 'MSNMSGR', '6.0.0602',
+                'MSMSGS ', username))
+            resp = self._sync_command(cvr, conn)
+            if resp.cmd != 'CVR':
+                raise Error(0, 'Bad response for CVR command.')
+
+            usr = Command('USR', self.transaction_id, ('TWN', 'I', username))
+            resp = self._sync_command(usr, conn)
+            if resp.cmd != 'USR' and resp.cmd != 'XFR':
+                raise Error(0, 'Bad response for USR command.')
+
+            # for dispatch server, response is ver, cvr, xfr; for notification
+            # server, it is ver, cvr, usr (or same as dispatch server, in some
+            # cases)
+
+            if resp.cmd == 'XFR':
+                return split(resp.args[1], ':', 1)
+            elif resp.cmd == 'USR':
+                twn_string = resp.args[2]
+
+                ticket = self.__get_twn_ticket(twn_string, username, password)
+
+                usr = Command('USR', self.transaction_id, ('TWN', 'S', ticket))
+                resp = self._sync_command(usr, conn)
+                if resp.cmd != 'USR':
+                    raise Error(int(resp.cmd), protocol.errors[resp.cmd])
+                elif resp.args[0] != 'OK':
+                    raise Error(0, 'Bad response for USR command.')
+
+                self.passport_id = resp.args[1]
+                self.display_name = url_codec.decode(resp.args[2])
+                self.logged_in = 1
+        finally:
+            if not self.logged_in:
+                conn.break_()
+            else:
+                self.conn = conn
+
+    def process(self, chats = False):
+        """Process events
+
+        Keyword arguments:
+            chats -- whether or not to call msnp.Chat.process for all active
+                chat sessions
+
+        This method must be called periodically, preferably in the client
+        application's main loop.
+        """
+        while self.logged_in:
+            fd = self.conn.socket.fileno()
+            r = select.select([fd], [], [], 0)
+            if len(r[0]) > 0:
+                buf = self.conn.receive_data_line()
+                self.__process_command_buf(buf)
+            elif len(self.send_queue) > 0:
+                cmd = self.send_queue.pop(0)
+                cmd.send(self.conn)
+            else:
+                break
+        if chats:
+            self.__process_active_chats()
+
+    def __process_active_chats(self):
+        [chat_.process() for chat_ in self.active_chats.values()]
+
+    def __process_command_buf(self, buf):
+        cmd = buf[:3]
+        if cmd == 'MSG':
+            self.__process_msg(buf)
+        elif cmd == 'QNG':
+            self.__process_qng(buf)
+        elif cmd == 'OUT':
+            self.__process_out(buf)
+        elif cmd == 'RNG':
+            self.__process_rng(buf)
+        else:
+            c = Command()
+            c.parse(buf)
+            if c.cmd == 'CHG':
+                self.__process_chg(c)
+            elif c.cmd == 'ILN':
+                self.__process_iln(c)
+            elif c.cmd == 'NLN':
+                self.__process_nln(c)
+            elif c.cmd == 'FLN':
+                self.__process_fln(c)
+            elif c.cmd == 'CHL':
+                self.__process_chl(c)
+            elif c.cmd == 'LSG':
+                self.__process_lsg(c)
+            elif c.cmd == 'LST':
+                self.__process_lst(c)
+            elif c.cmd == 'SYN':
+                self.__process_syn(c)
+            elif c.cmd == 'XFR':
+                self.__process_xfr(c)
+            elif c.cmd == 'BLP':
+                self.__process_blp(c)
+            elif c.cmd == 'GTC':
+                self.__process_gtc(c)
+            elif c.cmd == 'ADG':
+                self.__process_adg(c)
+            elif c.cmd == 'RMG':
+                self.__process_rmg(c)
+            elif c.cmd == 'REG':
+                self.__process_reg(c)
+            elif c.cmd == 'ADD':
+                self.__process_add(c)
+            elif c.cmd == 'REM':
+                self.__process_rem(c)
+            elif c.cmd == 'REA':
+                self.__process_rea(c)
+            elif c.cmd == '218':
+                pass
+            # TODO error handling
+
+    def __process_msg(self, buf):
+        msg = Msg()
+        msg.parse(buf)
+        msg.receive(self.conn)
+        # discard NS messages for now
+
+    def __process_qng(self, buf):
+        self.callbacks.ping()
+
+    def __process_out(self, buf):
+        self.conn.break_()
+        self.conn = None
+        self.logged_in = 0
+        self.callbacks.logged_out()
+
+    def __process_rng(self, buf):
+        cmdline = split(buf)
+        session_id = cmdline[1]
+        sb = split(cmdline[2], ':')
+        server = (sb[0], int(sb[1]))
+        hash = cmdline[4]
+        passport_id = cmdline[5]
+        display_name = url_codec.decode(cmdline[6])
+        try:
+            chat_ = chat.Chat(self, server, hash, passport_id,
+                display_name, session_id)
+        except Error, e:
+            if e.code == 1:  # connection closed
+                return
+            raise e
+        self.active_chats[chat_.session_id] = chat_
+        self.callbacks.chat_started(chat_)
+
+    def __process_chg(self, command):
+        self.callbacks.state_changed(command.args[0])
+
+    def __process_iln(self, command):
+        state = command.args[0]
+        passport_id = command.args[1]
+        display_name = url_codec.decode(command.args[2])
+        friend = self.friend_list.get_friend(passport_id)
+        if friend != None:
+            friend.state = state
+            friend.display_name = display_name
+            self.__friend_list_updated()
+        else:  # usu. immed. after login
+            self.friend_list.temp_iln[passport_id] = state
+        self.callbacks.friend_online(state, passport_id, display_name)
+
+    def __process_nln(self, command):
+        state = command.args[0]
+        passport_id = command.args[1]
+        display_name = url_codec.decode(command.args[2])
+        friend = self.friend_list.get_friend(passport_id)
+        if friend != None:
+            friend.display_name = display_name
+            friend.state = state
+            self.__friend_list_updated()
+        self.callbacks.friend_online(state, passport_id, display_name)
+
+    def __process_fln(self, command):
+        passport_id = command.args[0]
+        friend = self.friend_list.get_friend(passport_id)
+        if friend != None:
+            friend.state = States.OFFLINE
+            self.__friend_list_updated()
+        self.callbacks.friend_offline(passport_id)
+
+    def __process_chl(self, command):
+        qry = Qry(self.transaction_id, command.args[0])
+        self._async_command(qry)
+
+    def __process_lsg(self, command):
+        id = int(command.args[0])
+        name = url_codec.decode(command.args[1])
+
+        group = Group(id, name)
+        self.friend_list.groups[id] = group
+
+        self.__friend_list_updated()
+
+    def __process_lst(self, command):
+        from protocol import list_flags
+
+        passport_id  = command.args[0]
+        display_name = url_codec.decode(command.args[1])
+        list_        = int(command.args[2])
+        group_id     = []
+
+        if list_ & list_flags[Lists.FORWARD]:
+            group_id = [int(i) for i in split(command.args[3], ',')]
+
+        groups = None
+        if len(group_id):
+            groups = [self.friend_list.groups[g_id] for g_id in group_id]
+
+        friend = Friend(passport_id, display_name, groups = groups)
+        for f in list_flags.keys():
+            if list_ & list_flags[f]:
+                self.friend_list.lists[f][passport_id] = friend
+
+        if self.friend_list.temp_iln.has_key(passport_id):
+            friend.state = self.friend_list.temp_iln[passport_id]
+
+        self.__friend_list_updated()
+
+    def __process_syn(self, command):
+        ver = int(command.args[0])
+        self.friend_list.ver = ver
+        self.__friend_list_updated()
+
+    def __process_xfr(self, command):
+        sb = split(command.args[1], ':')
+        server = (sb[0], int(sb[1]))
+        cr = self.chat_requests[command.trn]
+        invitee = cr.invitee
+        chat_ = chat.Chat(self, server, command.args[3], self.passport_id,
+            self.display_name, None, invitee)
+        self.active_chats[chat_.session_id] = chat_
+        self.callbacks.chat_started(chat_)
+
+    def __process_blp(self, command):
+        privacy_mode = command.args[0]
+        self.friend_list.privacy_mode = privacy_mode
+        self.__friend_list_updated()
+
+    def __process_gtc(self, command):
+        notify_on_add = command.args[0] == 'A'
+        self.friend_list.notify_on_add_ = notify_on_add
+        self.__friend_list_updated()
+
+    def __process_adg(self, command):
+        ver = int(command.args[0])
+        name = url_codec.decode(command.args[1])
+        id = int(command.args[2])
+        self.friend_list.ver = ver
+        self.friend_list.groups[id] = Group(id, name)
+        self.__friend_list_updated()
+        self.callbacks.group_added(id, name)
+
+    def __process_rmg(self, command):
+        ver = int(command.args[0])
+        id = int(command.args[1])
+        self.friend_list.ver = ver
+        if self.friend_list.groups.has_key(id):
+            del self.friend_list.groups[id]
+        self.__friend_list_updated()
+        self.callbacks.group_removed(id)
+
+    def __process_reg(self, command):
+        ver = int(command.args[0])
+        id = int(command.args[1])
+        name = url_codec.decode(command.args[2])
+        self.friend_list.ver = ver
+        if self.friend_list.groups.has_key(id):
+            self.friend_list.groups[id].name = name
+        self.__friend_list_updated()
+        self.callbacks.group_renamed(id, name)
+
+    def __process_add(self, command):
+        list_ = command.args[0]
+        ver = int(command.args[1])
+        passport_id = command.args[2]
+        display_name = url_codec.decode(command.args[3])
+        group = None
+        if list_ == Lists.FORWARD:
+            group = self.friend_list.groups[int(command.args[4])]
+
+        self.friend_list.ver = ver
+ 
+        friend = self.friend_list.get_friend(passport_id, list_)
+        if friend != None:
+            friend.add_to_group(group)
+        else:
+            if group != None:
+                friend = Friend(passport_id, passport_id, (group))
+            else:
+                friend = Friend(passport_id, passport_id)
+            self.friend_list.lists[list_][passport_id] = friend
+
+        self.__friend_list_updated()
+
+        if group != None:
+            self.callbacks.friend_added(list_, passport_id, display_name,
+                group.get_id())
+        else:
+            self.callbacks.friend_added(list_, passport_id, display_name)
+
+    def __process_rem(self, command):
+        list_ = command.args[0]
+        ver = int(command.args[1])
+        passport_id = command.args[2]
+        group = None
+        if list_ == Lists.FORWARD:
+            group = self.friend_list.groups[int(command.args[3])]
+
+        self.friend_list.ver = ver
+
+        friend = self.friend_list.get_friend(passport_id, list_)
+        if friend != None: # this shouldn't be None, unless friend_list stale
+            if group != None:
+                friend.remove_from_group(group)
+            if len(friend.get_groups()) == 0:
+                del self.friend_list.lists[list_][passport_id]
+
+        self.__friend_list_updated()
+        if group != None:
+            self.callbacks.friend_removed(list_, passport_id, group.get_id())
+        else:
+            self.callbacks.friend_removed(list_, passport_id)
+
+    def __process_rea(self, command):
+        ver = int(command.args[0])
+        passport_id = command.args[1]
+        display_name = url_codec.decode(command.args[2])
+
+        if passport_id == self.passport_id:
+            self.display_name = display_name
+            self.callbacks.display_name_changed(display_name)
+        else:
+            self.callbacks.display_name_received(passport_id, display_name)
+
+    def __friend_list_updated(self):
+        self.friend_list.updated = time()
+        self.callbacks.friend_list_updated(self.friend_list)
+
+    def login(self, username, password, initial_state = States.ONLINE):
+        """Login to MSN server
+
+        Keyword arguments:
+            username -- username
+            password -- password
+            initial_state -- initial state (default msnp.States.ONLINE)
+        """
+        if self.logged_in:
+            return
+        server = self.dispatch_server
+        while not self.logged_in:
+            server = self.__handshake(server, username, password)
+        self.change_state(initial_state)
+
+    def ping(self):
+        """Ping server"""
+        if not self.logged_in:
+            return
+        self._async_command(Png())
+        self.process()
+
+    def logout(self):
+        """Logout from server"""
+        if not self.logged_in:
+            return
+        [chat_.leave() for chat_ in self.active_chats.values()]
+        self.process()
+        self.conn.break_()
+        self.conn = None
+        self.logged_in = 0
+
+    def change_state(self, state):
+        """Change user's state
+
+        Keyword arguments:
+            state -- new state (see msnp.States)
+        """
+        if not self.logged_in:
+            return
+        chg = Command('CHG', self.transaction_id, (state,))
+        self._async_command(chg)
+        self.process()
+
+    def sync_friend_list(self, ver = -1):
+        """Synchronise friend list by getting new copy from server
+
+        The friend list is updated asynchronously.
+        msnp.SessionCallbacks.friend_list_updated will be called repeatedly
+        after a call to this method.  The client may want to set a timer
+        instead, and check for updates to the friend list using the
+        msnp.FriendList.last_updated method.
+
+        Keyword arguments:
+            ver -- friend list version
+        """
+        if not self.logged_in:
+            return
+        self.friend_list.dirty = False
+        if ver == -1:
+            ver = self.friend_list.ver
+        syn = Command('SYN', self.transaction_id, (str(ver),))
+        self._async_command(syn)
+        self.process()
+
+    def request_list(self, list_ = Lists.FORWARD):
+        """Request a list from the server
+
+        Keyword arguments:
+            list_ -- type of list to request (see msnp.Lists)
+        """
+        if not self.logged_in:
+            return
+        lst = Command('LST', self.transaction_id, (list_,))
+        self._async_command(lst)
+        self.process()
+
+    def request_groups(self):
+        """Request groups from server"""
+        if not self.logged_in:
+            return
+        lsg = Command('LSG', self.transaction_id, ())
+        self._async_command(lsg)
+        self.process()
+
+    def change_privacy_mode(self, privacy_mode):
+        """Change privacy mode
+
+        Keyword arguments:
+            privacy_mode -- new privacy mode (see msnp.PrivacyModes)
+        """
+        if not self.logged_in:
+            return
+        blp = Command('BLP', self.transaction_id, (privacy_mode,))
+        self._async_command(blp)
+        self.process()
+
+    def notify_on_add(self, notify):
+        """Change setting for being notified on being added"""
+        if not self.logged_in:
+            return
+        setting = 'N'
+        if notify:
+            setting = 'A'
+        gtc = Command('GTC', self.transaction_id, (setting,))
+        self._async_command(gtc)
+        self.process()
+
+    def add_group(self, name):
+        """Add a group
+        
+        Keyword arguments:
+            name -- name of new group
+        """
+        if not self.logged_in:
+            return
+        adg = Command('ADG', self.transaction_id,
+            (url_codec.encode(name), '0'))
+        self._async_command(adg)
+        self.process()
+
+    def remove_group(self, id):
+        """Remove a group
+
+        Keyword arguments:
+            id -- group ID
+        """
+        if not self.logged_in:
+            return
+        rmg = Command('RMG', self.transaction_id, (str(id),))
+        self._async_command(rmg)
+        self.process()
+
+    def rename_group(self, id, name):
+        """Rename a group
+
+        Keyword arguments:
+            id -- group ID
+            name -- new name of group
+        """
+        if not self.logged_in:
+            return
+        reg = Command('REG', self.transaction_id,
+            (str(id), url_codec.encode(name), '0'))
+        self._async_command(reg)
+        self.process()
+
+    def add_friend(self, list_, passport_id, group_id = 0):
+        """Add a friend
+
+        Keyword arguments:
+            list_ -- type of list (allow, block, etc.)
+            passport_id -- string representing friend's passport ID
+            group_id -- group ID of group to which friend is being added
+        """
+        add = None
+        if list_ == Lists.FORWARD:
+            add = Command('ADD', self.transaction_id,
+                (list_, passport_id, passport_id, str(group_id)))
+        else:
+            add = Command('ADD', self.transaction_id,
+                (list_, passport_id, passport_id))
+        self._async_command(add)
+        self.process()
+
+    def remove_friend(self, list_, passport_id, group_id = 0):
+        """Remove a friend
+
+        Keyword arguments:
+            list_ -- type of list (allow, block, etc.)
+            passport_id -- string representing friend's passport ID
+            group_id -- group ID of group from which friend is being removed
+        """
+        rem = None
+        if list_ == Lists.FORWARD:
+            rem = Command('REM', self.transaction_id,
+                (list_, passport_id, str(group_id)))
+        else:
+            rem = Command('REM', self.transaction_id,
+                (list_, passport_id))
+        self._async_command(rem)
+        self.process()
+
+    def change_display_name(self, display_name):
+        """Change user's display name
+
+        Keyword arguments:
+            display_name -- user's new display name
+        """
+        if not self.logged_in:
+            return
+        rea = Command('REA', self.transaction_id,
+            (self.passport_id, url_codec.encode(display_name)))
+        self._async_command(rea)
+        self.process()
+
+    def request_display_name(self, passport_id):
+        """Request display name of a friend
+
+        Keyword arguments:
+            passport_id -- string representing friend's passport ID
+        """
+        if not self.logged_in:
+            return
+        rea = Command('REA', self.transaction_id,
+            (passport_id, url_codec.encode('MJ++')))
+        self._async_command(rea)
+        self.process()
+
+    def start_chat(self, invitee):
+        """Start a chat
+
+        Keyword arguments:
+            invitee -- friend invited for chat
+        """
+        if not self.logged_in:
+            return
+        xfr = Command('XFR', self.transaction_id, ('SB',))
+        self._async_command(xfr)
+        self.chat_requests[xfr.trn] = Session.__ChatRequest(invitee)
+        self.process()
+
+# vim: set ts=4 sw=4 et tw=79 :
+
+#!python
+
+from distutils.core import setup
+
+setup(name="msnp.py",
+      version="0.4.1",
+      description="An implementation of the MSN Messenger Protocol",
+      license="GNU General Public License (Version 2)",
+      author="Manish Jethani",
+      author_email="manish_jethani AT yahoo.com",
+      url="http://msnp.sf.net/",
+      packages = ['msnp'],
+     )
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<html>
+<head>
+<title>msnp.py Tutorial</title>
+
+<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
+
+<style type="text/css">
+<!--
+
+BODY {
+  color: black;
+  background-color: white;
+
+  font-family: serif;
+}
+
+A:link {
+  color: blue;
+  background-color: white;
+}
+
+A:visited {
+  color: purple;