Exemple #1
0
class App(QApplication):
    backendReady = pyqtSignal()

    def __init__(self, args):
        QApplication.__init__(self, args)

        self.data_path = self.setup_data_path()
        self.load_config()

        self.twitter = Twitter(self.config)
        self.load_state()

        self.twitter.accountCreated.connect(self.apply_proxy)

        self.aboutToQuit.connect(self._on_shutdown)

    def setup_data_path(self):
        data_path = path('~/.mutc').expand()
        if not data_path.exists():
            data_path.mkdir()
            config_filename = path(__file__).parent / "config.default.json"
            shutil.copy(config_filename, data_path / "config.json")

        return data_path

    def apply_proxy(self, account):
        account.proxy_host = self.proxy_host
        account.proxy_port = self.proxy_port

    def load_config(self):
        with open(self.data_path / 'config.json') as fd:
            self.config = json.load(fd)

        proxy = self.config["proxy"]

        if proxy["host"] and proxy["port"]:
            self.proxy_host = proxy["host"]
            self.proxy_port = proxy["port"]
        else:
            self.proxy_host, self.proxy_port = discover_proxy()

    def save_config(self):
        with open(self.data_path / 'config.json', 'w') as fd:
            json.dump(self.config, fd)

    def save_state(self):
        panels = [(s.subscription_type, s.account, s.args)
                    for s, _ in self.twitter.panel_model.panels]
        state = {
            "accounts": self.twitter.account_model.accounts,
            "accounts_selected": self.twitter.account_model.selected,
            "panels": panels,
        }
        import pprint
        pprint.pprint(state)
        with open(self.data_path / 'state.pickle', 'wb') as fd:
            pickle.dump(state, fd)

    def load_state(self):
        try:
            with open(self.data_path / 'state.pickle', 'rb') as fd:
                state = pickle.load(fd)
        except EOFError:
            Logger("app").warn("statefile corrupted")
            return
        except IOError:
            return

        for account in state["accounts"]:
            self.apply_proxy(account)
            self.twitter.add_account(account)

        self.twitter.account_model.selected = state["accounts_selected"]

        for subscription_type, account, args in state["panels"]:
            self.twitter.subscribe({
                "account": account,
                "type": subscription_type,
                "args": args,
            })

    def _on_shutdown(self):
        self.twitter.thread.running = False
        self.twitter.thread = False

        self.save_state()
        self.save_config()

    @pyqtSlot("QVariant")
    def open_url(self, url):
        return webbrowser.open_new_tab(url)