Added some code for starting

This commit is contained in:
2016-02-13 17:06:36 -06:00
parent 364472da5c
commit 0266100d66
110 changed files with 6044 additions and 0 deletions

View File

View File

@@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
from UserDict import UserDict
from configobj import ConfigObj, ParseError
from validate import Validator, VdtValueError
import os
class ConfigurationResetException(Exception):
pass
class Configuration (UserDict):
def __init__ (self, file=None, spec=None, *args, **kwargs):
self.file = file
self.spec = spec
self.validator = Validator()
self.setup_config(file=file, spec=spec)
self.validated = self.config.validate(self.validator, copy=True)
if self.validated:
self.write()
UserDict.__init__(self, self.config)
def setup_config (self, file, spec):
spec = ConfigObj(spec, list_values=False, encoding="utf-8")
try:
self.config = ConfigObj(infile=file, configspec=spec, create_empty=True, stringify=True, encoding="utf-8")
except ParseError:
os.remove(file)
self.config = ConfigObj(infile=file, configspec=spec, create_empty=True, stringify=True)
raise ConfigurationResetException
def __getitem__ (self, *args, **kwargs):
return dict(self.config).__getitem__(*args, **kwargs)
def __setitem__ (self, *args, **kwargs):
self.config.__setitem__(*args, **kwargs)
UserDict.__setitem__(self, *args, **kwargs)
def write (self):
if hasattr(self.config, 'write'):
self.config.write()
class SessionConfiguration (Configuration):
def setup_config (self, file, spec):
#No infile required.
spec = ConfigObj(spec, list_values=False)
self.config = ConfigObj(configspec=spec, stringify=True)

View File

