Refactored SessionManager so it will use pubsub as a communication pattern between GUI and logic and adds mastodon auth

This commit is contained in:
Manuel Cortez 2022-02-24 12:25:45 -06:00
parent 9322241747
commit af4e72ee27
No known key found for this signature in database
GPG Key ID: 9E0735CA15EFE790
3 changed files with 92 additions and 61 deletions

View File

@ -1,7 +1,4 @@
# -*- coding: cp1252 -*- # -*- coding: cp1252 -*-
#from config_utils import Configuration, ConfigurationResetException
from __future__ import unicode_literals
from builtins import object
import config import config
import paths import paths
import os import os
@ -16,13 +13,6 @@ def setup():
manager = sessionManager() manager = sessionManager()
class sessionManager(object): class sessionManager(object):
# def __init__(self):
# FILE = "sessions.conf"
# SPEC = "app-configuration.defaults"
# try:
# self.main = Configuration(paths.config_path(FILE), paths.app_path(SPEC))
# except ConfigurationResetException:
# pass
def get_current_session(self): def get_current_session(self):
if self.is_valid(config.app["sessions"]["current_session"]): if self.is_valid(config.app["sessions"]["current_session"]):

View File

@ -1,42 +1,51 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" Module to perform session actions such as adddition, removal or display of the global settings dialogue. """
import shutil import shutil
import widgetUtils
import platform
import output
if platform.system() == "Windows":
from . import wxUI as view
from controller import settings
elif platform.system() == "Linux":
from . import gtkUI as view
import paths
import time import time
import os import os
import logging import logging
import widgetUtils
import sessions import sessions
from sessions.twitter import session import output
from . import manager import paths
import config_utils import config_utils
import config import config
from pubsub import pub
from tweepy.errors import TweepyException from tweepy.errors import TweepyException
from controller import settings
from sessions.twitter import session as TwitterSession
from sessions.mastodon import session as MastodonSession
from . import manager
from . import wxUI as view
log = logging.getLogger("sessionmanager.sessionManager") log = logging.getLogger("sessionmanager.sessionManager")
class sessionManagerController(object): class sessionManagerController(object):
def __init__(self, started=False): def __init__(self, started: bool = False):
""" Class constructor.
Creates the SessionManager class controller, responsible for the accounts within TWBlue. From this dialog, users can add/Remove accounts, or load the global settings dialog.
:param started: Indicates whether this object is being created during application startup (when no other controller has been instantiated) or not. It is important for us to know this, as we won't show the button to open global settings dialog if the application has been started. Users must choose the corresponding option in the menu bar.
:type started: bool
"""
super(sessionManagerController, self).__init__() super(sessionManagerController, self).__init__()
log.debug("Setting up the session manager.") log.debug("Setting up the session manager.")
self.started = started self.started = started
manager.setup() manager.setup()
self.view = view.sessionManagerWindow() self.view = view.sessionManagerWindow()
widgetUtils.connect_event(self.view.new, widgetUtils.BUTTON_PRESSED, self.manage_new_account) pub.subscribe(self.manage_new_account, "sessionmanager.new_account")
widgetUtils.connect_event(self.view.remove, widgetUtils.BUTTON_PRESSED, self.remove) pub.subscribe(self.remove_account, "sessionmanager.remove_account")
if self.started == False: if self.started == False:
widgetUtils.connect_event(self.view.configuration, widgetUtils.BUTTON_PRESSED, self.configuration) pub.subscribe(self.configuration, "sessionmanager.configuration")
else: else:
self.view.hide_configuration() self.view.hide_configuration()
# Store a temporary copy of new and removed sessions, so we will perform actions on them during call to on_ok.
self.new_sessions = {} self.new_sessions = {}
self.removed_sessions = [] self.removed_sessions = []
def fill_list(self): def fill_list(self):
""" Fills the session list with all valid sessions that could be found in config path. """
sessionsList = [] sessionsList = []
reserved_dirs = ["dicts"] reserved_dirs = ["dicts"]
log.debug("Filling the sessions list.") log.debug("Filling the sessions list.")
@ -55,10 +64,16 @@ class sessionManagerController(object):
output.speak("An exception was raised while attempting to clean malformed session data. See the error log for details. If this message persists, contact the developers.",True) output.speak("An exception was raised while attempting to clean malformed session data. See the error log for details. If this message persists, contact the developers.",True)
os.exception("Exception thrown while removing malformed session") os.exception("Exception thrown while removing malformed session")
continue continue
name = config_test["twitter"]["user_name"] if config_test.get("twitter") != None:
name = _("{account_name} (Twitter)").format(account_name=config_test["twitter"]["user_name"])
if config_test["twitter"]["user_key"] != "" and config_test["twitter"]["user_secret"] != "": if config_test["twitter"]["user_key"] != "" and config_test["twitter"]["user_secret"] != "":
sessionsList.append(name) sessionsList.append(name)
self.sessions.append(i) self.sessions.append(i)
elif config_test.get("mastodon") != None:
name = _("{account_name} (Mastodon)").format(account_name=config_test["mastodon"]["user_name"])
if config_test["mastodon"]["instance"] != "" and config_test["mastodon"]["access_token"] != "":
sessionsList.append(name)
self.sessions.append(i)
else: else:
try: try:
log.debug("Deleting session %s" % (i,)) log.debug("Deleting session %s" % (i,))
@ -93,33 +108,29 @@ class sessionManagerController(object):
def show_auth_error(self, user_name): def show_auth_error(self, user_name):
error = view.auth_error(user_name) error = view.auth_error(user_name)
def manage_new_account(self, *args, **kwargs): def manage_new_account(self, type):
if self.view.new_account_dialog() == widgetUtils.YES: # Generic settings for all account types.
location = (str(time.time())[-6:]) location = (str(time.time())[-6:])
log.debug("Creating session in the %s path" % (location,)) log.debug("Creating %s session in the %s path" % (type, location))
s = session.Session(location) if type == "twitter":
s = TwitterSession.Session(location)
elif type == "mastodon":
s = MastodonSession.Session(location)
manager.manager.add_session(location) manager.manager.add_session(location)
s.get_configuration() s.get_configuration()
# try:
s.authorise() s.authorise()
self.sessions.append(location) self.sessions.append(location)
self.view.add_new_session_to_list() self.view.add_new_session_to_list()
s.settings.write() s.settings.write()
# except:
# log.exception("Error authorising the session")
# self.view.show_unauthorised_error()
# return
def remove(self, *args, **kwargs): def remove_account(self, index):
if self.view.remove_account_dialog() == widgetUtils.YES: selected_account = self.sessions[index]
selected_account = self.sessions[self.view.get_selected()] self.view.remove_session(index)
self.view.remove_session(self.view.get_selected())
self.removed_sessions.append(selected_account) self.removed_sessions.append(selected_account)
self.sessions.remove(selected_account) self.sessions.remove(selected_account)
shutil.rmtree(path=os.path.join(paths.config_path(), selected_account), ignore_errors=True) shutil.rmtree(path=os.path.join(paths.config_path(), selected_account), ignore_errors=True)
def configuration(self):
def configuration(self, *args, **kwargs):
""" Opens the global settings dialogue.""" """ Opens the global settings dialogue."""
d = settings.globalSettingsController() d = settings.globalSettingsController()
if d.response == widgetUtils.OK: if d.response == widgetUtils.OK:

