The next generation branch has been added

This commit is contained in:
2014-11-12 20:41:29 -06:00
parent 75f494fc5a
commit f54d9394b7
96 changed files with 2629 additions and 4517 deletions

View File

@@ -1 +1,9 @@
# -*- coding: cp1252 -*-
# -*- 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.
"""

View File

@@ -1,101 +0,0 @@
# -*- coding: utf-8 -*-
import time
import wx
import manager
import session_exceptions
import paths
import config
import sound
import languageHandler
import output
import os
import twitter
import webbrowser
from multiplatform_widgets import widgets
from config_utils import Configuration
class sessionManagerWindow(wx.Dialog):
def __init__(self):
super(sessionManagerWindow, self).__init__(parent=None, title=_(u"Session manager"), size=wx.DefaultSize)
# panelSizer = wx.BoxSizer(wx.VERTICAL)
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
label = wx.StaticText(panel, -1, _(u"Select a twitter account to start TW Blue"), size=wx.DefaultSize)
listSizer = wx.BoxSizer(wx.HORIZONTAL)
self.list = widgets.list(panel, _(u"Account"), style=wx.LC_SINGLE_SEL|wx.LC_REPORT)
self.fill_list()
listSizer.Add(label, 0, wx.ALL, 5)
listSizer.Add(self.list.list, 0, wx.ALL, 5)
sizer.Add(listSizer, 0, wx.ALL, 5)
new = wx.Button(panel, -1, _(u"New account"), size=wx.DefaultSize)
new.Bind(wx.EVT_BUTTON, self.new_account)
ok = wx.Button(panel, wx.ID_OK, size=wx.DefaultSize)
ok.SetDefault()
ok.Bind(wx.EVT_BUTTON, self.ok)
cancel = wx.Button(panel, wx.ID_CANCEL, size=wx.DefaultSize)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(new, 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)
# sizer.Layout()
# self.Fit()
# self.SetSize(panel.GetBestSize())
# panelSizer.Add(panel)
# self.SetSizerAndFit(sizer)
# sizer.Layout()
min = sizer.CalcMin()
self.SetClientSize(min)
def fill_list(self):
self.sessions = []
for i in os.listdir(paths.config_path()):
if os.path.isdir(paths.config_path(i)):
strconfig = "%s/session.conf" % (paths.config_path(i))
config_test = Configuration(strconfig)
name = config_test["twitter"]["user_name"]
if name != "" and config_test["twitter"]["user_key"] != "" and config_test["twitter"]["user_secret"] != "":
self.list.insert_item(False, name)
self.sessions.append(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
current_session = self.sessions[self.list.get_selected()]
manager.manager.set_current_session(current_session)
config.MAINFILE = "%s/session.conf" % (manager.manager.get_current_session())
config.setup()
lang=config.main['general']['language']
languageHandler.setLanguage(lang)
sound.setup()
output.setup()
# else:
# self.name = current_session
self.EndModal(wx.ID_OK)
def new_account(self, ev):
twitter_object = twitter.twitter.twitter()
dlg = wx.MessageDialog(self, _(u"The request for the required Twitter authorization to continue will be opened on your browser. You only need to do it once. Would you like to autorhise a new account now?"), _(u"Authorisation"), wx.YES_NO)
if dlg.ShowModal() == wx.ID_NO:
return
else:
location = (str(time.time())[:12])
manager.manager.add_session(location)
config.MAINFILE = "%s/session.conf" % (location,)
config.setup()
try:
twitter_object.authorise()
except:
wx.MessageDialog(None, _(u"Your access token is invalid or the authorisation has failed. Please try again."), _(u"Invalid user token"), wx.ICON_ERROR).ShowModal()
return
total = self.list.get_count()
name = _(u"Authorised account %d") % (total+1)
self.list.insert_item(False, name)
if self.list.get_count() == 1:
self.list.select_item(0)
self.sessions.append(location)

View File

@@ -1,5 +1,6 @@
# -*- coding: cp1252 -*-
from config_utils import Configuration, ConfigurationResetException
#from config_utils import Configuration, ConfigurationResetException
import config
import paths
import os
import session_exceptions
@@ -10,17 +11,17 @@ def setup():
manager = sessionManager()
class sessionManager(object):
def __init__(self):
FILE = "sessions.conf"
SPEC = "sessions.defaults"
try:
self.main = Configuration(paths.config_path(FILE), paths.app_path(SPEC))
except ConfigurationResetException:
pass
# 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):
if self.is_valid(self.main["sessions"]["current_session"]):
return self.main["sessions"]["current_session"]
if self.is_valid(config.app["sessions"]["current_session"]):
return config.app["sessions"]["current_session"]
else:
return False
@@ -28,16 +29,16 @@ class sessionManager(object):
path = paths.config_path(id)
if not os.path.exists(path):
os.mkdir(path)
self.main["sessions"]["sessions"].append(id)
config.app["sessions"]["sessions"].append(id)
def set_current_session(self, sessionID):
self.main["sessions"]["current_session"] = sessionID
self.main.write()
config.app["sessions"]["current_session"] = sessionID
config.app.write()
def is_valid(self, id):
if not os.path.exists(paths.config_path(id)):
raise session_exceptions.NonExistentSessionError("That session does not exist.")
self.main["sessions"]["current_session"] = ""
config.app["sessions"]["current_session"] = ""
return False
else:
return True

View File

@@ -0,0 +1,269 @@
# -*- coding: utf-8 -*-
""" The main session object. Here are the twitter functions to interact with the "model" of TWBlue."""
import twitter
import application
import db
import session_exceptions as Exceptions
import paths
import output
import time
import sound
from twitter import utils
from twython import TwythonError, TwythonRateLimitError, TwythonAuthError
from config_utils import Configuration, ConfigurationResetException
from mysc.thread_utils import call_threaded
sessions = {}
class Session(object):
""" 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 (a twitter object has credentials) on twitter.
Some functions may need this to avoid make 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 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):
""" Put the new items on the local database.
name str: The name for the buffer stored in the dictionary.
data list: A list with tweets.
returns the number of items that has been added in this execution"""
num = 0
if self.db.has_key(name) == False:
self.db[name] = []
for i in data:
if utils.find_item(i["id"], self.db[name]) == None:
if self.settings["general"]["reverse_timelines"] == False: self.db[name].append(i)
else: self.db[name].insert(0, i)
num = num+1
return num
def order_cursored_buffer(self, name, data):
""" Put the new items on the local database. Useful for cursored buffers (followers, friends, users of a list and searches)
name str: The name for the buffer stored in the dictionary.
data list: A list with items and some information about cursors.
returns the number of items that has been added in this execution"""
num = 0
if self.db.has_key(name) == False:
self.db[name] = {}
self.db[name]["items"] = []
# if len(self.db[name]["items"]) > 0:
for i in data:
if utils.find_item(i["id"], self.db[name]["items"]) == None:
if self.settings["general"]["reverse_timelines"] == False: self.db[name]["items"].append(i)
else: self.db[name]["items"].insert(0, i)
num = num+1
return num
def __init__(self, session_id):
""" 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
self.twitter = twitter.twitter.twitter()
self.db = {}
def get_configuration(self):
""" Gets settings for a session."""
file_ = "%s/session.conf" % (self.session_id,)
try:
self.settings = Configuration(paths.config_path(file_), paths.app_path("Conf.defaults"))
except:
self.settings = None
@_require_configuration
def login(self):
""" Login into twitter using credentials from settings.
if the user account isn't authorised, it needs to call self.authorise() before login."""
if self.settings["twitter"]["user_key"] != None and self.settings["twitter"]["user_secret"] != None:
self.twitter.login(self.settings["twitter"]["user_key"], self.settings["twitter"]["user_secret"])
self.logged = True
else:
self.logged = False
raise Exceptions.RequireCredentialsSessionError
@_require_configuration
def authorise(self):
""" Authorises a Twitter account. This function needs to be called for each new session, after of self.get_configuration() and before of self.login()"""
if self.logged == True:
raise Exceptions.AlreadyAuthorisedError("The authorisation process is not needed at this time.")
else:
self.twitter.authorise(self.settings)
def api_call(self, call_name, action="", _sound=None, report_success=False, report_failure=True, preexec_message="", *args, **kwargs):
""" Make a call to the Twitter API. If there is a connectionError or another exception not related to Twitter, It will call to the method at least 25 times, waiting a while between calls. Useful for post methods.
If twitter returns an error, it will not call anymore the method.
call_name str: The method to call
action str: The thing what you are doing on twitter, it will be reported to the user if report_success is set to True.
for example "following @tw_blue2" will be reported as "following @tw_blue2 succeeded".
_sound str: a sound to play if the call is executed properly.
report_success and report_failure bool: These are self explanatory. True or false. It's all.
preexec_message str: A message to speak to the user while the call is doing the work, example: "try to follow to x user"."""
finished = False
tries = 0
if preexec_message:
output.speak(preexec_message, True)
while finished==False and tries < 25:
try:
val = getattr(self.twitter.twitter, call_name)(*args, **kwargs)
finished = True
except TwythonError as e:
output.speak(e.message)
if report_failure and hasattr(e, 'message'):
output.speak(_("%s failed. Reason: %s") % (action, e.message))
finished = True
except:
tries = tries + 1
time.sleep(5)
if report_success:
output.speak(_("%s succeeded.") % action)
if _sound != None: sound.player.play(_sound)
@_require_login
def get_favourites_timeline(self, name, *args, **kwargs):
""" Gets favourites for the authenticated user or a friend or follower or somewhat.
name str: Name for store all in the database."""
tl = self.call_paged(self.twitter.twitter.get_favorites, *args, **kwargs)
return self.order_buffer(name, tl)
def call_paged(self, update_function, *args, **kwargs):
""" Makes a call to the Twitter API methods several times. Useful for get methods.
this function is needed for retrieving more than 200 items.
update_function str: The function to call. This function must be child of self.twitter.twitter
return a list with all items retrieved."""
max = int(self.settings["general"]["max_api_calls"])-1
results = []
data = getattr(self.twitter.twitter, update_function)(count=self.settings["general"]["max_tweets_per_call"], *args, **kwargs)
results.extend(data)
for i in range(0, max):
if i == 0: max_id = results[-1]["id"]
else: max_id = results[0]["id"]
data = update_function(max_id=max_id, count=self.settings["general"]["max_tweets_per_call"], *args, **kwargs)
results.extend(data)
results.reverse()
return results
@_require_login
def get_user_info(self):
""" Retrieves some information required by TWBlue for setup."""
f = self.twitter.twitter.get_account_settings()
sn = f["screen_name"]
self.db["user_name"] = sn
self.db["user_id"] = self.twitter.twitter.show_user(screen_name=sn)["id_str"]
try:
self.db["utc_offset"] = f["time_zone"]["utc_offset"]
except KeyError:
self.db["utc_offset"] = -time.timezone
self.get_lists()
self.get_muted_users()
self.settings.write()
@_require_login
def get_lists(self):
""" Gets the lists that the user is suscribed."""
self.db["lists"] = self.twitter.twitter.show_lists(reverse=True)
@_require_login
def get_muted_users(self):
""" Gets muted users (oh really?)."""
self.db["muted_users"] = self.twitter.twitter.get_muted_users_ids()["ids"]
@_require_login
def get_stream(self, name, function, *args, **kwargs):
""" Retrieves the items for a regular stream.
name str: Name to save items on the database.
function str: A function to get the items."""
last_id = -1
if self.db.has_key(name):
try:
if self.db[name][0]["id"] > self.db[name][-1]["id"]:
last_id = self.db[name][0]["id"]
else:
last_id = self.db[name][-1]["id"]
except IndexError:
pass
tl = self.call_paged(function, sinze_id=last_id, *args, **kwargs)
self.order_buffer(name, tl)
@_require_login
def get_cursored_stream(self, name, function, items="users", *args, **kwargs):
""" Gets items for API calls that requires using cursors to paginate the results.
name str: Name to save it in the database.
function str: Function that provides the items.
items: When the function returns the list with results, items will tell how the order function should be look.
for example get_followers_list returns a list and users are under list["users"], here the items should be point to "users"."""
items_ = []
try:
if self.db[name].has_key("next_cursor"):
next_cursor = self.db[name]["next_cursor"]
else:
next_cursor = -1
except KeyError:
next_cursor = -1
tl = getattr(self.twitter.twitter, function)(cursor=next_cursor, count=self.settings["general"]["max_tweets_per_call"], *args, **kwargs)
tl[items].reverse()
num = self.order_cursored_buffer(name, tl[items])
self.db[name]["next_cursor"] = tl["next_cursor"]
return num
def start_streaming(self):
""" Start the streaming for sending tweets in realtime."""
self.main_stream = twitter.buffers.stream.streamer(application.app_key, application.app_secret, self.settings["twitter"]["user_key"], self.settings["twitter"]["user_secret"], self)
call_threaded(self.main_stream.user)
self.timelinesStream = twitter.buffers.indibidual.timelinesStreamer(application.app_key, application.app_secret, self.settings["twitter"]["user_key"], self.settings["twitter"]["user_secret"], session=self)
ids = ""
for i in self.settings["other_buffers"]["timelines"]:
ids = ids + "%s, " % (self.db[i+"-timeline"][0]["user"]["id_str"])
# if ids != "":
call_threaded(self.timelinesStream.statuses.filter, follow=ids)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
import wx
import wxUI as view
import paths
import time
import os
import session
import manager
from config_utils import Configuration
class sessionManagerController(object):
def __init__(self):
super(sessionManagerController, self).__init__()
manager.setup()
def fill_list(self):
sessionsList = []
self.sessions = []
for i in os.listdir(paths.config_path()):
if os.path.isdir(paths.config_path(i)):
strconfig = "%s/session.conf" % (paths.config_path(i))
config_test = Configuration(strconfig)
name = config_test["twitter"]["user_name"]
if name != "" and config_test["twitter"]["user_key"] != "" and config_test["twitter"]["user_secret"] != "":
sessionsList.append(name)
self.sessions.append(i)
if hasattr(self, "view"): self.view.fill_list(sessionsList)
def show(self):
self.view = view.sessionManagerWindow(self)
if self.view.ShowModal() == wx.ID_CANCEL:
self.view.Destroy()
def do_ok(self):
for i in self.sessions:
s = session.Session(i)
s.get_configuration()
s.login()
session.sessions[i] = s
def manage_new_account(self):
location = (str(time.time())[:6])
s = session.Session(location)
manager.manager.add_session(location)
s.get_configuration()
try:
s.authorise()
self.sessions.append(location)
self.view.add_new_session_to_list()
except:
self.view.show_unauthorised_error()
return

