From 0cfa89b389285a98a3a5a5c4eccf82dcec33f851 Mon Sep 17 00:00:00 2001 From: Manuel Cortez Date: Fri, 17 Aug 2018 05:12:49 -0500 Subject: [PATCH] Moved Twitter's session from sessionmanager to sessions.twitter --- src/controller/mainController.py | 2 +- src/sessionmanager/manager.py | 2 +- src/sessionmanager/sessionManager.py | 2 +- src/sessionmanager/session_exceptions.py | 9 -- src/sessionmanager/wxUI.py | 18 +-- .../twitter}/session.py | 123 ++---------------- src/sessions/twitter/wxUI.py | 17 +++ 7 files changed, 33 insertions(+), 140 deletions(-) delete mode 100644 src/sessionmanager/session_exceptions.py rename src/{sessionmanager => sessions/twitter}/session.py (79%) create mode 100644 src/sessions/twitter/wxUI.py diff --git a/src/controller/mainController.py b/src/controller/mainController.py index 16eb8c44..07d6ed54 100644 --- a/src/controller/mainController.py +++ b/src/controller/mainController.py @@ -23,7 +23,7 @@ from sessionmanager import manager, sessionManager import buffersController import messages -from sessionmanager import session as session_ +from sessions.twitter import session as session_ from pubsub import pub import sound import output diff --git a/src/sessionmanager/manager.py b/src/sessionmanager/manager.py index 0fd9b5d8..ffdc0e18 100644 --- a/src/sessionmanager/manager.py +++ b/src/sessionmanager/manager.py @@ -5,7 +5,7 @@ import paths import os import logging log = logging.getLogger("sessionmanager.manager") -import session_exceptions +from sessions import session_exceptions manager = None def setup(): diff --git a/src/sessionmanager/sessionManager.py b/src/sessionmanager/sessionManager.py index ea902490..6d273d8e 100644 --- a/src/sessionmanager/sessionManager.py +++ b/src/sessionmanager/sessionManager.py @@ -12,7 +12,7 @@ import paths import time import os import logging -import session +from sessions.twitter import session import manager import config_utils import config diff --git a/src/sessionmanager/session_exceptions.py b/src/sessionmanager/session_exceptions.py deleted file mode 100644 index fd7cfc79..00000000 --- a/src/sessionmanager/session_exceptions.py +++ /dev/null @@ -1,9 +0,0 @@ -# -*- coding: cp1252 -*- -import exceptions - -class InvalidSessionError(exceptions.Exception): pass -class NonExistentSessionError(exceptions.Exception): pass -class NotLoggedSessionError(exceptions.BaseException): pass -class NotConfiguredSessionError(exceptions.BaseException): pass -class RequireCredentialsSessionError(exceptions.BaseException): pass -class AlreadyAuthorisedError(exceptions.BaseException): pass \ No newline at end of file diff --git a/src/sessionmanager/wxUI.py b/src/sessionmanager/wxUI.py index a3fb3eaa..cdf4d1c5 100644 --- a/src/sessionmanager/wxUI.py +++ b/src/sessionmanager/wxUI.py @@ -2,6 +2,7 @@ import wx from multiplatform_widgets import widgets import application + class sessionManagerWindow(wx.Dialog): def __init__(self): super(sessionManagerWindow, self).__init__(parent=None, title=_(u"Session manager"), size=wx.DefaultSize) @@ -73,19 +74,4 @@ class sessionManagerWindow(wx.Dialog): self.configuration.Hide() def destroy(self): - self.Destroy() - -class authorisationDialog(wx.Dialog): - def __init__(self): - super(authorisationDialog, self).__init__(parent=None, title=_(u"Authorising account...")) - panel = wx.Panel(self) - sizer = wx.BoxSizer(wx.VERTICAL) - static = wx.StaticText(panel, wx.NewId(), _(u"Enter your PIN code here")) - self.text = wx.TextCtrl(panel, -1) - self.ok = wx.Button(panel, wx.ID_OK) - self.cancel = wx.Button(panel, wx.ID_CANCEL) - sizer.Add(self.text, 0, wx.ALL, 5) - sizer.Add(self.cancel, 0, wx.ALL, 5) - panel.SetSizer(sizer) - min = sizer.CalcMin() - self.SetClientSize(min) \ No newline at end of file + self.Destroy() \ No newline at end of file diff --git a/src/sessionmanager/session.py b/src/sessions/twitter/session.py similarity index 79% rename from src/sessionmanager/session.py rename to src/sessions/twitter/session.py index 0bfc7187..745452e9 100644 --- a/src/sessionmanager/session.py +++ b/src/sessions/twitter/session.py @@ -1,10 +1,7 @@ # -*- coding: utf-8 -*- -""" The main session object. Here are the twitter functions to interact with the "model" of TWBlue.""" import wx -import urllib2 import config from keys import keyring -import session_exceptions as Exceptions import paths import output import time @@ -12,8 +9,6 @@ import sound import logging from sessions.twitter import client, utils, compose from twython import TwythonError, TwythonRateLimitError, TwythonAuthError -import config_utils -import shelve import application import os from mysc.thread_utils import stream_threaded, call_threaded @@ -21,37 +16,13 @@ from pubsub import pub log = logging.getLogger("sessionmanager.session") from sessions.twitter.long_tweets import tweets, twishort from wxUI import authorisationDialog +from sessions import base sessions = {} -class Session(object): +class Session(base.baseSession): """ A session object where we will save configuration, the twitter object and a local storage for saving the items retrieved through the Twitter API methods""" - # Decorators. - - def _require_login(fn): - - """ Decorator for checking if the user is logged in(a twitter object has credentials) on twitter. - Some functions may need this to avoid making unneeded twitter API calls.""" - - def f(self, *args, **kwargs): - if self.logged == True: - fn(self, *args, **kwargs) - else: - raise Exceptions.NotLoggedSessionError("You are not logged in yet.") - return f - - def _require_configuration(fn): - - """ Check if the user has a configured session.""" - - def f(self, *args, **kwargs): - if self.settings != None: - fn(self, *args, **kwargs) - else: - raise Exceptions.NotConfiguredSessionError("Not configured.") - return f - def order_buffer(self, name, data, ignore_older=True): """ Put the new items in the local database. @@ -127,43 +98,17 @@ class Session(object): pub.sendMessage("sent-dms-updated", total=sent, account=self.db["user_name"]) return incoming - def __init__(self, session_id): + def __init__(self, *args, **kwargs): """ session_id (str): The name of the folder inside the config directory where the session is located.""" - super(Session, self).__init__() - self.session_id = session_id - self.logged = False - self.settings = None + super(Session, self).__init__(*args, **kwargs) self.twitter = client.twitter() - self.db={} self.reconnection_function_active = False self.counter = 0 self.lists = [] - @property - def is_logged(self): - return self.logged - - def get_configuration(self): - - """ Gets settings for a session.""" - - file_ = "%s/session.conf" % (self.session_id,) -# try: - log.debug("Creating config file %s" % (file_,)) - self.settings = config_utils.load_config(paths.config_path(file_), paths.app_path("Conf.defaults")) - self.init_sound() - self.deshelve() -# except: -# log.exception("The session configuration has failed.") -# self.settings = None - - def init_sound(self): - try: self.sound = sound.soundSystem(self.settings["sound"]) - except: pass - - @_require_configuration +# @_require_configuration def login(self, verify_credentials=True): """ Log into twitter using credentials from settings. @@ -183,7 +128,7 @@ class Session(object): self.logged = False raise Exceptions.RequireCredentialsSessionError - @_require_configuration +# @_require_configuration def authorise(self): """ Authorises a Twitter account. This function needs to be called for each new session, after self.get_configuration() and before self.login()""" @@ -262,7 +207,7 @@ class Session(object): tl["statuses"].reverse() return tl["statuses"] - @_require_login +# @_require_login def get_favourites_timeline(self, name, *args, **kwargs): """ Gets favourites for the authenticated user or a friend or follower. @@ -290,7 +235,7 @@ class Session(object): results.reverse() return results - @_require_login +# @_require_login def get_user_info(self): """ Retrieves some information required by TWBlue for setup.""" @@ -311,21 +256,21 @@ class Session(object): self.get_muted_users() self.settings.write() - @_require_login +# @_require_login def get_lists(self): """ Gets the lists that the user is subscribed to and stores them in the database. Returns None.""" self.db["lists"] = self.twitter.twitter.show_lists(reverse=True) - @_require_login +# @_require_login def get_muted_users(self): """ Gets muted users (oh really?).""" self.db["muted_users"] = self.twitter.twitter.list_mute_ids()["ids"] - @_require_login +# @_require_login def get_stream(self, name, function, *args, **kwargs): """ Retrieves the items for a regular stream. @@ -386,52 +331,6 @@ class Session(object): self.reconnection_function_active = True self.reconnection_function_active = False - def shelve(self): - "Shelve the database to allow for persistance." - shelfname=paths.config_path(str(self.session_id)+"/cache.db") - if self.settings["general"]["persist_size"] == 0: - if os.path.exists(shelfname): - os.remove(shelfname) - return - try: - if not os.path.exists(shelfname): - output.speak("Generating database, this might take a while.",True) - shelf=shelve.open(paths.config_path(shelfname),'c') - for key,value in self.db.items(): - if type(key) != str and type(key) != unicode: - output.speak("Uh oh, while shelving the database, a key of type " + str(type(key)) + " has been found. It will be converted to type str, but this will cause all sorts of problems on deshelve. Please bring this to the attention of the " + application.name + " developers immediately. More information about the error will be written to the error log.",True) - log.error("Uh oh, " + str(key) + " is of type " + str(type(key)) + "!") - # Convert unicode objects to UTF-8 strings before shelve these objects. - if type(value) == list and self.settings["general"]["persist_size"] != -1 and len(value) > self.settings["general"]["persist_size"]: - shelf[str(key.encode("utf-8"))]=value[self.settings["general"]["persist_size"]:] - else: - shelf[str(key.encode("utf-8"))]=value - shelf.close() - except: - output.speak("An exception occurred while shelving the " + application.name + " database. It will be deleted and rebuilt automatically. If this error persists, send the error log to the " + application.name + " developers.",True) - log.exception("Exception while shelving" + shelfname) - os.remove(shelfname) - - def deshelve(self): - "Import a shelved database." - shelfname=paths.config_path(str(self.session_id)+"/cache.db") - if self.settings["general"]["persist_size"] == 0: - if os.path.exists(shelfname): - os.remove(shelfname) - return - try: - shelf=shelve.open(paths.config_path(shelfname),'c') - for key,value in shelf.items(): - self.db[key]=value - shelf.close() - except: - output.speak("An exception occurred while deshelving the " + application.name + " database. It will be deleted and rebuilt automatically. If this error persists, send the error log to the " + application.name + " developers.",True) - log.exception("Exception while deshelving" + shelfname) - try: - os.remove(shelfname) - except: - pass - def check_quoted_status(self, tweet): status = tweets.is_long(tweet) if status != False and config.app["app-settings"]["handle_longtweets"]: diff --git a/src/sessions/twitter/wxUI.py b/src/sessions/twitter/wxUI.py new file mode 100644 index 00000000..9ad4a782 --- /dev/null +++ b/src/sessions/twitter/wxUI.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +import wx + +class authorisationDialog(wx.Dialog): + def __init__(self): + super(authorisationDialog, self).__init__(parent=None, title=_(u"Authorising account...")) + panel = wx.Panel(self) + sizer = wx.BoxSizer(wx.VERTICAL) + static = wx.StaticText(panel, wx.NewId(), _(u"Enter your PIN code here")) + self.text = wx.TextCtrl(panel, -1) + self.ok = wx.Button(panel, wx.ID_OK) + self.cancel = wx.Button(panel, wx.ID_CANCEL) + sizer.Add(self.text, 0, wx.ALL, 5) + sizer.Add(self.cancel, 0, wx.ALL, 5) + panel.SetSizer(sizer) + min = sizer.CalcMin() + self.SetClientSize(min) \ No newline at end of file