mirror of
https://github.com/MCV-Software/TWBlue.git
synced 2026-03-06 17:37:33 +01:00
Avance
This commit is contained in:
9
srcantiguo/sessionmanager/__init__.py
Normal file
9
srcantiguo/sessionmanager/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" Module to manage sessions. It can create and configure all sessions.
|
||||
|
||||
Contents of this package:
|
||||
wxUI: The graphical user interface written in WX Python (for windows). The view.
|
||||
session_exceptions: Some useful exceptions when there is an error.
|
||||
manager: Handles multiple sessions, setting the configuration files and check if the session is valid. Part of the model.
|
||||
session: Creates a twitter session for an user. The other part of the model.
|
||||
"""
|
||||
34
srcantiguo/sessionmanager/manager.py
Normal file
34
srcantiguo/sessionmanager/manager.py
Normal file
@@ -0,0 +1,34 @@
|
||||
# -*- coding: cp1252 -*-
|
||||
""" Lightweigth module that saves session position across global config and performs validation of config files. """
|
||||
import os
|
||||
import logging
|
||||
import config
|
||||
import paths
|
||||
log = logging.getLogger("sessionmanager.manager")
|
||||
from sessions import session_exceptions
|
||||
|
||||
manager = None
|
||||
def setup():
|
||||
""" Creates the singleton instance used within TWBlue to access this object. """
|
||||
global manager
|
||||
if not manager:
|
||||
manager = sessionManager()
|
||||
|
||||
class sessionManager(object):
|
||||
|
||||
def get_current_session(self):
|
||||
""" Returns the currently focused session, if valid. """
|
||||
if self.is_valid(config.app["sessions"]["current_session"]):
|
||||
return config.app["sessions"]["current_session"]
|
||||
|
||||
def set_current_session(self, sessionID):
|
||||
config.app["sessions"]["current_session"] = sessionID
|
||||
config.app.write()
|
||||
|
||||
def is_valid(self, id):
|
||||
if not os.path.exists(os.path.join(paths.config_path(), id)):
|
||||
raise session_exceptions.NonExistentSessionError("That session does not exist.")
|
||||
config.app["sessions"]["current_session"] = ""
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
136
srcantiguo/sessionmanager/sessionManager.py
Normal file
136
srcantiguo/sessionmanager/sessionManager.py
Normal file
@@ -0,0 +1,136 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" Module to perform session actions such as addition, removal or display of the global settings dialogue. """
|
||||
import time
|
||||
import os
|
||||
import logging
|
||||
import shutil
|
||||
import widgetUtils
|
||||
import sessions
|
||||
import output
|
||||
import paths
|
||||
import config_utils
|
||||
import config
|
||||
import application
|
||||
from pubsub import pub
|
||||
from controller import settings
|
||||
from sessions.mastodon import session as MastodonSession
|
||||
from sessions.gotosocial import session as GotosocialSession
|
||||
from . import manager
|
||||
from . import wxUI as view
|
||||
|
||||
log = logging.getLogger("sessionmanager.sessionManager")
|
||||
|
||||
class sessionManagerController(object):
|
||||
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__()
|
||||
log.debug("Setting up the session manager.")
|
||||
self.started = started
|
||||
# Initialize the manager, responsible for storing session objects.
|
||||
manager.setup()
|
||||
self.view = view.sessionManagerWindow()
|
||||
pub.subscribe(self.manage_new_account, "sessionmanager.new_account")
|
||||
pub.subscribe(self.remove_account, "sessionmanager.remove_account")
|
||||
if self.started == False:
|
||||
pub.subscribe(self.configuration, "sessionmanager.configuration")
|
||||
else:
|
||||
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.removed_sessions = []
|
||||
|
||||
def fill_list(self):
|
||||
""" Fills the session list with all valid sessions that could be found in config path. """
|
||||
sessionsList = []
|
||||
reserved_dirs = ["dicts"]
|
||||
log.debug("Filling the sessions list.")
|
||||
self.sessions = []
|
||||
for i in os.listdir(paths.config_path()):
|
||||
if os.path.isdir(os.path.join(paths.config_path(), i)) and i not in reserved_dirs:
|
||||
log.debug("Adding session %s" % (i,))
|
||||
strconfig = "%s/session.conf" % (os.path.join(paths.config_path(), i))
|
||||
config_test = config_utils.load_config(strconfig)
|
||||
if len(config_test) == 0:
|
||||
try:
|
||||
log.debug("Deleting session %s" % (i,))
|
||||
shutil.rmtree(os.path.join(paths.config_path(), i))
|
||||
continue
|
||||
except:
|
||||
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")
|
||||
continue
|
||||
if config_test.get("mastodon") != None:
|
||||
name = _("{account_name}@{instance} (Mastodon)").format(account_name=config_test["mastodon"]["user_name"], instance=config_test["mastodon"]["instance"].replace("https://", ""))
|
||||
if config_test["mastodon"]["instance"] != "" and config_test["mastodon"]["access_token"] != "":
|
||||
sessionsList.append(name)
|
||||
self.sessions.append(dict(type=config_test["mastodon"].get("type", "mastodon"), id=i))
|
||||
else:
|
||||
try:
|
||||
log.debug("Deleting session %s" % (i,))
|
||||
shutil.rmtree(os.path.join(paths.config_path(), i))
|
||||
except:
|
||||
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")
|
||||
self.view.fill_list(sessionsList)
|
||||
|
||||
def show(self):
|
||||
""" Displays the session manager dialog. """
|
||||
if self.view.get_response() == widgetUtils.OK:
|
||||
self.do_ok()
|
||||
# else:
|
||||
self.view.destroy()
|
||||
|
||||
def do_ok(self):
|
||||
log.debug("Starting sessions...")
|
||||
for i in self.sessions:
|
||||
# Skip already created sessions. Useful when session manager controller is not created during startup.
|
||||
if sessions.sessions.get(i.get("id")) != None:
|
||||
continue
|
||||
# Create the session object based in session type.
|
||||
if i.get("type") == "mastodon":
|
||||
s = MastodonSession.Session(i.get("id"))
|
||||
elif i.get("type") == "gotosocial":
|
||||
s = GotosocialSession.Session(i.get("id"))
|
||||
s.get_configuration()
|
||||
if i.get("id") not in config.app["sessions"]["ignored_sessions"]:
|
||||
try:
|
||||
s.login()
|
||||
except Exception as e:
|
||||
log.exception("Exception during login on a TWBlue session.")
|
||||
continue
|
||||
sessions.sessions[i.get("id")] = s
|
||||
self.new_sessions[i.get("id")] = s
|
||||
# self.view.destroy()
|
||||
|
||||
def show_auth_error(self):
|
||||
error = view.auth_error()
|
||||
|
||||
def manage_new_account(self, type):
|
||||
# Generic settings for all account types.
|
||||
location = (str(time.time())[-6:])
|
||||
log.debug("Creating %s session in the %s path" % (type, location))
|
||||
if type == "mastodon":
|
||||
s = MastodonSession.Session(location)
|
||||
result = s.authorise()
|
||||
if result == True:
|
||||
self.sessions.append(dict(id=location, type=s.settings["mastodon"].get("type")))
|
||||
self.view.add_new_session_to_list()
|
||||
|
||||
def remove_account(self, index):
|
||||
selected_account = self.sessions[index]
|
||||
self.view.remove_session(index)
|
||||
self.removed_sessions.append(selected_account.get("id"))
|
||||
self.sessions.remove(selected_account)
|
||||
shutil.rmtree(path=os.path.join(paths.config_path(), selected_account.get("id")), ignore_errors=True)
|
||||
|
||||
def configuration(self):
|
||||
""" Opens the global settings dialogue."""
|
||||
d = settings.globalSettingsController()
|
||||
if d.response == widgetUtils.OK:
|
||||
d.save_configuration()
|
||||
99
srcantiguo/sessionmanager/wxUI.py
Normal file
99
srcantiguo/sessionmanager/wxUI.py
Normal file
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
""" Base GUI (Wx) class for the Session manager module."""
|
||||
import wx
|
||||
import application
|
||||
from pubsub import pub
|
||||
from multiplatform_widgets import widgets
|
||||
|
||||
class sessionManagerWindow(wx.Dialog):
|
||||
""" Dialog that displays all session managing capabilities to users. """
|
||||
def __init__(self):
|
||||
super(sessionManagerWindow, self).__init__(parent=None, title=_(u"Session manager"), size=wx.DefaultSize)
|
||||
panel = wx.Panel(self)
|
||||
sizer = wx.BoxSizer(wx.VERTICAL)
|
||||
label = wx.StaticText(panel, -1, _(u"Accounts list"), size=wx.DefaultSize)
|
||||
listSizer = wx.BoxSizer(wx.HORIZONTAL)
|
||||
self.list = widgets.list(panel, _(u"Account"), style=wx.LC_SINGLE_SEL|wx.LC_REPORT)
|
||||
listSizer.Add(label, 0, wx.ALL, 5)
|
||||
listSizer.Add(self.list.list, 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.Bind(wx.EVT_BUTTON, self.on_new_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.Bind(wx.EVT_BUTTON, self.on_configuration)
|
||||
ok = wx.Button(panel, wx.ID_OK, size=wx.DefaultSize)
|
||||
ok.SetDefault()
|
||||
cancel = wx.Button(panel, wx.ID_CANCEL, size=wx.DefaultSize)
|
||||
buttons = wx.BoxSizer(wx.HORIZONTAL)
|
||||
buttons.Add(self.new, 0, wx.ALL, 5)
|
||||
buttons.Add(self.configuration, 0, wx.ALL, 5)
|
||||
buttons.Add(ok, 0, wx.ALL, 5)
|
||||
buttons.Add(cancel, 0, wx.ALL, 5)
|
||||
sizer.Add(buttons, 0, wx.ALL, 5)
|
||||
panel.SetSizer(sizer)
|
||||
min = sizer.CalcMin()
|
||||
self.SetClientSize(min)
|
||||
|
||||
def fill_list(self, sessionsList):
|
||||
for i in sessionsList:
|
||||
self.list.insert_item(False, i)
|
||||
if self.list.get_count() > 0:
|
||||
self.list.select_item(0)
|
||||
self.list.list.SetSize(self.list.list.GetBestSize())
|
||||
|
||||
def ok(self, ev):
|
||||
if self.list.get_count() == 0:
|
||||
wx.MessageDialog(None, _(u"You need to configure an account."), _(u"Account Error"), wx.ICON_ERROR).ShowModal()
|
||||
return
|
||||
self.EndModal(wx.ID_OK)
|
||||
|
||||
def on_new_account(self, *args, **kwargs):
|
||||
menu = wx.Menu()
|
||||
mastodon = menu.Append(wx.ID_ANY, _("Mastodon"))
|
||||
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 add_new_session_to_list(self):
|
||||
total = self.list.get_count()
|
||||
name = _(u"Authorized account %d") % (total+1)
|
||||
self.list.insert_item(False, name)
|
||||
if self.list.get_count() == 1:
|
||||
self.list.select_item(0)
|
||||
|
||||
def show_unauthorised_error(self):
|
||||
wx.MessageDialog(None, _(u"Your access token is invalid or the authorization has failed. Please try again."), _(u"Invalid user token"), wx.ICON_ERROR).ShowModal()
|
||||
|
||||
def get_response(self):
|
||||
return self.ShowModal()
|
||||
|
||||
def on_remove(self, *args, **kwargs):
|
||||
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):
|
||||
return self.list.get_selected()
|
||||
|
||||
def remove_session(self, sessionID):
|
||||
self.list.remove_item(sessionID)
|
||||
|
||||
def hide_configuration(self):
|
||||
self.configuration.Hide()
|
||||
|
||||
def destroy(self):
|
||||
self.Destroy()
|
||||
Reference in New Issue
Block a user