def on_save(self, e): # Do some simple protocol dependent validation. c = get(self.account, 'connection', None) if c is not None: for updatee in get(c, 'needs_update', []): try: attr, fname = updatee f = getattr(c, fname) except: attr = updatee f = lambda _v: setattr(c, attr, _v) f(getattr(self, attr).Value) for attr, validator, message in getattr(self.protocolinfo, 'validators', []): if not validator(getattr(self, attr).Value): return wx.MessageBox(message, 'Account Information Error') if hasattr(self, 'register') and self.register.IsChecked(): self.save.Enabled = False info = self.info() log.info_s('adding account: %r', info) profile.register_account( on_success = lambda: wx.CallAfter(self.on_success_register), on_fail = lambda error: wx.CallAfter(self.on_fail_register, error), **info) else: self.EndModal(wx.ID_SAVE)
def on_save(self, e): # Do some simple protocol dependent validation. c = get(self.account, "connection", None) if c is not None: for updatee in get(c, "needs_update", []): try: attr, fname = updatee f = getattr(c, fname) except: attr = updatee f = lambda _v: setattr(c, attr, _v) f(getattr(self, attr).Value) for attr, validator, message in getattr(self.protocolinfo, "validators", []): if not validator(getattr(self, attr).Value): return wx.MessageBox(message, "Account Information Error") if hasattr(self, "register") and self.register.IsChecked(): self.save.Enabled = False info = self.info() log.info_s("adding account: %r", info) profile.register_account( on_success=lambda: wx.CallAfter(self.on_success_register), on_fail=lambda error: wx.CallAfter(self.on_fail_register, error), **info ) else: self.EndModal(wx.ID_SAVE)
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 set_filter(e): _t, _i = e.EventObject.Name.split("/") keylist = get(self.account, "%s_keys" % _t) _k = get(keylist, int(_i)) self.account.filters[_t][_k] = e.IsChecked() if _t == "alerts": self.account.notify(_t)
def __getattr__(self, attr): try: return observe.Observable.__getattribute__(self, attr) except AttributeError, e: try: v = get(get(self, 'Statuses'), attr) return v == self.state except Exception: raise e
def set_filter(e): _t,_i = e.EventObject.Name.split('/') keylist = get(self.account,'%s_keys' % _t) _k = get(keylist, int(_i)) self.account.filters[_t][_k] = e.IsChecked() if _t == 'alerts': self.account.notify(_t)
def service(self): num_or_str = get(self, '_btype', 1) num = get(dict(msn=1,mob=4,fed=32), num_or_str, num_or_str) if num == 32 and self.name.endswith('yahoo.com'): prot_name = 'yahoo' else: prot_name = self.protocol.name return prot_name
def on_error(self, e): import traceback log.error(traceback.format_exc()) title = get(e, 'header', 'Error:') msg = get(e, 'major', '%s: %s'%(type(e).__name__,str(e))) details = get(e, 'minor', '') close = (_('Close'), lambda: None) fire('error', title = title, msg = msg, details = details, sticky = True, popupid = Exception, buttons = (close,), update = 'replace')
def _handle_token_response(env, sectoks, xml, login_check=True, callback=None, url='https://login.live.com/RST.srf'): if type(xml) is not util.xml_tag.tag: t = util.xml_tag.tag(xml) else: t = xml if t.Fault: errmsg = 'SOAP Fault trying to authenticate. Here\'s the fault xml: %r' % t.Fault._to_xml( ) log.error(errmsg) callback.error(Exception(errmsg)) return tokens = {} RSTS = t.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse #assert len(RSTS) == len(sectoks) login_token = None for sectok, RST in zip(sectoks, RSTS): tokenref = RST.RequestedTokenReference sectok.received = RST tokens[sectok.domain] = sectok if (funcs.get(tokenref.KeyIdentifier, 'ValueType', None) == 'urn:passport:compact' and funcs.get(tokenref.Reference, 'URI', None) == ('#Compact%d' % sectok.number)): login_token = sectok if login_token is None: errmsg = 'Could not find binary secret in response. Heres the response: %r' % t._to_xml( ) log.error(errmsg) return callback.error(Exception(errmsg)) token = str(login_token.received.RequestedSecurityToken.BinarySecurityToken ).strip() secret = str(login_token.received.RequestedProofToken.BinarySecret).strip() callback.success(token, secret, tokens)
def set_message_object(self, messageobj, callback): media = getattr(messageobj, 'media', None) log.debug('set_message_object got this for (messageobj, media): %r', (messageobj, media)) if media is not None: # # fmt is # # %(title)s - %(artist)s # or maybe just # %(title)s # # args is a dictionary for splatting into fmt # fmt, args = funcs.get(media, 'format_string', ''), funcs.get(media, 'format_args', {}) if fmt and args: fmtstring, keys = transform_format_groups(fmt) values = [args[key] for key in keys] application = media.get('app', '') type = media.get('type', 'Music') enabled = '1' # ITunes\\0Music\\01\\0{0} - {1}\\0Crownless\\0Nightwish\\0Wishmaster\\0 array = '\\0'.join([application, type, enabled, fmtstring] + values + ['']) ''' * Application - This is the app you are using. Usually empty (iTunes and Winamp are the only ones known to be accepted) * Type - This is the type of PSM, either 'Music', 'Games' or 'Office' * Enabled - This is a boolean value (0/1) to enable/disable the Current Media setting * Format - A formatter string (you may be familiar with this syntax if you've used .NET); for example, "{0} - {1}" * First line - The first line (Matches {0} in the Format) * Second line - The second line (Matches {1} in the Format) * Third line - The third line (Matches {2} in the Format) ''' self.send_uux(mediainfo=array, callback=callback) else: log.debug( 'msn not sending CurrentMedia because no fmt or args. (fmt=%r, args=%r)', fmt, args) self.send_uux(message=messageobj.message, callback=callback) else: log.debug('msn not sending CurrentMedia because media is None') self.send_uux(messageobj.message, callback=callback)
def remove(self, acct): import services.service_provider as sp with sp.ServiceProviderContainer( self.profile).rebuilding() as container: log.info('removing account %r', acct) with acct.flagged(DELETING): if acct.connected and hasattr(acct, 'disable'): with traceguard: acct.disable() elif get(acct, 'enabled', False): acct.enabled = False removed = False for x in self._all_accounts.values(): try: x.accounts.remove(acct) except ValueError: continue else: break try: self.connected_accounts.remove(acct) except ValueError: #ok, so it wasn't in the list pass self.unwatch_account(acct) from gui import toast for id in getattr(acct, 'popupids', ()): toast.cancel_id(id) container.rebuild(self)
def remove(self, acct): import services.service_provider as sp with sp.ServiceProviderContainer(self.profile).rebuilding() as container: log.info('removing account %r', acct) with acct.flagged(DELETING): if acct.connected and hasattr(acct, 'disable'): with traceguard: acct.disable() elif get(acct, 'enabled', False): acct.enabled = False removed = False for x in self._all_accounts.values(): try: x.accounts.remove(acct) except ValueError: continue else: break try: self.connected_accounts.remove(acct) except ValueError: #ok, so it wasn't in the list pass self.unwatch_account(acct) from gui import toast for id in getattr(acct, 'popupids',()): toast.cancel_id(id) container.rebuild(self)
def openurl(self, name, userid=None): if get(self, 'sesskey', False) and pref('privacy.www_auto_signin', False): url = self.getURL(name, userid) else: url = 'http://www.myspace.com' self.launchbrowser(url)
def combined_feed(self): activities = self.activities[:] statuses = self.friend_status[:] entries = activities + statuses entries.sort(key = lambda x: funcs.get(x, 'updated_parsed', 0), reverse = True) return filter(self.should_show_entry, entries)
def on_dclick(self, e): key = e.GetText() from util.primitives.funcs import get mysentinel = Sentinel() #@UndefinedVariable defval = get(self.defaults, key, mysentinel) val = self.prefs.setdefault(key, defval) preftype = defval.__class__ if defval is not mysentinel else val.__class__ if issubclass(preftype, bool): val = not val elif isinstance(val, list): if is_all(val, (str, unicode))[0]: from gui.toolbox import edit_string_list ok, new_list = edit_string_list(self, val, 'Editing ' + key) if ok and new_list: val = new_list elif ok: val = defval elif is_all(val)[0]: from gui.toolbox import edit_list ok, new_list = edit_list(self, val, 'Editing ' + key) if ok and new_list: val = new_list elif ok: val = defval else: print is_all(val) raise AssertionError, key + \ ' is not a homogenous list :( tell Kevin to make this more gooder' if val == defval and defval is mysentinel: delpref(str(key)) return elif isinstance(defval, (str, unicode, int, float)) or defval is mysentinel: t = type(val) if defval is mysentinel else type(defval) print 'editing pref of type', t diag = wx.TextEntryDialog(self, key, 'Enter %s' % nice_type_names[t], str(val)) if diag.ShowModal() == wx.ID_OK: val = diag.GetValue() if t is bool: val = bool_from_string(val) if val != '': val = t(val) elif defval is not mysentinel: val = defval else: delpref(str(key)) return self.prefs[str(key)] = val self.on_filter_txt() self._did_change_pref = True
def set_message_object(self, messageobj, callback): media = getattr(messageobj, 'media', None) log.debug('set_message_object got this for (messageobj, media): %r', (messageobj, media)) if media is not None: # # fmt is # # %(title)s - %(artist)s # or maybe just # %(title)s # # args is a dictionary for splatting into fmt # fmt, args = funcs.get(media,'format_string',''), funcs.get(media, 'format_args', {}) if fmt and args: fmtstring, keys = transform_format_groups(fmt) values = [args[key] for key in keys] application = media.get('app', '') type = media.get('type', 'Music') enabled = '1' # ITunes\\0Music\\01\\0{0} - {1}\\0Crownless\\0Nightwish\\0Wishmaster\\0 array = '\\0'.join([application, type, enabled, fmtstring] + values + ['']) ''' * Application - This is the app you are using. Usually empty (iTunes and Winamp are the only ones known to be accepted) * Type - This is the type of PSM, either 'Music', 'Games' or 'Office' * Enabled - This is a boolean value (0/1) to enable/disable the Current Media setting * Format - A formatter string (you may be familiar with this syntax if you've used .NET); for example, "{0} - {1}" * First line - The first line (Matches {0} in the Format) * Second line - The second line (Matches {1} in the Format) * Third line - The third line (Matches {2} in the Format) ''' self.send_uux(mediainfo = array, callback = callback) else: log.debug('msn not sending CurrentMedia because no fmt or args. (fmt=%r, args=%r)', fmt, args) self.send_uux(message = messageobj.message, callback=callback) else: log.debug('msn not sending CurrentMedia because media is None') self.send_uux(messageobj.message, callback = callback)
def set_enabled(self, value): # the first time "enabled" is set, create a timer has_been_set = hasattr(self, '_enabled') if not has_been_set: self.change_reason(self.Reasons.NONE) if self.update_mixin_timer: info('%s creating a timer with update frequency %s', self,self.updatefreq) self.timer = RepeatTimer(int(self.updatefreq), self.update_now) self.timer.start(); self.timer.stop() if get(self, 'on_connect', None) is not None and self.update_now not in self.on_connect: self.on_connect += self.update_now # when enabled, start the timer. self._enabled = value if value: info('enabling timer for %s', self) if self.OFFLINE and getattr(self, '_needs_connect', True): self._needs_connect = False get(self, 'Connect', nothing)() if self.update_mixin_timer: self.timer.reset(int(self.updatefreq)) # when disabled, stop the timer. else: if has_been_set: if not self.OFFLINE: get(self, 'Disconnect',nothing)() self._needs_connect = True if self.update_mixin_timer: info('stopping timer for %s', self) self.timer.stop() get(self, 'on_disable', nothing)()
def on_error(self, e): import traceback log.error(traceback.format_exc()) title = get(e, 'header', 'Error:') msg = get(e, 'major', '%s: %s' % (type(e).__name__, str(e))) details = get(e, 'minor', '') close = (_('Close'), lambda: None) fire('error', title=title, msg=msg, details=details, sticky=True, popupid=Exception, buttons=(close, ), update='replace')
def combined_feed(self): activities = self.activities[:] statuses = self.friend_status[:] entries = activities + statuses entries.sort(key=lambda x: funcs.get(x, 'updated_parsed', 0), reverse=True) return filter(self.should_show_entry, entries)
def make_pretty_addr(d): addrkeys = ('street', 'city', 'state', 'zip', 'country') get = make_dgetter(d) def addytemplate(d): fields = [] for k in addrkeys: fields.append(get(k)) return 'http://maps.google.com/maps?q=' + (u' '.join(filter(None, fields)).encode('utf-8').encode('url')) country = get('country') zip = get('zip') state = get('state') city = get('city') street = get('street') res = [] add = lambda s: res.insert(0, s) if country: add(u'\n' + country) if zip: add(zip) if state: if zip: add(u', ') add(state) if city: if (state or zip): add(u', ') add(city) if street: if (city or state or zip): add(u'\n') add(street) if res: add([u'(', (addytemplate(d), u'map'), u')\n']) return res
def __contains__(self, buddy): bname = get(buddy, 'name', buddy) if bname in self.buddies: buddy = self.buddies[bname] else: buddy = self.buddies[bname] = self.protocol.buddies[bname] return buddy in self.room_list
def __init__(self, ns, to_invite=()): self.ns = ns # bind events to NS self.principals = [] self.to_invite = to_invite self.__chatbuddy = get(to_invite, 0, None) EventMixin.__init__(self)
def recv_rem(self, msg): log.debug('got rem') (l_id, ver, name), g_id = msg.args[:3], get(msg, 3, None) if g_id is not None: g_id = GroupId(g_id) list_flags = dict(FL=1, AL=2, BL=4, RL=8, PL=16)[l_id] self.event('contact_remove', name, l_id, g_id)
def on_dclick(self, e): key = e.GetText() from util.primitives.funcs import get mysentinel = Sentinel() #@UndefinedVariable defval = get(self.defaults, key, mysentinel) val = self.prefs.setdefault(key, defval) preftype = defval.__class__ if defval is not mysentinel else val.__class__ if issubclass(preftype, bool): val = not val elif isinstance(val, list): if is_all(val, (str, unicode))[0]: from gui.toolbox import edit_string_list ok, new_list = edit_string_list(self, val, 'Editing ' + key) if ok and new_list: val = new_list elif ok: val = defval elif is_all(val)[0]: from gui.toolbox import edit_list ok, new_list = edit_list(self, val, 'Editing ' + key) if ok and new_list: val = new_list elif ok: val = defval else: print is_all(val) raise AssertionError, key + \ ' is not a homogenous list :( tell Kevin to make this more gooder' if val == defval and defval is mysentinel: delpref(str(key)) return elif isinstance(defval, (str,unicode,int,float)) or defval is mysentinel: t = type(val) if defval is mysentinel else type(defval) print 'editing pref of type',t diag = wx.TextEntryDialog(self, key, 'Enter %s' % nice_type_names[t], str(val)) if diag.ShowModal() == wx.ID_OK: val = diag.GetValue() if t is bool: val = bool_from_string(val) if val != '': val = t(val) elif defval is not mysentinel: val = defval else: delpref(str(key)) return self.prefs[str(key)] = val self.on_filter_txt() self._did_change_pref = True
def _parse_iln_nln(self, msg): log.debug("got iln/nln") args = Super._parse_iln_nln(self, msg) iconinfo = msn.util.url_decode(get(msg.args, 4, "")) msnobj = None if "<" in iconinfo and ">" in iconinfo: try: msnobj = msn.MSNObject.parse(iconinfo) except Exception, e: log.error("Error parsing msn object (%r). here's data: %r", e, iconinfo)
def _handle_token_response(env, sectoks, xml, login_check = True, callback = None, url = 'https://login.live.com/RST.srf'): if type(xml) is not util.xml_tag.tag: t = util.xml_tag.tag(xml) else: t = xml if t.Fault: errmsg = 'SOAP Fault trying to authenticate. Here\'s the fault xml: %r' % t.Fault._to_xml() log.error(errmsg) callback.error(Exception(errmsg)) return tokens = {} RSTS = t.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse #assert len(RSTS) == len(sectoks) login_token = None for sectok, RST in zip(sectoks, RSTS): tokenref = RST.RequestedTokenReference sectok.received = RST tokens[sectok.domain] = sectok if (funcs.get(tokenref.KeyIdentifier,'ValueType',None) == 'urn:passport:compact' and funcs.get(tokenref.Reference, 'URI', None) == ('#Compact%d'% sectok.number)): login_token = sectok if login_token is None: errmsg = 'Could not find binary secret in response. Heres the response: %r' % t._to_xml() log.error(errmsg) return callback.error(Exception(errmsg)) token = str(login_token.received.RequestedSecurityToken.BinarySecurityToken).strip() secret = str(login_token.received.RequestedProofToken.BinarySecret).strip() callback.success(token, secret, tokens)
def __init__(self, parent, account=None, protocol_name=None): "Please do not call directly. See classmethods create_new and edit_account." # Editing an existing account if account is not None: self.new = False assert protocol_name is None protocolinfo = account.protocol_info() self.protocol_name = account.protocol title = "%s - %s Settings" % (account.name, protocolinfo.name) # Creating a new account if account is None: self.new = True protocolinfo = protocols[protocol_name] self.protocol_name = protocol_name title = "%s Account" % protocolinfo.name # What to call the username (screenname, username, Jabber ID, etc.) self.screenname_name = protocolinfo.username_desc wx.Dialog.__init__(self, parent, title=title, size=(400, 300)) self.account = account if account is not None else emptystringer(getattr(protocolinfo, "defaults", None)) self.new = account is None self.protocolinfo = protocolinfo # Set the account type icon from gui import skin self.SetFrameIcon(skin.get("serviceicons.%s" % self.protocol_name)) self.formtype = getattr(protocolinfo, "form", "default") self.info_callbacks = Delegate() if self.new: self._allaccts = [acctid(a.protocol, a.name) for a in profile.account_manager] self.construct(account is None) self.layout() # enable or disable the save button as necessary. self.check_warnings() self.Fit() # focus the first enabled text control. for c in self.Children: if isinstance(c, TextCtrl) and c.IsEnabled() and c.IsEditable(): if c is get(self, "password", None): c.SetSelection(-1, -1) # only makes sense to select all on a password field :) wx.CallAfter(c.SetFocus) break
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 recv_rem(self, msg): l_id = msg.args[0] try: c_id = ContactId(msg.args[1]) except ValueError: c_id = msg.args[1] # buddy name! g_id = get(msg.args, 2, None) if g_id is not None: g_id = GroupId(g_id) self.event("contact_remove", c_id, l_id, g_id)
def recv_rem(self, msg): l_id = msg.args[0] try: c_id = ContactId(msg.args[1]) except ValueError: c_id = msg.args[1] # buddy name! g_id = get(msg.args, 2, None) if g_id is not None: g_id = GroupId(g_id) self.event('contact_remove', c_id, l_id, g_id)
def _parse_iln_nln(self, msg): log.debug('got iln/nln') args = Super._parse_iln_nln(self, msg) iconinfo = msn.util.url_decode(get(msg.args, 4, '')) msnobj = None if '<' in iconinfo and '>' in iconinfo: try: msnobj = msn.MSNObject.parse(iconinfo) except Exception, e: log.error('Error parsing msn object (%r). here\'s data: %r', e, iconinfo)
def construct_social(self): types = ('alerts','feed', 'indicators') self.checks = {} if self.account.filters: from copy import deepcopy as copy self._origfilters = copy(self.account.filters) def set_filter(e): _t,_i = e.EventObject.Name.split('/') keylist = get(self.account,'%s_keys' % _t) _k = get(keylist, int(_i)) self.account.filters[_t][_k] = e.IsChecked() if _t == 'alerts': self.account.notify(_t) for typ in types: if getattr(self.protocolinfo, 'needs_%s' % typ, False): self.checks[typ] = [] for i, nicename in enumerate(self.protocolinfo[typ]): key = get(get(self.account,'%s_keys' % typ), i, None) if key is not None: val = self.account.filters[typ][key] else: val = True chk = wx.CheckBox(self, label=nicename, name='%s/%s' % (typ,i)) chk.Value = val if self.account: chk.Bind(wx.EVT_CHECKBOX, set_filter) self.checks[typ].append(chk)
def __init__(self, parent, account = None, protocol_name = None): "Please do not call directly. See classmethods create_new and edit_account." # Editing an existing account if account is not None: self.new = False assert protocol_name is None protocolinfo = account.protocol_info() self.protocol_name = account.protocol title = '%s - %s Settings' % (account.name, protocolinfo.name) # Creating a new account if account is None: self.new = True protocolinfo = protocols[protocol_name] self.protocol_name = protocol_name title = '%s Account' % protocolinfo.name # What to call the username (screenname, username, Jabber ID, etc.) self.screenname_name = protocolinfo.username_desc wx.Dialog.__init__(self, parent, title=title, size=(400,300)) self.account = account if account is not None else emptystringer(getattr(protocolinfo, 'defaults', None)) self.new = account is None self.protocolinfo = protocolinfo # Set the account type icon from gui import skin self.SetFrameIcon(skin.get('serviceicons.%s' % self.protocol_name)) self.formtype = getattr(protocolinfo, 'form', 'default') self.info_callbacks = Delegate() if self.new: self._allaccts = [acctid(a.protocol, a.name) for a in profile.account_manager] self.construct(account is None) self.layout() # enable or disable the save button as necessary. self.check_warnings() self.Fit() # focus the first enabled text control. for c in self.Children: if isinstance(c, TextCtrl) and c.IsEnabled() and c.IsEditable(): if c is get(self, 'password', None): c.SetSelection(-1, -1) # only makes sense to select all on a password field :) wx.CallAfter(c.SetFocus) break
def construct_social(self): types = ("alerts", "feed", "indicators") self.checks = {} if self.account.filters: from copy import deepcopy as copy self._origfilters = copy(self.account.filters) def set_filter(e): _t, _i = e.EventObject.Name.split("/") keylist = get(self.account, "%s_keys" % _t) _k = get(keylist, int(_i)) self.account.filters[_t][_k] = e.IsChecked() if _t == "alerts": self.account.notify(_t) for typ in types: if getattr(self.protocolinfo, "needs_%s" % typ, False): self.checks[typ] = [] for i, nicename in enumerate(self.protocolinfo[typ]): key = get(get(self.account, "%s_keys" % typ), i, None) if key is not None: val = self.account.filters[typ][key] else: val = True chk = wx.CheckBox(self, label=nicename, name="%s/%s" % (typ, i)) chk.Value = val if self.account: chk.Bind(wx.EVT_CHECKBOX, set_filter) self.checks[typ].append(chk)
def error(data): errcode, data = oscar.unpack((('err', 'H'),), data) from util.primitives.funcs import get errmsg = get(errcodes,errcode,'Unknown') tlv = None if data: tlv, data = oscar.unpack((('tlv', 'tlv'),), data) # ICQ (family x15) has an additional tlv if data: tlv2, data = oscar.unpack(('tlv', 'tlv'),data) assert not data if tlv and tlv.t == 8: (subcode,) = struct.unpack('!H', tlv.v) else: subcode = None return errcode, errmsg, subcode
def timeout_check(self): log.info('Checking server connection for %r', self) if self.state in (self.Statuses.OFFLINE, self.Statuses.ONLINE): log.info('%s is not currently checking', self) return True if get(self, 'conn', False): try: self.conn.noop() except: self.on_error() log.error('%s\'s server connection has failed', self) return False else: log.error('%s has no conn attribute', self) self.on_error() return False
def error(data): errcode, data = oscar.unpack((('err', 'H'), ), data) from util.primitives.funcs import get errmsg = get(errcodes, errcode, 'Unknown') tlv = None if data: tlv, data = oscar.unpack((('tlv', 'tlv'), ), data) # ICQ (family x15) has an additional tlv if data: tlv2, data = oscar.unpack(('tlv', 'tlv'), data) assert not data if tlv and tlv.t == 8: (subcode, ) = struct.unpack('!H', tlv.v) else: subcode = None return errcode, errmsg, subcode
def dgetter(key): ''' Returns a unicode string by getting the attribute/item 'key' from 'obj'. in debug mode will raise assertion errors if the returned value is not unicode. ''' val = get(obj, key, u'') # will getitem or getattr if not val: # To fix None-type objects val = u'' try: assert isinstance(val, unicode), (key, val, obj) except: print_exc() if not isinstance(val, unicode): return val.decode('fuzzy utf8') return val
def acct_del(self, accts): ''' Network account delete. ''' for acct in accts: for account in self: if acct.id == account.id: acct2 = account break else: acct2 = None if acct2 is not None: with self.accounts_flagged(NETWORK_FLAG): if get(acct2, 'enabled', False): acct2.enabled = False self.remove(acct2) self._all_acct_hash.pop(acct2.id, None) from gui import toast for id in getattr(acct2, 'popupids',()): toast.cancel_id(id)
def _remove_buddy(self, lid, buddy, group, callback=None): role = dict(F="Forward", P="Pending", A="Allow", R="Reverse", B="Block")[lid[0]] if group and role in ("Forward",): log.info("Removing %r (%r) from %r (%r)", buddy, buddy.id, group, getattr(group, "id", group)) self.ABGroupContactDelete(buddy.name, buddy.id, get(group, "id", group)) # return True # else: if buddy.contactsoap is not None: self.ABContactDelete(buddy) else: log.info("Not calling ABContactDelete because no contact soap was received for %r", buddy) if role in buddy.mships: self.DeleteMember(buddy, role) else: log.info("Not calling DeleteMember because %s not in %r's member roles", role, buddy) callback.success()
def acct_del(self, accts): ''' Network account delete. ''' for acct in accts: for account in self: if acct.id == account.id: acct2 = account break else: acct2 = None if acct2 is not None: with self.accounts_flagged(NETWORK_FLAG): if get(acct2, 'enabled', False): acct2.enabled = False self.remove(acct2) self._all_acct_hash.pop(acct2.id, None) from gui import toast for id in getattr(acct2, 'popupids', ()): toast.cancel_id(id)
def _remove_buddy(self, lid, buddy, group, callback=None): role = dict(F='Forward',P='Pending', A='Allow',R='Reverse',B='Block')[lid[0]] if group and role in ('Forward',): log.info('Removing %r (%r) from %r (%r)', buddy, buddy.id, group, getattr(group, 'id',group)) self.ABGroupContactDelete(buddy.name, buddy.id, get(group, 'id',group)) #return True # else: if buddy.contactsoap is not None: self.ABContactDelete(buddy) else: log.info('Not calling ABContactDelete because no contact soap was received for %r', buddy) if role in buddy.mships: self.DeleteMember(buddy, role) else: log.info('Not calling DeleteMember because %s not in %r\'s member roles', role, buddy) callback.success()
def acct_changed(self, *a, **k): if wx.IsDestroyed(self): return log.warning( 'pg_privacy is getting notified but is destroyed. FIX ME') try: val = int(self.acct.connection.allow_unknown_contacts) except: val = 0 self.check.SetValue(val) AcctPrivacyPanel.acct_changed(self, *a, **k) conn = get(self.acct, 'connection', None) if self.observing_privacy and not conn: self.observing_privacy = False elif not self.observing_privacy and conn: conn.add_observer(self.privacy_changed, 'allow_unknown_contacts') self.observing_privacy = True else: assert bool( self.observing_privacy) == bool(conn), (conn, self.observing_privacy)
def link_logging(self, src, key, *a, **k): n = 'logging' if not isinstance(key, basestring) or not key.startswith(n): return logname = key[len(n):] or None if logname is not None: logname = logname.strip('.') newlevel = try_this(lambda: int(get(src, key)), 0) logging.log(100, 'Setting %s to level %d', logname or 'root', newlevel) import main if not hasattr(main, 'full_loggers'): return # logging system not setup # don't bother modifying console handlers if we never setup any if not getattr(main, 'logging_to_stdout', False): return if not logname: logger = logging.getLogger('') s_handlers = [h for h in logger.handlers if (h.__class__ is console_handler_class) and h not in main.full_loggers] s_handlers[0].setLevel(newlevel) else: rootlogger = logging.getLogger('') root_handlers = [h for h in rootlogger.handlers if (h.__class__ is not console_handler_class) or h in main.full_loggers] handler = self.consolehandlers[newlevel] handler.setLevel(newlevel) from main import ConsoleFormatter formatter = ConsoleFormatter() handler.setFormatter(formatter) root_handlers.append(handler) new_logger = logging.getLogger(logname) new_logger.propagate = False new_logger.handlers[:] = root_handlers
def set_enabled(self, value): # the first time "enabled" is set, create a timer has_been_set = hasattr(self, '_enabled') if not has_been_set: self.change_reason(self.Reasons.NONE) if self.update_mixin_timer: info('%s creating a timer with update frequency %s', self, self.updatefreq) self.timer = RepeatTimer(int(self.updatefreq), self.update_now) self.timer.start() self.timer.stop() if get( self, 'on_connect', None ) is not None and self.update_now not in self.on_connect: self.on_connect += self.update_now # when enabled, start the timer. self._enabled = value if value: info('enabling timer for %s', self) if self.OFFLINE and getattr(self, '_needs_connect', True): self._needs_connect = False get(self, 'Connect', nothing)() if self.update_mixin_timer: self.timer.reset(int(self.updatefreq)) # when disabled, stop the timer. else: if has_been_set: if not self.OFFLINE: get(self, 'Disconnect', nothing)() self._needs_connect = True if self.update_mixin_timer: info('stopping timer for %s', self) self.timer.stop() get(self, 'on_disable', nothing)()
def get_enabled(self): return get(self, '_enabled', False)
def addytemplate(d): fields = [] for k in addrkeys: fields.append(get(k)) return 'http://maps.google.com/maps?q=' + (u' '.join(filter(None, fields)).encode('utf-8').encode('url'))
def from_net(cls, rfc822msg): ''' FN: Font Name. URL-encoded name of font. EF: Effects. B, I, U, S [bold, italic, underline, strikethru] CO: Color. BBGGRR format (FFFFFF is white, 000000 is black. etc.) CS: Charset (old pre-unicode windows stuff) PF: Pitch and family - for figuring out a font if it's not available RL: Right alignment. If 0, left-align. otherwise, right-align. ''' m = rfc822msg fmt = m.get('X-MMS-IM-Format', '') body = m.get_payload().decode('fuzzy utf-8') msg = cls(body) if fmt: if fmt.strip().endswith(";"): fmt = fmt.strip()[:-1] try: fmt = msn.util.mime_to_dict(fmt) except Exception, e: traceback.print_exc() return msg _g = lambda k: get(fmt, k, None) fontname = _g('FN') msg.fontname = None if fontname is None else fontname.decode('url').decode('utf-8') color = _g('CO') effects = _g('EF') charset = _g('CS') family = _g('PF') ralign = _g('RL') if color is not None: try: color = int(msn.util.bgr_to_rgb(color), 16) except ValueError: color = None else: r = (color & 0xFF0000) >> 16 g = (color & 0x00FF00) >> 8 b = (color & 0x0000FF) msg.color = (r,g,b) msg.r = r msg.g = g msg.b = b if charset is not None: msg.charset = int(charset,16) if family is not None: msg.family = int(family) if ralign is not None: msg.rightalign = bool(int(ralign)) if effects is not None: ef = lambda x: x in effects msg.bold = ef('B') msg.italic = ef('I') msg.underline = ef('U') msg.strike = ef('S') msg.effects = effects
def __getattr__(self, attr): if attr in ('id','data'): return get(self.contents, attr) else: return MSG.__getattr__(self,attr)
def on_offline_change(self, src, attr, old, new): accounts_debug('%s\'s %s changed from %s to %s', src, attr, old, new) assert attr in ('offline_reason', None) attr = 'offline_reason' if new is None: new = getattr(src, attr) Reasons = StateMixin.Reasons conditions = ( old == new, # no change...this function shouldn't have been called in the first place new == StateMixin.Reasons.NONE, # normal offline state, doesn't matter ) if any(conditions): return log.debug('%s offline reason: %r->%r', src, old, new) if getattr(Reasons, 'WILL_RECONNECT', None) in (new, old): # something we set - ignore for now # new means we set it lower down in this function, old means we're moving out of this state, which should # not be an error. log.debug('Skipping the rest because reason is WILL_RECONNECT') return if new == getattr(Reasons, 'BAD_PASSWORD', None) and src is self.profile: if not self.profile.has_authorized: log.debug( 'Wrong password for digsbyprofile - not going to reconnect' ) return else: new = None if src is self.profile and not self.profile.loaded: log.debug( 'DigsbyProfile has never connected, not reconnecting after %s state.', new) return if (is_im_account(src) or src is self.profile) and new not in ( Reasons.BAD_PASSWORD, Reasons.NO_MAILBOX, Reasons.OTHER_USER, Reasons.RATE_LIMIT, Reasons.SERVER_ERROR): maxerror = (pref('%s.max_error_tolerance' % src.protocol, False) or getattr(src, 'max_error_tolerance', False) or pref('login.max_error_tolerance', False) or 4) count = src.error_count src.error_count += 1 log.info( '%s\'s error_count is now %d.', src, src.error_count, ) if (self.reconnect or src is self.profile): #and count < maxerror: if src in self.reconnect_timers: src.error_count -= 1 # account is already scheduled for a reconnect return src.setnotifyif('offline_reason', Reasons.WILL_RECONNECT) # schedule/attempt reconnect reconnect_time = get((1, 10, 30, 300), count, 300) if src in self.accounts or src is self.profile: profile_on_return = False if src is self.profile: log.critical( 'Going to try to reconnect the digsbyprofile. This could get interesting...' ) reconnect_time, profile_on_return = self.get_profile_reconnect_time( ) def rct(): log.info('Reconnecting %s...', src) try: log.warning( 'src=%r...setting on_connect to change_state', src) if src is self.profile: def set_online(*a, **k): src.connection.setnotify( 'state', StateMixin.Statuses.ONLINE) src.on_connect = set_online if getattr(src, 'connection', None) is None: src._reconnect() else: log.error( 'There was already a connection for this account that was supposed to reconnect: %r', src) except Exception, e: log.critical( 'Error while trying to reconnect %s (error was: %r)', src, e) traceback.print_exc() x = self.reconnect_timers.pop(src, None) if x is not None: x.stop() log.info( 'Starting reconnect timer for %s. Will reconnect in %d seconds %r', src, reconnect_time, self.state_desc(src)) self.reconnect_timers[src] = rct_timer = call_later( reconnect_time, threaded(rct)) if profile_on_return: def reconnect_profile_now(*a, **k): rct_timer.done_at = 0 wakeup_timeout_thread() self.profile.OnReturnFromIdle += reconnect_profile_now return else: assert isinstance(src, UpdateMixin) # this is a social or email account -- it has its own timers and things # and will attempt the next update when appropriate return log.info('Error count too high, or reconnect disabled.')
def on_offline_change(self, src, attr, old, new): accounts_debug('%s\'s %s changed from %s to %s', src, attr, old, new) assert attr in ('offline_reason', None) attr = 'offline_reason' if new is None: new = getattr(src, attr) Reasons = StateMixin.Reasons conditions = (old == new, # no change...this function shouldn't have been called in the first place new == StateMixin.Reasons.NONE, # normal offline state, doesn't matter ) if any(conditions): return log.debug('%s offline reason: %r->%r', src, old, new) if getattr(Reasons, 'WILL_RECONNECT', None) in (new, old): # something we set - ignore for now # new means we set it lower down in this function, old means we're moving out of this state, which should # not be an error. log.debug('Skipping the rest because reason is WILL_RECONNECT') return if new == getattr(Reasons, 'BAD_PASSWORD', None) and src is self.profile: if not self.profile.has_authorized: log.debug('Wrong password for digsbyprofile - not going to reconnect') return else: new = None if src is self.profile and not self.profile.loaded: log.debug('DigsbyProfile has never connected, not reconnecting after %s state.', new) return if (is_im_account(src) or src is self.profile) and new not in (Reasons.BAD_PASSWORD, Reasons.NO_MAILBOX, Reasons.OTHER_USER, Reasons.RATE_LIMIT, Reasons.SERVER_ERROR): maxerror = (pref('%s.max_error_tolerance' % src.protocol, False) or getattr(src, 'max_error_tolerance', False) or pref('login.max_error_tolerance', False) or 4 ) count = src.error_count src.error_count += 1 log.info('%s\'s error_count is now %d.', src, src.error_count,) if (self.reconnect or src is self.profile): #and count < maxerror: if src in self.reconnect_timers: src.error_count -= 1 # account is already scheduled for a reconnect return src.setnotifyif('offline_reason', Reasons.WILL_RECONNECT) # schedule/attempt reconnect reconnect_time = get((1,10,30,300), count, 300) if src in self.accounts or src is self.profile: profile_on_return = False if src is self.profile: log.critical('Going to try to reconnect the digsbyprofile. This could get interesting...') reconnect_time, profile_on_return = self.get_profile_reconnect_time() def rct(): log.info('Reconnecting %s...', src) try: log.warning('src=%r...setting on_connect to change_state', src) if src is self.profile: def set_online(*a, **k): src.connection.setnotify('state', StateMixin.Statuses.ONLINE) src.on_connect = set_online if getattr(src, 'connection', None) is None: src._reconnect() else: log.error('There was already a connection for this account that was supposed to reconnect: %r', src) except Exception, e: log.critical('Error while trying to reconnect %s (error was: %r)', src, e) traceback.print_exc() x = self.reconnect_timers.pop(src,None) if x is not None: x.stop() log.info('Starting reconnect timer for %s. Will reconnect in %d seconds %r', src, reconnect_time, self.state_desc(src)) self.reconnect_timers[src] = rct_timer = call_later(reconnect_time, threaded(rct)) if profile_on_return: def reconnect_profile_now(*a, **k): rct_timer.done_at = 0 wakeup_timeout_thread() self.profile.OnReturnFromIdle += reconnect_profile_now return else: assert isinstance(src, UpdateMixin) # this is a social or email account -- it has its own timers and things # and will attempt the next update when appropriate return log.info('Error count too high, or reconnect disabled.')