View File

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals """ Base GUI (Wx) class for the Session manager module."""
import wx import wx
from pubsub import pub
from multiplatform_widgets import widgets from multiplatform_widgets import widgets
import application
class sessionManagerWindow(wx.Dialog): class sessionManagerWindow(wx.Dialog):
""" Dialog that displays all session managing capabilities to users. """
def __init__(self): def __init__(self):
super(sessionManagerWindow, self).__init__(parent=None, title=_(u"Session manager"), size=wx.DefaultSize) super(sessionManagerWindow, self).__init__(parent=None, title=_(u"Session manager"), size=wx.DefaultSize)
panel = wx.Panel(self) panel = wx.Panel(self)
@ -16,8 +17,11 @@ class sessionManagerWindow(wx.Dialog):
listSizer.Add(self.list.list, 0, wx.ALL, 5) listSizer.Add(self.list.list, 0, wx.ALL, 5)
sizer.Add(listSizer, 0, wx.ALL, 5) sizer.Add(listSizer, 0, wx.ALL, 5)
self.new = wx.Button(panel, -1, _(u"New account"), size=wx.DefaultSize) self.new = wx.Button(panel, -1, _(u"New account"), size=wx.DefaultSize)
self.new.Bind(wx.EVT_BUTTON, self.on_new_account)
self.remove = wx.Button(panel, -1, _(u"Remove account")) self.remove = wx.Button(panel, -1, _(u"Remove account"))
self.remove.Bind(wx.EVT_BUTTON, self.on_remove)
self.configuration = wx.Button(panel, -1, _(u"Global Settings")) self.configuration = wx.Button(panel, -1, _(u"Global Settings"))
self.configuration.Bind(wx.EVT_BUTTON, self.on_configuration)
ok = wx.Button(panel, wx.ID_OK, size=wx.DefaultSize) ok = wx.Button(panel, wx.ID_OK, size=wx.DefaultSize)
ok.SetDefault() ok.SetDefault()
cancel = wx.Button(panel, wx.ID_CANCEL, size=wx.DefaultSize) cancel = wx.Button(panel, wx.ID_CANCEL, size=wx.DefaultSize)
@ -42,11 +46,29 @@ class sessionManagerWindow(wx.Dialog):
if self.list.get_count() == 0: if self.list.get_count() == 0:
wx.MessageDialog(None, _(u"You need to configure an account."), _(u"Account Error"), wx.ICON_ERROR).ShowModal() wx.MessageDialog(None, _(u"You need to configure an account."), _(u"Account Error"), wx.ICON_ERROR).ShowModal()
return return
self.controller.do_ok()
self.EndModal(wx.ID_OK) self.EndModal(wx.ID_OK)
def new_account_dialog(self): def on_new_account(self, *args, **kwargs):
return wx.MessageDialog(self, _(u"The request to authorize your Twitter account will be opened in your browser. You only need to do this once. Would you like to continue?"), _(u"Authorization"), wx.YES_NO).ShowModal() menu = wx.Menu()
twitter = menu.Append(wx.ID_ANY, _("Twitter"))
mastodon = menu.Append(wx.ID_ANY, _("Mastodon"))
menu.Bind(wx.EVT_MENU, self.on_new_twitter_account, twitter)
menu.Bind(wx.EVT_MENU, self.on_new_mastodon_account, mastodon)
self.PopupMenu(menu, self.new.GetPosition())
def on_new_mastodon_account(self, *args, **kwargs):
dlg = wx.MessageDialog(self, _("You will be prompted for your Mastodon data (instance URL, email address and password) so we can authorise TWBlue in your instance. Would you like to authorise your account now?"), _(u"Authorization"), wx.YES_NO)
response = dlg.ShowModal()
dlg.Destroy()
if response == wx.ID_YES:
pub.sendMessage("sessionmanager.new_account", type="mastodon")
def on_new_twitter_account(self, *args, **kwargs):
dlg = wx.MessageDialog(self, _(u"The request to authorize your Twitter account will be opened in your browser. You only need to do this once. Would you like to continue?"), _(u"Authorization"), wx.YES_NO)
response = dlg.ShowModal()
dlg.Destroy()
if response == wx.ID_YES:
pub.sendMessage("sessionmanager.new_account", type="twitter")
def add_new_session_to_list(self): def add_new_session_to_list(self):
total = self.list.get_count() total = self.list.get_count()
@ -61,8 +83,16 @@ class sessionManagerWindow(wx.Dialog):
def get_response(self): def get_response(self):
return self.ShowModal() return self.ShowModal()
def remove_account_dialog(self): def on_remove(self, *args, **kwargs):
return wx.MessageDialog(self, _(u"Do you really want to delete this account?"), _(u"Remove account"), wx.YES_NO).ShowModal() dlg = wx.MessageDialog(self, _(u"Do you really want to delete this account?"), _(u"Remove account"), wx.YES_NO)
response = dlg.ShowModal()
dlg.Destroy()
if response == wx.ID_YES:
selected = self.list.get_selected()
pub.sendMessage("sessionmanager.remove_account", index=selected)
def on_configuration(self, *args, **kwargs):
pub.sendMessage("sessionmanager.configuration")
def get_selected(self): def get_selected(self):
return self.list.get_selected() return self.list.get_selected()