View File

@@ -3,3 +3,7 @@ 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

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
import wx
from multiplatform_widgets import widgets
class sessionManagerWindow(wx.Dialog):
def __init__(self, controller):
super(sessionManagerWindow, self).__init__(parent=None, title="Session manager", size=wx.DefaultSize)
self.controller = controller
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
label = wx.StaticText(panel, -1, u"Select a twitter account to start TW Blue", 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)
new = wx.Button(panel, -1, u"New account", size=wx.DefaultSize)
new.Bind(wx.EVT_BUTTON, self.new_account)
ok = wx.Button(panel, wx.ID_OK, size=wx.DefaultSize)
ok.SetDefault()
ok.Bind(wx.EVT_BUTTON, self.ok)
cancel = wx.Button(panel, wx.ID_CANCEL, size=wx.DefaultSize)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(new, 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.controller.do_ok()
self.EndModal(wx.ID_OK)
def new_account(self, ev):
dlg = wx.MessageDialog(self, _(u"The request for the required Twitter authorization to continue will be opened on your browser. You only need to do it once. Would you like to autorhise a new account now?"), _(u"Authorisation"), wx.YES_NO)
if dlg.ShowModal() == wx.ID_NO:
return
else:
self.controller.manage_new_account()
def add_new_session_to_list(self):
total = self.list.get_count()
name = _(u"Authorised 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 authorisation has failed. Please try again."), _(u"Invalid user token"), wx.ICON_ERROR).ShowModal()