@@ -0,0 +1,226 @@
# -*- coding: utf-8 -*-
import arrow
import languageHandler
import paths
import vkSessionHandler
import logging
import utils
from config_utils import Configuration, ConfigurationResetException
log = logging.getLogger("vk.session")
sessions = {}
def add_attachment(attachment):
""" Adds information about the attachment files in posts. It only adds the text, I mean, no attachment file is added here.
This will produce a result like 'Title of a web page: http://url.xxx', etc."""
msg = u""
if attachment["type"] == "link":
msg = u"{0}: {1}".format(attachment["link"]["title"], attachment["link"]["url"])
elif attachment["type"] == "photo":
msg = attachment["photo"]["text"]
if msg == "":
return "photo with no description available"
elif attachment["type"] == "video":
msg = u"video: {0}".format(attachment["video"]["title"],)
return msg
def add_text(status):
""" This shorts the text to 140 characters for displaying it in the list control."""
message = ""
if status.has_key("text"):
if len(status["text"]) < 140:
message = status["text"]
else:
message = status["text"][:139]
return message
def compose_new(status, session):
""" This method is used to compose an item of the news feed."""
user = session.get_user_name(status["source_id"])
message = ""
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
if status["type"] == "post":
message += add_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += add_attachment(status["attachment"])
if message == "":
message = "no description available"
elif status["type"] == "audio":
message = u"{0} has posted an audio: {1}".format(user, u", ".join(compose_audio(status["audio"][1], session)),)
elif status["type"] == "friend":
ids = ""
for i in status["friends"][1:]:
ids = ids + "{0}, ".format(i["uid"])
users = session.vk.client.users.get(user_ids=ids, fields="uid, first_name, last_name")
msg_users = u""
for i in users:
msg_users = msg_users + u"{0} {1}, ".format(i["first_name"], i["last_name"])
message = u"{0} hadded friends: {1}".format(user, msg_users)
else:
if status["type"] != "post": print status["type"]
return [user, message, created_at]
def compose_status(status, session):
# print status.keys()
user = session.get_user_name(status["from_id"])
message = ""
# user = status["copy_owner_id"]
original_date = arrow.get(status["date"])
created_at = original_date.humanize(locale=languageHandler.getLanguage())
# created_at = str(status["date"])
if status["post_type"] == "post":
message += add_text(status)
if status.has_key("attachment") and len(status["attachment"]) > 0:
message += add_attachment(status["attachment"])
if message == "":
message = "no description available"
return [user, message, created_at]
def compose_audio(audio, session):
# print audio
return [audio["title"], audio["artist"], utils.seconds_to_string(audio["duration"])]
class vkSession(object):
def order_buffer(self, name, data, field):
""" Put the new items on the local database. Useful for cursored buffers
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"] = []
for i in data:
# print i.keys()
# print i.keys()
# print i["type"]
# if i.has_key(field) and find_item(i[field], self.db[name]["items"], field) == None:
if i.has_key("type") and i["type"] == "wall_photo": continue
if i not in self.db[name]["items"]:
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):
self.session_id = session_id
self.logged = False
self.settings = None
self.vk = vkSessionHandler.vkObject()
self.db = {}
self.db["users"] = {}
self.db["groups"] = {}
@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 = Configuration(paths.config_path(file_), paths.app_path("session.defaults"))
# except:
# log.exception("The session configuration has failed.")
def login(self):
""" Login using credentials from settings.
if the user account isn't authorised, it needs to call self.authorise() before login."""
if self.settings["vk"]["token"] != None:
self.vk.login_access_token(self.settings["vk"]["token"])
self.logged = True
log.debug("Logged.")
else:
self.logged = False
raise Exceptions.RequireCredentialsSessionError
def authorise(self):
if self.logged == True:
raise Exceptions.AlreadyAuthorisedError("The authorisation process is not needed at this time.")
else:
self.vk.login(self.settings["vk"]["user"], self.settings["vk"]["password"])
self.settings["vk"]["token"] = self.vk.client._session.access_token
def post_wall_status(self, message, *args, **kwargs):
response = self.vk.client.wall.post(message=message, *args, **kwargs)
# print response
def get_newsfeed(self, name="newsfeed", no_next=True, endpoint="", *args, **kwargs):
data = getattr(self.vk.client.newsfeed, "get")(*args, **kwargs)
# print data
if data != None:
# try:
# num = self.order_buffer(name, data[1:])
# except:
num = self.order_buffer(name, data["items"][:-1], "post_id")
ids = ""
gids = ""
for i in data["items"][:-1]:
if i.has_key("source_id"):
if i["source_id"] > 0:
if str(i["source_id"]) not in ids: ids += "{0},".format(i["source_id"])
else:
if str(i["source_id"]) not in gids: gids += "{0},".format(abs(i["source_id"]))
self.get_users(ids, gids)
return num
def get_page(self, name="", no_next=True, endpoint="", *args, **kwargs):
data = None
full_list = False
if kwargs.has_key("parent_endpoint"):
p = kwargs["parent_endpoint"]
kwargs.pop("parent_endpoint")
if kwargs.has_key("full_list"):
print kwargs
full_list = True
kwargs.pop("full_list")
if kwargs.has_key("identifier"):
identifier = kwargs["identifier"]
kwargs.pop("identifier")
p = getattr(self.vk.client, p)
data = getattr(p, endpoint)(*args, **kwargs)
# print data
if data != None:
# try:
if full_list == False:
num = self.order_buffer(name, data[1:], identifier)
else:
num = self.order_buffer(name, data, identifier)
# except:
# num = self.order_buffer(name, data["items"][:-1])
ids = ""
for i in data[1:]:
if i.has_key("from_id"):
if str(i["from_id"]) not in ids: ids += "{0},".format(i["from_id"])
self.get_users(ids)
return num
def get_user_name(self, user_id):
if user_id > 0:
if self.db["users"].has_key(user_id):
return self.db["users"][user_id]
else:
return "no specified user"
else:
if self.db["groups"].has_key(abs(user_id)):
return self.db["groups"][abs(user_id)]
else:
return "no specified community"
def get_users(self, user_ids=None, group_ids=None):
if user_ids != None:
u = self.vk.client.users.get(user_ids=user_ids, fields="uid, first_name, last_name")
for i in u:
self.db["users"][i["uid"]] = u"{0} {1}".format(i["first_name"], i["last_name"])
if group_ids != None:
g = self.vk.client.groups.getById(group_ids=group_ids, fields="name")
for i in g:
self.db["groups"][i["gid"]] = i["name"]

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
import os
import shutil
import widgetUtils
import wxUI as view
import paths
import time
import os
import logging
import session
from config_utils import Configuration
log = logging.getLogger("sessionmanager.sessionManager")
class sessionManagerController(object):
def __init__(self):
super(sessionManagerController, self).__init__()
log.debug("Setting up the session manager.")
self.view = view.sessionManagerWindow()
widgetUtils.connect_event(self.view.new, widgetUtils.BUTTON_PRESSED, self.manage_new_account)
widgetUtils.connect_event(self.view.remove, widgetUtils.BUTTON_PRESSED, self.remove)
self.new_sessions = {}
self.removed_sessions = []
def fill_list(self):
sessionsList = []
log.debug("Filling the sessions list.")
self.sessions = []
for i in os.listdir(paths.config_path()):
if os.path.isdir(paths.config_path(i)):
log.debug("Adding session %s" % (i,))
strconfig = "%s/session.conf" % (paths.config_path(i))
config_test = Configuration(strconfig)
name = config_test["vk"]["user"]
sessionsList.append(name)
self.sessions.append(i)
self.view.fill_list(sessionsList)
def show(self):
if self.view.get_response() == widgetUtils.OK:
self.do_ok()
def do_ok(self):
log.debug("Starting sessions...")
for i in self.sessions:
if session.sessions.has_key(i) == True: continue
s = session.vkSession(i)
s.get_configuration()
session.sessions[i] = s
self.new_sessions[i] = s
def manage_new_account(self, *args, **kwargs):
if self.view.new_account_dialog() == widgetUtils.YES:
location = (str(time.time())[-6:])
log.debug("Creating session in the %s path" % (location,))
s = session.vkSession(location)
path = paths.config_path(location)
if not os.path.exists(path):
log.debug("Creating %s path" % (paths.config_path(path),))
os.mkdir(path)
s.get_configuration()
self.get_authorisation(s)
self.sessions.append(location)
self.view.add_new_session_to_list()
# except:
# log.exception("Error authorising the session")
# self.view.show_unauthorised_error()
# return
def remove(self, *args, **kwargs):
if self.view.remove_account_dialog() == widgetUtils.YES:
selected_account = self.sessions[self.view.get_selected()]
self.view.remove_session(self.view.get_selected())
self.removed_sessions.append(selected_account)
self.sessions.remove(selected_account)
shutil.rmtree(path=paths.config_path(selected_account), ignore_errors=True)
def get_authorisation(self, c):
dl = view.newSessionDialog()
if dl.ShowModal() == widgetUtils.OK:
c.settings["vk"]["user"] = dl.get_email()
c.settings["vk"]["password"] = dl.get_password()
c.authorise()
c.settings.write()

