def yahoo_v15_auth_success(crumb, yc, t, jar): y.cookies.update(Y=yc.split()[0][:-1], T=t.split()[0][:-1]) y.jar = jar crumbchallengehash = yahoo64(md5(crumb + challenge_str).digest()) log.info("logging on with initial status %s", y.initial_status) common.netcall( lambda: y.send( "authresp", y.initial_status, [ 1, user, 0, user, "ycookie", yc, "tcookie", t, "crumbchallengehash", crumbchallengehash, "mystery_login_num", "8388543", # str(0x3fffbf),#'4194239', "identity", user, "locale", "us", "version_str", "10.0.0.1270", ], ) )
def add_contact(self, name, account): if not isinstance(self.name, unicode): raise TypeError('DGroup.name must always be unicode') if not isinstance(name, basestring): raise TypeError('name must be a string: %s' % type(name)) from common import profile import hub x = (name, account.connection.service) if x in profile.blist.metacontacts.buddies_to_metas: id = list(profile.blist.metacontacts.buddies_to_metas[x])[0].id m = profile.blist.metacontacts[id] alias = m.alias group = list(m.groups)[0][-1] message = _('That buddy is already part of metacontact ' '"{alias}" in group "{group}."').format(alias=alias, group=group) hub.get_instance().user_message(message, _('Add Contact')) if account.connection: proto = account.connection def do_add(groupid): proto.add_contact(name, groupid) self.protocols.append(proto) self.ids.append(groupid) self.id_lookup[proto] = groupid if proto not in self.protocols: # the group doesn't exist yet netcall(lambda: proto.add_group(self.name, success=do_add)) else: # the group already exists. netcall(lambda: do_add(self.id_lookup[proto]))
def yahoo_v15_auth_success(crumb, yc, t, jar): y.cookies.update(Y=yc.split()[0][:-1], T=t.split()[0][:-1]) y.jar = jar crumbchallengehash = yahoo64(md5(crumb + challenge_str).digest()) log.info('logging on with initial status %s', y.initial_status) common.netcall(lambda: y.send( 'authresp', y.initial_status, [ 1, user, 0, user, 'ycookie', yc, 'tcookie', t, 'crumbchallengehash', crumbchallengehash, 'mystery_login_num', '8388543', #str(0x3fffbf),#'4194239', 'identity', user, 'locale', 'us', 'version_str', '10.0.0.1270' ]))
def on_url(self, invite_url, widget_id): 'Called back when VideoChatHttp successfully creates a new video widget token.' # Send an invite message. buddy = self.buddy_info.buddy() if buddy is not None: message = _('Join me in an audio/video call: %s') % invite_url def send_and_echo_invite(): convo = buddy.protocol.convo_for(buddy) convo.send_plaintext_message(message) convo.system_message( _('You have invited {name} to an audio/video chat.'). format(name=buddy.name)) netcall(send_and_echo_invite) # Show the video chat window. title = VIDEO_CHAT_TITLE.format(name=self.buddy_info.buddy_name) from gui.video.webvideo import VideoChatWindow frame = self.video_frame = VideoChatWindow(title, widget_id, on_close=self.stop) gui_call_later(frame.Show)
def add_contact(self, name, account): if not isinstance(self.name, unicode): raise TypeError('DGroup.name must always be unicode') if not isinstance(name, basestring): raise TypeError('name must be a string: %s' % type(name)) from common import profile import hub x = (name, account.connection.service) if x in profile.blist.metacontacts.buddies_to_metas: id = list(profile.blist.metacontacts.buddies_to_metas[x])[0].id m = profile.blist.metacontacts[id] alias = m.alias group = list(m.groups)[0][-1] message = _('That buddy is already part of metacontact ' '"{alias}" in group "{group}."').format(alias=alias, group=group) hub.get_instance().user_message(message, _('Add Contact')) if account.connection: proto = account.connection def do_add(groupid): proto.add_contact(name, groupid) self.protocols.append(proto) self.ids.append(groupid) self.id_lookup[proto] = groupid if proto not in self.protocols: # the group doesn't exist yet netcall(lambda: proto.add_group(self.name, success = do_add)) else: # the group already exists. netcall(lambda: do_add(self.id_lookup[proto]))
def stop(self): 'End all communication with the video widget.' self.stop = lambda *a: None # don't stop more than once self._stopped = True log.info('stopping video chat %r', self) # destroy the video window if self.video_frame: gui_call_later(self.video_frame.Destroy) # appear offline to the widget convo = self.widget_convo if convo is not None: netcall(self.widget_convo.buddy.appear_offline_to) # remove IM window link token = self.http.video_token if token is not None: conn = profile.connection if conn is not None: conn.remove_video_chat(token) # tell the server to kill the video info threaded(self.http.close_video)() self.on_stop()
def _on_response(self, request, response): if request.get_data(): log.debug_s('OUT : %r', request.get_data()) if self._session_id is None: self._poller.start() session_info = MIMEParse(response['x-msn-messenger']) self.gateway_ip = session_info.get('GW-IP', self.gateway_ip) self._session_id = self.fix_session_id(session_info.get('SessionID', None)) close = session_info.get('Session', '').lower() == 'close' if self._session_id is None and not close: raise Exception("Didn't get a session ID!") self._waiting = False if not close: common.netcall(self.process) if close: # this way if the socket is closed from within "_process_data" it won't be counted as "unexpected" self._session_id = None data = response.body self._process_data(data) if close: self.on_close()
def gui_thread(st=acctstatus): from common import profile if profile and profile.prefs: from gui.uberwidgets.formattedinput import get_default_format st = st.copy(editable=None) st.format = get_default_format() netcall(lambda: self.set_message_object(st))
def start(self): url = 'http://stream.twitter.com/1/statuses/filter.json' req = asynchttp.HTTPRequest.make_request(url, data=self.post_data, method='POST', accumulate_body=False) req.bind_event('on_chunk', self._on_chunk) log.info('starting twitter stream, following %d people', len(self.follow_ids)) netcall(lambda: self.httpmaster.request(req))
def _set_stream(self, stream): new = stream if new is None: old = self.stream if old is not None: netcall(old.close) for attr in ('process_stream_error', 'state_change', 'owner'): setattr(old, attr, Null) self._stream = new
def _connect_socket(self,sock,to=None): """Initialize stream on outgoing connection. :Parameters: - `sock`: connected socket for the stream - `to`: name of the remote host """ logging.getLogger("ThreadStream").debug("connecting") netcall(lambda: LegacyClientStream._connect_socket(self, sock, to))
def _connect_socket(self, sock, to=None): """Initialize stream on outgoing connection. :Parameters: - `sock`: connected socket for the stream - `to`: name of the remote host """ logging.getLogger("ThreadStream").debug("connecting") netcall(lambda: LegacyClientStream._connect_socket(self, sock, to))
def send_message(self, message, *args, **kwargs): # allow plugins to modify the message import hooks message = hooks.reduce('digsby.im.msg.send', message) echonow = pref('messaging.echo_immediately', type=bool, default=True) # Call Protocol Conversation's send message. def error(e=None): log.info('Error sending message: %r', message.format_as('plaintext')) log.info('Message error callback received %r: %r', type(e), e) if self.just_had_error: return emsg = getattr(e, 'error_message', '') if emsg: self.system_message(emsg, content_type = 'text/plain') else: self.system_message(_("Some of the messages you sent may not have been received."), content_type = 'text/plain') self.just_had_error = True def message_sent(): self.just_had_error = False def echo_message(msg=None): echomsg = msg or message if kwargs.get('auto', False): #echomsg = AUTORESP.format(message = echomsg) if 'has_autotext' not in kwargs: kwargs.update(has_autotext = True) self.sent_message(echomsg, **kwargs) if echonow: def success(msg=None): message_sent() echo_message() else: def success(msg=None): message_sent() echo_message(msg) conn = profile.connection if conn is not None: conn.send_message_intercept(self.buddy, message.format_as('plaintext')) netcall(lambda: self._send_message(message, success=success, error=error, *args, **kwargs)) if not self.ischat: # If this is a normal one-on-one chat, record an entry in the # "to-from" list b = self.buddy if b is not None and b is not self.protocol.self_buddy: profile.blist.add_tofrom('im', b, self.protocol)
def _on_timer(self, timer_name): t = getattr(self, timer_name, None) if t is not None: t.stop() if timer_name == 'network_timer': log.info('timer fired. saving buddylist blob...') netcall(lambda: profile.save('buddylist')) elif timer_name == 'tofrom_timer': log.info('local timer fired. saving tofrom to disk') wx.CallAfter(self.save_local_data) else: assert False, 'invalid timer name'
def finish_init(self, did_login, callback, *a): my_account = common.profile.find_account(self.username, self.protocol) api=uid=None with FacebookLogin(my_account) as fl: self.api = api = fl.loginmanager.digsby self.uid = uid = fl.loginmanager.digsby.uid if did_login: self.access_token = self.api.access_token acct = common.profile.find_account(self.username, self.protocol) if acct is not None: acct.uid = self.api.uid acct.access_token = self.api.access_token acct.update() self.jid = JID(UID_PREPEND + str(self.api.uid), 'chat.facebook.com', 'Digsby') common.netcall(lambda: super(FaceBookChatXMPP, self).Connect(*a, callback=callback))
def finish_init(self, did_login, callback, *a): my_account = common.profile.find_account(self.username, self.protocol) api = uid = None with FacebookLogin(my_account) as fl: self.api = api = fl.loginmanager.digsby self.uid = uid = fl.loginmanager.digsby.uid if did_login: self.access_token = self.api.access_token acct = common.profile.find_account(self.username, self.protocol) if acct is not None: acct.uid = self.api.uid acct.access_token = self.api.access_token acct.update() self.jid = JID(UID_PREPEND + str(self.api.uid), 'chat.facebook.com', 'Digsby') common.netcall(lambda: super(FaceBookChatXMPP, self).Connect( *a, callback=callback))
def move_buddy_creating_group(self, contact, groupname, fromgroupname, index = 0, callback = None): def do_move(): self.move_buddy(contact, groupname, fromgroupname, index, callback = callback) group = self.get_group(groupname) if group is None: self.add_group(groupname, success = lambda newgroup,*a,**k: netcall(do_move)) else: do_move()
def _rate_limited_icon_get(buddy): ''' May call buddy.protocol.get_buddyicon, if enough time has passed since the last call. Stores "last time" on the buddy. ''' last_get = getattr(buddy, '_last_icon_get', 0) now = time() # limit buddy icon requests if now - last_get > ICON_REQUEST_LIMIT_SECS: buddy._last_icon_get = now # log a warning if we've gotten this buddy's icon a lot buddy._icon_requests += 1 if buddy._icon_requests > ICON_REQUEST_WARNING_LIMIT: log.warning("asking for %r's buddy icon too often", buddy) buddy._icon_requests = 0 netcall(lambda: buddy.protocol.get_buddy_icon(buddy.name))
def on_url(self, invite_url, widget_id): 'Called back when VideoChatHttp successfully creates a new video widget token.' # Send an invite message. buddy = self.buddy_info.buddy() if buddy is not None: message = _('Join me in an audio/video call: %s') % invite_url def send_and_echo_invite(): convo = buddy.protocol.convo_for(buddy) convo.send_plaintext_message(message) convo.system_message(_('You have invited {name} to an audio/video chat.').format(name=buddy.name)) netcall(send_and_echo_invite) # Show the video chat window. title = VIDEO_CHAT_TITLE.format(name=self.buddy_info.buddy_name) from gui.video.webvideo import VideoChatWindow frame = self.video_frame = VideoChatWindow(title, widget_id, on_close = self.stop) gui_call_later(frame.Show)
def connect(self, register = False): """Connect to the server and set up the stream. Set `self.stream` and notify `self.state_changed` when connection succeeds.""" if not self.jid: raise ClientError, "Cannot connect: no or bad JID given" self.lock.acquire() try: stream = self.stream self.stream = None if stream: import common common.netcall(stream.close) self.__logger.debug("Creating client stream: %r, auth_methods=%r" % (self.stream_class, self.auth_methods)) stream=self.stream_class(jid = self.jid, password = self.password, server = self.server, port = self.port, auth_methods = self.auth_methods, tls_settings = self.tls_settings, keepalive = self.keepalive, owner = self) stream.process_stream_error = self.stream_error self.stream_created(stream) stream.state_change = self.__stream_state_change stream.connect() self.stream = stream self.state_changed.notify() self.state_changed.release() except: self.stream = None self.state_changed.release() raise
def set_formatted_profile(self, protocol, fstr=None): if fstr is None: fstr = self.profile # $$plugin setprofile import plugin_manager.plugin_hub as plugin_hub if not plugin_hub.act('digsby.im.setprofile.pre', protocol, fstr): return plugin_hub.act('digsby.im.setprofile.async', protocol, fstr) add_promo_string = self.prefs.get('profile.promote', True) if fstr.bestFormat == "rtf": if add_promo_string: fstr = fstr + PROMOTE_STRING_RTF format = None else: #legacy profile support if add_promo_string: fstr = fstr.format_as("plaintext").encode('xml') + PROMOTE_STRING_HTML from gui.uberwidgets.formattedinput import get_default_format format = get_default_format('profile.formatting') netcall(lambda: protocol.set_profile(fstr, format))
def add_item(self, _str): netcall(lambda: self.protocol.add_to_allow( _str, success=lambda *a, **k: wx.CallAfter(lambda: MSNListEditor. add_item(self, _str))))
def cb(item): from common import netcall netcall(lambda: getattr(self, name)(item.email))
def send(self, msgobj, trid=sentinel, callback=None, **kw): self._q.append((msgobj, trid, callback, kw)) if not self._paused: common.netcall(self.process)
def lose(e): netcall(callback.error)
def update_now(self): 'Invoked by the GUI.' netcall(self.update) self.timer.reset(self.updatefreq)
def later(): netcall(foo) import wx
def remove_contact(self, buddy, callback=None): if buddy.protocol in self.protocols: netcall( lambda: buddy.protocol.remove_buddy(buddy, callback=callback))
def send_im(self, message): 'Sends an unechoed IM to the video widget.' convo = self.widget_convo if convo is not None: netcall(lambda: convo.send_plaintext_message(message))
root.extend(newlist) # remove "duplicate" contacts--that is, contacts with the same on the same # protocol that appear under different accounts. If functionality in the # right click menu is required, we'll have to make some kind of "DContact" # with multiple protocols. unique = set() for con in is_group[False]: chash = con.info_key if chash not in unique: unique.add(chash) root.append(con) return root def remove_group(profile, group_name, force = False): group_name = group_name.lower() # Remove all metacontacts in this group. profile.blist.metacontacts.remove_group(group_name) def network(accts): for acct in accts: try: acct.connection.remove_group(group_name) except Exception, e: print_exc() netcall(lambda: network(profile.connected_accounts))
def Disconnect(self): netcall(self._Disconnect)
root.extend(newlist) # remove "duplicate" contacts--that is, contacts with the same on the same # protocol that appear under different accounts. If functionality in the # right click menu is required, we'll have to make some kind of "DContact" # with multiple protocols. unique = set() for con in is_group[False]: chash = con.info_key if chash not in unique: unique.add(chash) root.append(con) return root def remove_group(profile, group_name, force=False): group_name = group_name.lower() # Remove all metacontacts in this group. profile.blist.metacontacts.remove_group(group_name) def network(accts): for acct in accts: try: acct.connection.remove_group(group_name) except Exception, e: print_exc() netcall(lambda: network(profile.connected_accounts))
def remove_item(self, _str): netcall(lambda: self.protocol.rem_from_allow( _str, success=lambda *a, **k: wx.CallAfter(lambda: MSNListEditor. remove_item(self, _str))))
def fetch_favicon(domain, linked_domains=None): start_domain = domain real_domain = get_icon_domain(domain) if linked_domains is None: linked_domains = [] if real_domain != domain: linked_domains.append(domain) domain = real_domain wwwdomain = 'www.' + domain if not (domain.startswith('www') or wwwdomain in linked_domains): linked_domains.append(domain) domain = wwwdomain log.info('Using %r for %r (linked = %r)', domain, start_domain, linked_domains) url = 'http://' + domain + '/favicon.ico' def on_success(req, resp): data = resp.read() log.info('httpopen(%s): received %d bytes of data', url, len(data)) log.info('%r', resp) cache_icon(domain, linked_domains, data) unset_fetching([domain]) def on_error(req=None, resp=None): log.error('on_error for domain=%r, linked_domains=%r', domain, linked_domains) if 1 < domain.count('.') < MAX_SUBDOMAIN_CHECK: # try stripping a subdomain off and making another request new_domain = '.'.join(domain.split('.')[1:]) wx.CallAfter(fetch_favicon, new_domain, linked_domains + [domain]) # return now so that the original domain remains in the "fetching" # state. return else: log.error( 'No more subdomains to try for %r. Error response was: %r', domain, resp) cache_noicon(domain, linked_domains) unset_fetching(linked_domains + [domain]) def on_redirect(req): if 'favicon' not in req.get_selector(): new_url = 'http://%s/%s' % (req.get_host(), 'favicon.ico') old_req = req._orig_request checked_urls = getattr(old_req, '_favicons_checked_urls', set()) if new_url in checked_urls: return None checked_urls.add(new_url) req = req.copy(url=new_url) req._favicons_checked_urls = old_req._favicons_checked_urls = checked_urls req._orig_request = old_req return req with fetch_lock: if domain in currently_fetching: log.info('already fetching %r', url) return else: log.info('getting %r', url) currently_fetching.add(domain) netcall(lambda: asynchttp.httpopen( url, success=on_success, error=on_error, on_redirect=on_redirect))
def unpause(self): self._paused = False common.netcall(self.process)
def on_yes(): from common import netcall netcall(lambda: self.oscar.join_chat(cookie=chatcookie))
def auth(self): netcall(self.authenticate)
class ThreadStreamSocket(common.socket): ac_in_buffer_size = 4096 * 16 ac_out_buffer_size = 4096 * 16 def __init__(self, sock, collect, term, on_close, on_error, ssl=False): self.term = term self.tls = None if not ssl else sock self.collect_incoming_data = collect self.set_terminator(self.term) self.__logger = logging.getLogger("ThreadStreamSocket") self.on_close = on_close self.on_error = on_error self.killed = False self.lastbuffer = '' self.__want_write = False self.__want_read = False common.socket.__init__(self, sock) def found_terminator(self): self.set_terminator(self.term) def handle_error(self, e=None): import traceback traceback.print_exc() t, v = sys.exc_info()[:2] if t is not None: msg = get(get(v.args, 0, 'say what?'), 'message', '') if msg.startswith('bad write retry'): assert False self.__logger.error( 'Got that weird-ass "bad write retry" message in jabber socket' ) # return sslzero_closes = pref('jabber.ssl_error_zero.should_close', type=bool, default=True) if t is SSLError and get(v.args, 0, sentinel) == 0: self.__logger('SSL error 0!') if not sslzero_closes: self.__logger('\tnot closing') return self.__logger.debug('handle_error in %r', self) async_chat.close(self) if not self.killed: self.killed = True self.on_error() def handle_close(self): self.__logger.debug('handle_close in %r', self) async_chat.close(self) if not self.killed: self.killed = True self.on_close() @lock @callsback def make_tls(self, ctx, callback=None): self._realfileno = self._fileno self.socket.setblocking(True) self.del_channel() dbg = self.__logger.debug def blocking_connect(): try: dbg("Creating TLS connection") self.tls = SSL.Connection(ctx, self.socket) dbg("Setting up TLS connection") self.tls.setup_ssl() dbg("Setting TLS connect state") self.tls.set_connect_state() dbg("Starting TLS handshake") # self.tls.setblocking(True) self.tls.connect_ssl() self.socket.setblocking(False) self.tls.setblocking(False) self.ssocket = self.socket self.socket = self.tls except Exception, e: try: self.socket.close() self.tls.close() dbg('There was an exception in TLS blocking_connect: %r', e) except Exception: pass raise e def win(): self._fileno = self._realfileno self.add_channel() callback.success() def lose(e): netcall(callback.error) threaded(blocking_connect)(success=lambda: netcall(win), error=lose)
def later(): netcall(foo)
def remove_item(self, _str): netcall(lambda: self.protocol.rem_from_block( _str, success=lambda *a: (self.protocol.add_to_allow(_str), wx.CallAfter(lambda: MSNListEditor.remove_item(self, _str)))))
def remove_contact(self, buddy, callback = None): if buddy.protocol in self.protocols: netcall(lambda: buddy.protocol.remove_buddy(buddy, callback = callback))
def send_message(self, message, *args, **kwargs): # allow plugins to modify the message import hooks message = hooks.reduce('digsby.im.msg.send', message) echonow = pref('messaging.echo_immediately', type=bool, default=True) # Call Protocol Conversation's send message. def error(e=None): log.info('Error sending message: %r', message.format_as('plaintext')) log.info('Message error callback received %r: %r', type(e), e) if self.just_had_error: return emsg = getattr(e, 'error_message', '') if emsg: self.system_message(emsg, content_type='text/plain') else: self.system_message(_( "Some of the messages you sent may not have been received." ), content_type='text/plain') self.just_had_error = True def message_sent(): self.just_had_error = False def echo_message(msg=None): echomsg = msg or message if kwargs.get('auto', False): #echomsg = AUTORESP.format(message = echomsg) if 'has_autotext' not in kwargs: kwargs.update(has_autotext=True) self.sent_message(echomsg, **kwargs) if echonow: def success(msg=None): message_sent() echo_message() else: def success(msg=None): message_sent() echo_message(msg) conn = profile.connection if conn is not None: conn.send_message_intercept(self.buddy, message.format_as('plaintext')) netcall(lambda: self._send_message( message, success=success, error=error, *args, **kwargs)) if not self.ischat: # If this is a normal one-on-one chat, record an entry in the # "to-from" list b = self.buddy if b is not None and b is not self.protocol.self_buddy: profile.blist.add_tofrom('im', b, self.protocol)
def _on_status_timer(self): self.status_timer.stop() netcall(lambda: self.save('statuses'))
def Connect(self, invisible=False): if invisible: log.warning('Connect ignoring invisbile argument') netcall(lambda: self.socket.connect(self.server))
def fetch_favicon(domain, linked_domains = None): start_domain = domain real_domain = get_icon_domain(domain) if linked_domains is None: linked_domains = [] if real_domain != domain: linked_domains.append(domain) domain = real_domain wwwdomain = 'www.' + domain if not (domain.startswith('www') or wwwdomain in linked_domains): linked_domains.append(domain) domain = wwwdomain log.info('Using %r for %r (linked = %r)', domain, start_domain, linked_domains) url = 'http://' + domain + '/favicon.ico' def on_success(req, resp): data = resp.read() log.info('httpopen(%s): received %d bytes of data', url, len(data)) log.info('%r', resp) cache_icon(domain, linked_domains, data) unset_fetching([domain]) def on_error(req=None, resp=None): log.error('on_error for domain=%r, linked_domains=%r', domain, linked_domains) if 1 < domain.count('.') < MAX_SUBDOMAIN_CHECK: # try stripping a subdomain off and making another request new_domain = '.'.join(domain.split('.')[1:]) wx.CallAfter(fetch_favicon, new_domain, linked_domains + [domain]) # return now so that the original domain remains in the "fetching" # state. return else: log.error('No more subdomains to try for %r. Error response was: %r', domain, resp) cache_noicon(domain, linked_domains) unset_fetching(linked_domains + [domain]) def on_redirect(req): if 'favicon' not in req.get_selector(): new_url = 'http://%s/%s' % (req.get_host(), 'favicon.ico') old_req = req._orig_request checked_urls = getattr(old_req, '_favicons_checked_urls', set()) if new_url in checked_urls: return None checked_urls.add(new_url) req = req.copy(url = new_url) req._favicons_checked_urls = old_req._favicons_checked_urls = checked_urls req._orig_request = old_req return req with fetch_lock: if domain in currently_fetching: log.info('already fetching %r', url) return else: log.info('getting %r', url) currently_fetching.add(domain) netcall(lambda: asynchttp.httpopen(url, success = on_success, error = on_error, on_redirect = on_redirect))
def _on_pref_timer(self): self.pref_timer.stop() netcall(lambda: self.save('prefs'))