home *** CD-ROM | disk | FTP | other *** search
Wrap
# Source Generated with Decompyle++ # File: in.pyo (Python 2.6) from __future__ import with_statement import wx import cgui from cgui import LoginWindow, IsMainThread from traceback import print_exc DEFAULT_SPLASH_POS = (300, 300) from cPickle import dump, load import os.path as os import sys import path import syck import re import logging log = logging.getLogger('loginwindow') try: _ except: _ = lambda s: s SIGN_IN = _('&Sign In') RESDIR = 'res' if not True: pass USE_NEW_STORAGE = sys.DEV import datetime if datetime.date.today().timetuple()[1:3] == (3, 17): digsby_logo_filename = 'digsby_stpatricks.png' else: digsby_logo_filename = 'digsbybig.png' connection_errors = dict(auth = _('Authentication Error'), connlost = _('Connection Lost'), server = _('We are upgrading Digsby. Please try connecting again in a few minutes.'), client = _('Could not contact remote server. Check your network configuration.')) class DataProblems(object): BAD_USERNAME = _('Invalid Digsby Username') def GetUserTempDir(): import stdpaths if getattr(sys, 'is_portable', False): base_temp = stdpaths.temp / 'digsby' else: base_temp = stdpaths.userlocaldata pth = path.path(base_temp) / 'temp' if not pth.isdir(): os.makedirs(pth) return pth class SplashDiskStorage(object): info_default = { '': dict(username = '', password = '', save = False, autologin = False, pos = (200, 200)), None: dict() } last_default = '' def get_conf_dir(self): import stdpaths c_dir = stdpaths.userdata try: return c_dir finally: if not os.path.exists(c_dir): os.mkdir(c_dir) def get_splash_data_path(self): return None(os.path.join, self.get_conf_dir() % self.data_file_name if sys.REVISION == 'dev' else '') def crypt_pws(self, info, codec): for user in info: if 'password' in info[user]: if codec == 'encode': info[user]['password'] = self.simple_crypt(info[user]['password'].encode('utf8'), keymat = user.encode('utf8')) elif codec == 'decode': info[user]['password'] = self.simple_crypt(info[user]['password'], keymat = user.encode('utf8')).decode('utf8') else: raise AssertionError codec == 'encode' def simple_crypt(self, s, k = None, keymat = ''): raise NotImplementedError def save_to_disk(self, last, info): raise NotImplementedError def load_from_disk(self): raise NotImplementedError def can_write(self): fname = os.path.join(self.get_conf_dir(), '__test__') test_data = 'test' try: try: f = _[1] f.write(test_data) finally: pass try: f = _[2] if f.read() == test_data: return True finally: pass return False except Exception: return False finally: try: if os.path.exists(fname): os.remove(fname) except Exception: pass class NewSplashDiskStorage(SplashDiskStorage): data_file_name = 'logininfo%s.yaml' def __init__(self): SplashDiskStorage.__init__(self) self.fallback = OldSplashDiskStorage() def get_conf_dir(self): import stdpaths c_dir = stdpaths.userlocaldata try: return c_dir finally: if not os.path.exists(c_dir): os.makedirs(c_dir) def simple_crypt(self, s, k = None, keymat = ''): RC4 = RC4 import M2Crypto.RC4 if k is None: k = self._get_key(keymat) return RC4(k).update(s) def _get_key(self, keymat = ''): keys = getattr(self, '_keys', None) if keys is None: keys = self._keys = { } key = keys.get(keymat, None) if key is not None: return key sysident = sysident import sysident self._keys[keymat] = sysident(append = keymat) return self._keys[keymat] def load_from_disk(self): path = self.get_splash_data_path() try: try: f = _[1] all_info = syck.load(f) finally: pass info = all_info.get('users', self.info_default) last = all_info.get('last', self.last_default) self.crypt_pws(info, 'decode') except Exception: e = None print_exc() (last, info) = self.fallback.load_from_disk() oldpth = self.fallback.get_splash_data_path() if os.path.exists(oldpth): try: os.remove(oldpth) except Exception: print_exc() except: None<EXCEPTION MATCH>Exception None<EXCEPTION MATCH>Exception return (last, info) def save_to_disk(self, last, info): path = self.get_splash_data_path() self.crypt_pws(info, 'encode') for_yaml = { 'users': info, 'last': last } try: try: f = _[1] syck.dump(for_yaml, f) finally: pass except Exception: print_exc() self.crypt_pws(info, 'decode') return True class OldSplashDiskStorage(SplashDiskStorage): data_file_name = 'digsby%s.dat' def simple_crypt(self, s, k = None, keymat = ''): RC4 = RC4 import M2Crypto.RC4 if k is None: k = 'foo' return RC4(k).update(s) def load_from_disk(self): path = self.get_splash_data_path() last = self.last_default info = self.info_default try: if os.path.exists(path): try: f = _[1] last = load(f) info = load(f) finally: pass self.crypt_pws(info, 'decode') except Exception: e = None print_exc() return (last, info) def save_to_disk(self, last, info): path = self.get_splash_data_path() self.crypt_pws(info, 'encode') try: try: f = _[1] dump(last, f) dump(info, f) finally: pass except Exception: print_exc() self.crypt_pws(info, 'decode') return True class PortableSplashDiskStorage(OldSplashDiskStorage): pass def res(*a): return os.path.join(RESDIR, *a) def digsby_icon_filename(): return res('digsby.ico') _icon_bundle = None def icon_bundle(): global _icon_bundle if _icon_bundle is None: _icon_bundle = wx.IconBundleFromFile(digsby_icon_filename(), wx.BITMAP_TYPE_ANY) return _icon_bundle class LoginController(object): have_shown_updated = False def __init__(self, on_success = (lambda : pass), autologin_override = None): self.allow_autologin = sys.opts.autologin self.cancelling = False self.on_success = on_success if getattr(sys, 'is_portable', False): self._datastore = PortableSplashDiskStorage() elif USE_NEW_STORAGE: self._datastore = NewSplashDiskStorage() else: self._datastore = OldSplashDiskStorage() self._profile = sentinel (username, self.allinfo) = self._datastore.load_from_disk() position = self.allinfo.get('pos', DEFAULT_SPLASH_POS) login_bitmap = wx.Bitmap(res('digsbybig.png')) help_bitmap = wx.Bitmap(res('skins/default/help.png')) revision_string = ' '.join((lambda .0: for x in .0: str(x))((getattr(sys, 'REVISION', ''), getattr(sys, 'TAG', ''), getattr(sys, 'BRAND', '')))) show_languages = False self.window = LoginWindow(None, position, login_bitmap, help_bitmap, str(revision_string), show_languages) self.bind_events() try: self._set_frame_icon() except Exception: print_exc() cgui.FitInMonitors(self.window) try: info = self.allinfo[username] except KeyError: info = dict(username = self._get_window_username(), password = '', save = False, autologin = False, pos = DEFAULT_SPLASH_POS) try: status_message = self.allinfo[None]['status'] self.allinfo[None]['status'] = '' except KeyError: if None not in self.allinfo: self.allinfo[None] = dict(status = '') elif 'status' not in self.allinfo[None]: self.allinfo[None]['status'] = '' status_message = '' if not status_message: if not (self.have_shown_updated) and sys.opts.updated: status_message = _('Update Successful') LoginController.have_shown_updated = True self.set_status(status_message) self.apply_info(info) if not info['password']: autologin_override = False self._init_state(autologin_override) self.setup_languages() def setup_languages(self): choice = self.window.LanguageChoice if choice is None: return None languages = [ 'English', 'English (1337)'] choice.Frozen().__enter__() try: choice.Clear() for lang in languages: choice.Append(lang) choice.SetSelection(0) finally: pass def _should_show_register(self): if sys.opts.register: return True if not self._datastore.can_write(): return False return not bool(self.allinfo) def _set_frame_icon(self): wx.Log.SetActiveTarget(wx.LogStderr()) wx.Log.EnableLogging(False) self.window.SetIcons(icon_bundle()) wx.Log.EnableLogging(True) def ShowWindow(self): self.window.Show() self.window.Raise() def DestroyWindow(self): import digsbyprofile try: if digsbyprofile.profile and getattr(digsbyprofile.profile, 'connection', None) is not None: digsbyprofile.profile.connection.remove_observer(self.OnStatusChange, 'state') self.window.Hide() finally: self.window.Destroy() def bind_events(self): bind = self.window.Bind bind(wx.EVT_CHECKBOX, self.OnCheck) bind(wx.EVT_TEXT, self.OnText) bind(wx.EVT_BUTTON, self.OnButton, id = wx.ID_OK) bind(wx.EVT_BUTTON, self.OnHelpButton, id = LoginWindow.HELPBUTTON) bind(wx.EVT_HYPERLINK, self.OnPWLink, id = LoginWindow.FORGOTPASSWORD) bind(wx.EVT_HYPERLINK, show_conn_settings, id = LoginWindow.CONNSETTINGS) bind(wx.EVT_HYPERLINK, self.OnNoAcct, id = LoginWindow.NOACCOUNT) bind(wx.EVT_CLOSE, self.OnClose) bind(wx.EVT_CHOICE, self.OnLanguage, id = LoginWindow.LANGUAGE) def OnLanguage(self, e): print 'language:', e.String print 'n:', e.Int def _init_state(self, autologin_override): self.OnCheck(None) self.OnText(None) if self._should_autologin(autologin_override): def paint(): self.window.Refresh() self.window.Update() wx.CallAfter(paint) wx.CallAfter(self.signin) def _should_autologin(self, autologin_override): if not self.allow_autologin: return False if autologin_override is not None and not autologin_override: return False if (not self.window.GetAutoLogin() or autologin_override is not None) and not autologin_override: return False return True def disconnect_prof(self): import digsbyprofile as d if d.profile: call_later = call_later import AsyncoreThread call_later(d.profile.disconnect) if d.profile is self._profile: self.unwatch_profile(d.profile) def OnClose(self, evt): sys.util_allowed = True self.window.Hide() self.cleanup() wx.CallAfter(self.exit) def cleanup(self): try: self.disconnect_prof() self.save_info() except Exception: print_exc() def exit(self): try: self.DestroyWindow() except: print_exc() wx.GetApp().DigsbyCleanupAndQuit() def watch_profile(self, p): if self._profile is not sentinel: self.unwatch_profile(self._profile) self._profile = p def unwatch_profile(self, p = None): if p is None: p = self._profile if p is self._profile: self._profile = sentinel def OnButton(self, evt): self.signin() def signin(self): if 'digsbyprofile' not in sys.modules: sys.util_allowed = True self.set_status(_('Loading...')) self.window.EnableControls(False, SIGN_IN, False) self.window.Update() m2 = m2 import M2Crypto m2.rand_bytes(16) import digsbyprofile if digsbyprofile.profile and digsbyprofile.profile.is_connected: self.window.EnableControls(True, SIGN_IN, True) self.disconnect_prof() self.cancelling = True else: self.login() def login(self): (good_data, reason) = validate_data(self.get_info().values()[0]) if not good_data: self.set_status(reason) self.window.EnableControls(True, SIGN_IN, True) self.window.Update() return None self.set_status(_('Connecting...')) self.window.EnableControls(False, SIGN_IN) self.window.Update() self.save_info() info = self.allinfo[self._get_window_username()] def myfunc(): import digsby try: print 'calling cb' self.cancelling = False self.on_success(info) import digsbyprofile self.watch_profile(digsbyprofile.profile) except digsby.DigsbyLoginError: print 'login error' self.set_status(_('Login error!')) self.window.EnableControls(True, SIGN_IN, True) return None import digsbyprofile if digsbyprofile.profile and getattr(digsbyprofile.profile, 'connection', None) is not None: conn = digsbyprofile.profile.connection cb = self.OnStatusChange conn.add_observer(cb, 'state') wx.CallAfter(myfunc) def OnText(self, evt): self._ontextcount = getattr(self, '_ontextcount', 0) + 1 if getattr(self, '_in_on_text', False): return evt.Skip() self._in_on_text = True try: if evt is not None: evt.Skip() window = self.window if not hasattr(self, 'allinfo'): return None if evt and evt.Id == LoginWindow.USERNAME: if self._get_window_username() in self.allinfo: self.apply_info(self.allinfo[self._get_window_username()], set_username = False) else: window.SetPassword('') if self._get_window_username(): pass enabled = bool(window.GetPassword()) window.FindWindowById(wx.ID_OK).Enable(enabled) finally: self._in_on_text = False def OnCheck(self, evt): if not self.window.GetSaveInfo(): self.window.SetAutoLogin(False) if evt and evt.GetId() == LoginWindow.SAVEPASSWORD and evt.GetInt() and getattr(sys, 'is_portable', False): if not self.do_portable_security_warning(): self.window.SetAutoLogin(False) self.window.FindWindowById(LoginWindow.SAVEPASSWORD).Value = False self.save_info() return None if evt and evt.GetId() in (LoginWindow.SAVEPASSWORD, LoginWindow.AUTOLOGIN): self.save_info() def do_portable_security_warning(self): dlg = wx.MessageDialog(self.window, _('Your password will be saved on your portable device.\n\nAnyone with access to this device will be able to log into your Digsby account. Are you sure you want to save your password?'), _('Security Information'), wx.ICON_EXCLAMATION | wx.YES_NO) response = dlg.ShowModal() return response == wx.ID_YES def OnPWLink(self, evt): wx.LaunchDefaultBrowser('https://accounts.digsby.com/forgot_pw.php') def OnNoAcct(self, evt): show_register_page(self.window) def OnHelpButton(self, evt = None): wx.LaunchDefaultBrowser('http://wiki.digsby.com') def OnStatusChange(self, src, attr, old, new): wx.CallAfter(self.OnStatusChanged, src, attr, old, new) def OnStatusChanged(self, src, attr, old, new): if wx.IsDestroyed(self.window): print >>sys.stderr, 'Warning: splash screen is Destroyed but still getting notified.' return None if self.cancelling and new != src.Statuses.OFFLINE: src.disconnect() if new in (src.Statuses.CONNECTING, src.Statuses.AUTHENTICATING, src.Statuses.SYNC_PREFS, src.Statuses.AUTHORIZED): self.window.EnableControls(False, SIGN_IN, False) def f(): if self.cancelling or new == src.Statuses.OFFLINE: if self.cancelling: self.set_status('') else: self.set_status(src.offline_reason) self.window.EnableControls(True, SIGN_IN, True) else: self.window.EnableControls(False, SIGN_IN) self.set_status(new) wx.CallAfter(f) def set_status(self, label, window_title = None, do_conn_error = False): conn_fail_message = _('Failed to Connect') if not window_title: pass self.window.SetStatus(label, '') if label == _('Authentication Error') and not getattr(self, 'auth_error_fired', False): self.auth_error_fired = True wx.MessageBox(_('Please make sure you have entered your Digsby username and password correctly.\nIf you need an account or forgot your password, use the links on the login screen. '), _('Authentication Error')) if do_conn_error: if label == conn_fail_message and not getattr(self, 'connect_error_fired', False): self.connect_error_fired = True wx.MessageBox(_('Please check your Internet connection and make sure a firewall isn\'t blocking Digsby.\nIf you connect to the Internet through a proxy server,\nclick the "Connection Settings" link to set up the proxy.\nIf you are still unable to connect, email bugs@digsby.com for technical support.'), _('Failed to Connect')) def _get_window_username(self): return self.window.GetUsername().strip() def get_info(self): find = self.window.FindWindowById window = self.window username = self._get_window_username() info_dict = dict(username = username, password = window.GetPassword(), save = window.GetSaveInfo(), autologin = window.GetAutoLogin()) return { username: info_dict } def apply_info(self, info, set_username = True): w = self.window if set_username: w.SetUsername(info['username']) w.SetPassword(info['password']) w.SetSaveInfo(info['save']) w.SetAutoLogin(info['autologin']) def set_username(self, username): self.window.SetUsername(username) def set_password(self, password): self.window.SetPassword(password) def save_info(self): username = self._get_window_username() self.allinfo.update(self.get_info()) info = self.allinfo[username] password = info['password'] if not info['save']: info['password'] = '' self.allinfo['pos'] = tuple(self.window.Position) self._datastore.save_to_disk(username, self.allinfo) if not info['password']: info['password'] = password def proto_error(self, exc): import digsby msgbox = None if exc is None: message = _('Failed to Connect') else: try: raise exc except digsby.DigsbyLoginError: if exc.reason == 'auth': message = _('Authentication Error') elif exc.reason == 'connlost': message = _('Connection Lost') else: message = _('Failed to Connect') if exc.reason == 'server': msgbox = _('We are upgrading Digsby. Please try connecting again in a few minutes.') elif exc.reason == 'client': msgbox = _('Could not contact remote server. Check your network configuration.') except Exception: print_exc() message = _('Failed to Connect') self.set_status(message, do_conn_error = True) self.window.EnableControls(True, SIGN_IN, True) self.disconnect_prof() if msgbox is not None: wx.MessageBox(msgbox, message) def _ensure_proxy_setup(): import wx.webview as wx f = wx.Frame(None) wx.webview.WebView(f) f.Destroy() import main main.set_did_create_webview() def _register_frame(splash): REGISTER_TITLE = _('Register a Digsby Account') REGISTER_SIZE = (675, 421) f = wx.Frame(splash, size = REGISTER_SIZE, title = REGISTER_TITLE, style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER) | wx.STAY_ON_TOP) f.SetBackgroundColour(wx.Color(168, 145, 102)) def paint(e): TEXT = _('Loading...') dc = wx.PaintDC(f) r = f.ClientRect dc.Font = f.Font (w, h) = dc.GetTextExtent(TEXT) (x, y) = r.CenterPoint((w, h)) dc.Brush = wx.WHITE_BRUSH dc.Pen = wx.TRANSPARENT_PEN dc.DrawRoundedRectangle(x - 10, y - 10, w + 20, h + 20, 5) dc.DrawText(TEXT, x, y) f.Bind(wx.EVT_PAINT, paint) cgui.SetFrameIcon(f, wx.Image(res('skins/default/digsbybig.png'))) return f def show_register_page(splash): import wx REGISTER_URL = 'https://accounts.digsby.com/reg.php' if sys.BRAND is not None: REGISTER_URL = REGISTER_URL + '?code=' + sys.BRAND f = _register_frame(splash) f.CenterOnScreen() f.Show() f.Update() f.Sizer = wx.BoxSizer(wx.HORIZONTAL) _ensure_proxy_setup() UrlQuery = UrlQuery import util.net import wx.webview as wx class WebBrowser((wx.webview.WebView,)): def __init__(self, parent, url = (None,)): wx.webview.WebView.__init__(self, parent) if url is not None: self.LoadURL(url) browser = WebBrowser(f, url = REGISTER_URL) browser.SetPosition((-3000, -3000)) def on_nav(url): if url.startswith(REGISTER_URL): query = UrlQuery.parse(url)['query'] if query.get('done'): username = query.get('u') if username is not None: splash.FindWindowById(LoginWindow.USERNAME).Value = username def after(): splash.FindWindowById(LoginWindow.PASSWORD).SetFocus() splash.Raise() after = (wx.CallAfter,)(after) if query.get('s') == 'true': import hooks hooks.notify('digsby.browsersettings.set_homepage') hooks.notify('digsby.browsersettings.set_search') def on_load(e): if e.State == wx.webview.WEBVIEW_LOAD_DOC_COMPLETED: on_nav(e.URL) else: e.Skip() browser.Bind(wx.webview.EVT_WEBVIEW_LOAD, on_load) add_window_open_redirect = add_window_open_redirect import gui.browser.webkit.webkitwindow add_window_open_redirect(browser, blank_opens_browser = True) def later(): f.Sizer.Add(browser, 1, wx.EXPAND) f.Layout() wx.CallLater(500, later) def show_conn_settings(evt): sys.util_allowed = True ProxyDialog = ProxyDialog import gui.proxydialog import util p = ProxyDialog() def later(): try: p.ShowModal() except Exception: print_exc() else: import hooks hooks.notify('proxy.info_changed', util.GetProxyInfo()) finally: p.Destroy() wx.CallAfter(later) def validate_data(info): email_regex_string = '^(?:([a-zA-Z0-9_][a-zA-Z0-9_\\-\\.]*)(\\+[a-zA-Z0-9_\\-\\.]+)?@((?:[a-zA-Z0-9\\-_]+\\.?)*[a-zA-Z]{1,4}))$' if not re.match(email_regex_string, info['username'] + '@digsby.org'): log.error('Bad username: %r', info['username']) return (False, DataProblems.BAD_USERNAME) return (True, None)