home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 October / maximum-cd-2011-10.iso / DiscContents / digsby_setup.exe / lib / msn / MsnHttpSocket.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-06-22  |  9.6 KB  |  299 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. import threading
  5. import traceback
  6. import collections
  7. import time
  8. import logging
  9. import httplib
  10. import pprint
  11. import threading
  12. import util
  13. import util.allow_once as once
  14. import util.httplib2 as httplib2
  15. import util.threads.threadpool as threadpool
  16. import common
  17. import common.asynchttp as asynchttp
  18. log = logging.getLogger('msnhttp')
  19. import msn
  20. MIMEParse = msn.util.mime_to_dict
  21.  
  22. class MsnHttpSocket(msn.MSNSocketBase):
  23.     POLLINTERVAL = 3
  24.     proto = 'http'
  25.     gateway_ip = 'gateway.messenger.hotmail.com'
  26.     gateway_path = '/gateway/gateway.dll'
  27.     gateway_port = 80
  28.     
  29.     def get_local_sockname(self):
  30.         return ('localhost', 0)
  31.  
  32.     
  33.     def endpoint(self):
  34.         if self.gateway_port != httplib.HTTP_PORT:
  35.             s = '%s://%s:%s%s' % (self.proto, self.gateway_ip, self.gateway_port, self.gateway_path)
  36.         else:
  37.             s = '%s://%s%s' % (self.proto, self.gateway_ip, self.gateway_path)
  38.         return s
  39.  
  40.     endpoint = property(endpoint)
  41.     
  42.     def __init__(self, *a, **k):
  43.         self._session_id = None
  44.         msn.MSNSocketBase.__init__(self, *a, **k)
  45.         self._q = []
  46.         self._waiting = False
  47.         self._poller = util.RepeatTimer(self.POLLINTERVAL, self._poll)
  48.         self._poller._verbose = False
  49.         self._closed = False
  50.         self._poll_in_queue = False
  51.         self._paused = False
  52.  
  53.     
  54.     def connect(self, type_host):
  55.         (type, host) = self._parse_addr(type_host)
  56.         self.typehost = type_host
  57.         self.type = type
  58.         self.host = self._server = host
  59.         self.on_connect()
  60.  
  61.     _connect = connect
  62.     
  63.     def _parse_addr(self, type_addr):
  64.         
  65.         try:
  66.             (type, addr) = type_addr
  67.         except (ValueError, TypeError):
  68.             raise TypeError("%r.connect argument must be <type 'tuple'> (type, addr) not %r (%r)", type(self).__name__, type(type_addr), type_addr)
  69.  
  70.         bad_addr = False
  71.         port = None
  72.         if len(addr) == 1:
  73.             host = addr[0]
  74.             port = 80
  75.         elif isinstance(addr, basestring):
  76.             (host, port) = util.srv_str_to_tuple(addr, 80)
  77.         elif len(addr) == 2:
  78.             (host, port) = addr
  79.         else:
  80.             bad_addr = True
  81.         
  82.         try:
  83.             port = int(port)
  84.         except ValueError:
  85.             bad_addr = True
  86.  
  87.         if bad_addr:
  88.             raise TypeError('%r.connect argument\'s second element must be either string ("srv" or "srv:port") or tuple (("srv", port) or ("srv",)).Got %r instead' % addr)
  89.         bad_addr
  90.         return (type, host)
  91.  
  92.     
  93.     def connect_args_for(self, type, addr):
  94.         return ((type.upper(), addr),)
  95.  
  96.     
  97.     def _poll(self):
  98.         if not (self._waiting) and not (self._poll_in_queue):
  99.             self._poll_in_queue = True
  100.             self.send(None)
  101.         
  102.  
  103.     
  104.     def pause(self):
  105.         self._paused = True
  106.  
  107.     
  108.     def unpause(self):
  109.         self._paused = False
  110.         common.netcall(self.process)
  111.  
  112.     
  113.     def send(self, msgobj, trid = sentinel, callback = None, **kw):
  114.         self._q.append((msgobj, trid, callback, kw))
  115.         if not self._paused:
  116.             common.netcall(self.process)
  117.         
  118.  
  119.     send = util.callsback(send)
  120.     
  121.     def process(self):
  122.         if not (self._q) or self._waiting:
  123.             return None
  124.         self._waiting = True
  125.         data = []
  126.         sending = []
  127.         queue = self._q[:]
  128.         self._q[:] = []
  129.         while queue:
  130.             (msgobj, trid, callback, kw) = queue.pop(0)
  131.             if msgobj is not None:
  132.                 self.set_trid(msgobj, trid)
  133.                 self.set_callbacks(msgobj, callback)
  134.                 data.append(str(msgobj))
  135.             else:
  136.                 self._poll_in_queue = False
  137.             sending.append(callback)
  138.         if self._session_id is None:
  139.             url_kws = dict(Action = 'open', Server = self.type, IP = self.host)
  140.         elif len(data) == 0:
  141.             url_kws = dict(Action = 'poll', SessionID = self._session_id)
  142.         else:
  143.             url_kws = dict(SessionID = self._session_id)
  144.         data = ''.join(data)
  145.         req = self.make_request(url_kws, data = data)
  146.         
  147.         def _transport_error(_req = None, _resp = (None, None, None)):
  148.             log.error('Transport error in MsnHttpSocket: req = %r, resp = %r', _req, _resp)
  149.             if isinstance(_req, Exception):
  150.                 e = _req
  151.             elif isinstance(_resp, Exception):
  152.                 e = _resp
  153.             else:
  154.                 e = _resp
  155.             for cb in sending:
  156.                 cb_error = getattr(callback, 'error', None)
  157.                 if cb_error is not None:
  158.                     cb_error(self, e)
  159.                     continue
  160.             
  161.             
  162.             try:
  163.                 del self.gateway_ip
  164.             except AttributeError:
  165.                 pass
  166.  
  167.             self._on_send_error(e)
  168.  
  169.         asynchttp.httpopen(req, success = self._on_response, error = _transport_error)
  170.  
  171.     
  172.     def fix_session_id(self, sess):
  173.         return sess
  174.  
  175.     
  176.     def _on_response(self, request, response):
  177.         if request.get_data():
  178.             log.debug_s('OUT : %r', request.get_data())
  179.         
  180.         if self._session_id is None:
  181.             self._poller.start()
  182.         
  183.         session_info = MIMEParse(response['x-msn-messenger'])
  184.         self.gateway_ip = session_info.get('GW-IP', self.gateway_ip)
  185.         self._session_id = self.fix_session_id(session_info.get('SessionID', None))
  186.         close = session_info.get('Session', '').lower() == 'close'
  187.         if self._session_id is None and not close:
  188.             raise Exception("Didn't get a session ID!")
  189.         not close
  190.         self._waiting = False
  191.         if not close:
  192.             common.netcall(self.process)
  193.         
  194.         if close:
  195.             self._session_id = None
  196.         
  197.         data = response.body
  198.         self._process_data(data)
  199.         if close:
  200.             self.on_close()
  201.         
  202.  
  203.     
  204.     def _process_data(self, data):
  205.         line = data.readline()
  206.         while line:
  207.             payload = False
  208.             line.rstrip('\r\n')
  209.             dlist = line.split()
  210.             cmd = dlist[0]
  211.             if cmd in self.payload_commands:
  212.                 payload = True
  213.                 
  214.                 try:
  215.                     sz = int(dlist[-1])
  216.                 except ValueError:
  217.                     sz = 0
  218.  
  219.                 line += data.read(sz)
  220.             
  221.             
  222.             try:
  223.                 msg = msn.Message.from_net(line, payload)
  224.                 self.on_message(msg)
  225.             except Exception:
  226.                 e = None
  227.                 log.error('Error handling %r. e = %r', line, e)
  228.                 traceback.print_exc()
  229.  
  230.             line = data.readline()
  231.  
  232.     
  233.     def _on_send_error(self, e):
  234.         log.error('Something bad happened in MsnHttpSocket: %r', e)
  235.         self.on_conn_error(e)
  236.  
  237.     
  238.     def make_request(self, url_kws, data = None):
  239.         url = util.UrlQuery(self.endpoint, url_kws)
  240.         headers = {
  241.             'Accept': '*/*',
  242.             'Content-Type': 'text/xml; charset=utf-8',
  243.             'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SIMBAR={0B74DA00-76D2-11DD-9ABA-0016CFF93348}; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.1.4322; Windows Live Messenger BETA 9.0.1407)',
  244.             'Cache-Control': 'no-cache',
  245.             'Accept-Language': 'en-us' }
  246.         req = asynchttp.HTTPRequest.make_request(url, data = data, headers = headers, method = 'POST')
  247.         return req
  248.  
  249.     
  250.     def close(self):
  251.         log.info('Closing %r', self)
  252.         msn.MSNSocketBase.close(self)
  253.         del self._q[:]
  254.         if self._session_id is None:
  255.             self.on_close()
  256.         else:
  257.             self.send(msn.Message('OUT'))
  258.  
  259.     close = once.allow_once(close)
  260.     
  261.     def on_close(self):
  262.         log.info('on_close: %r', self)
  263.         self._closed = True
  264.         self._poller.stop()
  265.         self._on_response = Null
  266.         self._on_send_error = Null
  267.         self._session_id = None
  268.         self.gateway_ip = type(self).gateway_ip
  269.         del self._q[:]
  270.         self.pause()
  271.         msn.MSNSocketBase.on_close(self)
  272.  
  273.     _disconnect = close_when_done = close
  274.     
  275.     def __repr__(self):
  276.         return '<%s session_id=%r gateway_ip=%r>' % (type(self).__name__, self._session_id, self.gateway_ip)
  277.  
  278.  
  279.  
  280. def main():
  281.     scktype = MsnHttpSocket
  282.     sck = scktype()
  283.     args = sck.connect_args_for('NS', ('messenger.hotmail.com', 1863))
  284.     print args
  285.     sck.connect(*args)
  286.     sck.send(msn.Message('VER', 'MSNP8', 'CVR0'), trid = True)
  287.     app.toggle_crust()
  288.     app.MainLoop()
  289.  
  290. if __name__ == '__main__':
  291.     import digsbysite
  292.     import netextensions
  293.     from tests.testapp import testapp
  294.     logging.getLogger('events').setLevel(1)
  295.     app = testapp('.')
  296.     threadpool.ThreadPool(5)
  297.     main()
  298.  
  299.