View File

@@ -0,0 +1,17 @@
#!/usr/bin/python
import keys
from vk import API, AuthSession, Session
class vkObject(object):
def __init__(self):
self.api_key = keys.keyring.get_api_key()
def login(self, user, password):
s = AuthSession(app_id=self.api_key, user_login=user, user_password=password, scope="wall, notify, friends, photos, audio, video, docs, notes, pages, status, groups, messages, notifications, stats")
self.client = API(s)
self.client.account.getProfileInfo()
def login_access_token(self, token):
s = Session(access_token=token)
self.client = API(s)

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
import wx
import widgetUtils
class sessionManagerWindow(widgetUtils.BaseDialog):
def __init__(self):
super(sessionManagerWindow, self).__init__(parent=None, title="Session manager", size=wx.DefaultSize)
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
label = wx.StaticText(panel, -1, u"Accounts", size=wx.DefaultSize)
listSizer = wx.BoxSizer(wx.HORIZONTAL)
self.list = widgetUtils.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.remove = wx.Button(panel, -1, _(u"Remove account"))
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(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_dialog(self):
return wx.MessageDialog(self, _(u"The request for the required facebook 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).ShowModal()
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 remove_account_dialog(self):
return wx.MessageDialog(self, _(u"Do you really want delete this account?"), _(u"Remove account"), wx.YES_NO).ShowModal()
def get_selected(self):
return self.list.get_selected()
def remove_session(self, sessionID):
self.list.remove_item(sessionID)
class newSessionDialog(widgetUtils.BaseDialog):
def __init__(self):
super(newSessionDialog, self).__init__(parent=None, id=wx.NewId(), title=_(u"Authorise VK"))
panel = wx.Panel(self)
lbl1 = wx.StaticText(panel, -1, _(u"Email address"))
self.email = wx.TextCtrl(panel, -1)
lbl2 = wx.StaticText(panel, -1, _(u"Password"))
self.passw = wx.TextCtrl(panel, -1, style=wx.TE_PASSWORD)
sizer = wx.BoxSizer()
b1 = wx.BoxSizer(wx.HORIZONTAL)
b1.Add(lbl1, 0, wx.ALL, 5)
b1.Add(self.email, 0, wx.ALL, 5)
b2 = wx.BoxSizer(wx.HORIZONTAL)
b2.Add(lbl2, 0, wx.ALL, 5)
b2.Add(self.passw, 0, wx.ALL, 5)
sizer.Add(b1, 0, wx.ALL, 5)
sizer.Add(b2, 0, wx.ALL, 5)
ok = wx.Button(panel, wx.ID_OK)
cancel = wx.Button(panel, wx.ID_CANCEL)
btnb = wx.BoxSizer(wx.HORIZONTAL)
btnb.Add(ok, 0, wx.ALL, 5)
btnb.Add(cancel, 0, wx.ALL, 5)
sizer.Add(btnb, 0, wx.ALL, 5)
panel.SetSizer(sizer)
def get_email(self):
return self.email.GetValue()
def get_password(self):
return self.passw.GetValue()