Added loggers to some functions. Needs more work

This commit is contained in:
Manuel Cortez 2016-05-10 20:23:48 -05:00
parent df563d86d8
commit 745a2a614e
9 changed files with 84 additions and 17 deletions

View File

@ -1,7 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
import widgetUtils import widgetUtils
import logging
from wxUI.dialogs import attach as gui from wxUI.dialogs import attach as gui
log = logging.getLogger("controller.attach")
class attach(object): class attach(object):
def __init__(self): def __init__(self):
@ -10,21 +12,26 @@ class attach(object):
widgetUtils.connect_event(self.dialog.photo, widgetUtils.BUTTON_PRESSED, self.upload_image) widgetUtils.connect_event(self.dialog.photo, widgetUtils.BUTTON_PRESSED, self.upload_image)
widgetUtils.connect_event(self.dialog.remove, widgetUtils.BUTTON_PRESSED, self.remove_attachment) widgetUtils.connect_event(self.dialog.remove, widgetUtils.BUTTON_PRESSED, self.remove_attachment)
self.dialog.get_response() self.dialog.get_response()
log.debug("Attachments controller started.")
def upload_image(self, *args, **kwargs): def upload_image(self, *args, **kwargs):
image, description = self.dialog.get_image() image, description = self.dialog.get_image()
if image != None: if image != None:
self.attachments.append({"type": "photo", "file": image, "description": os.path.basename(image)}) imageInfo = {"type": "photo", "file": image, "description": os.path.basename(image)}
log.debug("Image data to upload: %r" % (imageInfo,))
self.attachments.append(imageInfo)
info = [_(u"Photo"), os.path.basename(image)] info = [_(u"Photo"), os.path.basename(image)]
self.dialog.attachments.insert_item(False, *info) self.dialog.attachments.insert_item(False, *info)
self.dialog.remove.Enable(True) self.dialog.remove.Enable(True)
def remove_attachment(self, *args, **kwargs): def remove_attachment(self, *args, **kwargs):
current_item = self.dialog.attachments.get_selected() current_item = self.dialog.attachments.get_selected()
log.debug("Removing item %d" % (current_item,))
if current_item == -1: current_item = 0 if current_item == -1: current_item = 0
self.attachments.pop(current_item) self.attachments.pop(current_item)
self.dialog.attachments.remove_item(current_item) self.dialog.attachments.remove_item(current_item)
self.check_remove_status() self.check_remove_status()
log.debug("Removed")
def check_remove_status(self): def check_remove_status(self):
if len(self.attachments) == 0 and self.dialog.attachments.get_count() == 0: if len(self.attachments) == 0 and self.dialog.attachments.get_count() == 0:

View File

@ -6,6 +6,7 @@ import utils
import posts import posts
import player import player
import output import output
import logging
from wxUI.tabs import home from wxUI.tabs import home
from pubsub import pub from pubsub import pub
from sessionmanager import session from sessionmanager import session
@ -14,6 +15,8 @@ from wxUI import commonMessages
from vk import upload from vk import upload
from vk.exceptions import VkAPIMethodError from vk.exceptions import VkAPIMethodError
log = logging.getLogger("controller.buffers")
class baseBuffer(object): class baseBuffer(object):
""" a basic representation of a buffer. Other buffers should be derived from this class""" """ a basic representation of a buffer. Other buffers should be derived from this class"""
def __init__(self, parent=None, name="", session=None, composefunc=None, *args, **kwargs): def __init__(self, parent=None, name="", session=None, composefunc=None, *args, **kwargs):

View File

@ -2,7 +2,10 @@
import requests import requests
import paths import paths
import os import os
import logging
log = logging.getLogger("fixes.fix_requests")
def fix(): def fix():
log.debug("Applying fix for requests...")
os.environ["REQUESTS_CA_BUNDLE"] = paths.app_path("cacert.pem") os.environ["REQUESTS_CA_BUNDLE"] = paths.app_path("cacert.pem")
log.debug("Changed CA path to %s" % (paths.app_path("cacert.pem"),))

View File

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging
log = logging.getLogger("keyring")
keyring = None keyring = None
@ -6,6 +8,7 @@ def setup():
global keyring global keyring
if keyring == None: if keyring == None:
keyring = Keyring() keyring = Keyring()
log.debug("Keyring started")
class Keyring(object): class Keyring(object):

30
src/logger.py Normal file
View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler
import paths
import sys
APP_LOG_FILE = 'debug.log'
ERROR_LOG_FILE = "error.log"
MESSAGE_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s"
DATE_FORMAT = u"%d/%m/%Y %H:%M:%S"
formatter = logging.Formatter(MESSAGE_FORMAT.decode("utf-8"), datefmt=DATE_FORMAT)
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
#handlers
app_handler = RotatingFileHandler(paths.logs_path(APP_LOG_FILE), mode="w")
app_handler.setFormatter(formatter)
app_handler.setLevel(logging.DEBUG)
logger.addHandler(app_handler)
error_handler = logging.FileHandler(paths.logs_path(ERROR_LOG_FILE), mode="w")
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.ERROR)
logger.addHandler(error_handler)

View File

@ -9,6 +9,7 @@ import widgetUtils
import paths import paths
import config import config
import output import output
import logger
import logging import logging
import keys import keys
import application import application
@ -24,10 +25,12 @@ def setup():
log.debug("config path is %s" % (paths.config_path(),)) log.debug("config path is %s" % (paths.config_path(),))
output.setup() output.setup()
languageHandler.setLanguage(config.app["app-settings"]["language"]) languageHandler.setLanguage(config.app["app-settings"]["language"])
log.debug("Language set to %s" % (languageHandler.getLanguage()))
keys.setup() keys.setup()
from controller import mainController from controller import mainController
from sessionmanager import sessionManager from sessionmanager import sessionManager
app = widgetUtils.mainLoopObject() app = widgetUtils.mainLoopObject()
log.debug("Created Application mainloop object")
sm = sessionManager.sessionManagerController() sm = sessionManager.sessionManagerController()
del sm del sm
r = mainController.Controller() r = mainController.Controller()

View File

@ -7,34 +7,34 @@ import vkSessionHandler
import logging import logging
import utils import utils
from config_utils import Configuration, ConfigurationResetException from config_utils import Configuration, ConfigurationResetException
log = logging.getLogger("vk.session") log = logging.getLogger("session")
sessions = {} sessions = {}
# Saves possible set of identifier keys for VK'S data types # Saves possible set of identifier keys for VK'S data types
# see https://vk.com/dev/datatypes for more information. # see https://vk.com/dev/datatypes for more information.
# I've added the Date identifier (this is a field in unix time format), for special objects (like friendships indicators) because these objects doesn't have an own identifier. # I've added the Date identifier (this is a field in unix time format), for special objects (like friendship indicators) because these objects doesn't have an own identifier.
identifiers = ["date", "aid", "gid", "uid", "pid", "id", "post_id", "nid", "date"] identifiers = ["aid", "gid", "uid", "pid", "id", "post_id", "nid", "date"]
def find_item(list, item): def find_item(list, item):
""" Finds an item in a list by taking an identifier""" """ Finds an item in a list by taking an identifier"""
# determines the kind of identifier that we are using # determines the kind of identifier that we are using
global identifiers global identifiers
identifier = "date" identifier = None
# for i in identifiers: for i in identifiers:
# if item.has_key(i): if item.has_key(i):
# identifier = i identifier = i
# break break
if identifier == None: if identifier == None:
# if there are objects that can't be processed by lack of identifier, let's print keys for finding one. # if there are objects that can't be processed by lack of identifier, let's print keys for finding one.
print item.keys() log.exception("Can't find an identifier for the following object: %r" % (item.keys(),))
for i in list: for i in list:
if i.has_key(identifier) and i[identifier] == item[identifier]: if i.has_key(identifier) and i[identifier] == item[identifier]:
return True return True
return False return False
def add_attachment(attachment): 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. """ Adds information about 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.""" This will produce a result like 'Title of a web page: http://url.xxx', etc."""
msg = u"" msg = u""
if attachment["type"] == "link": if attachment["type"] == "link":
@ -141,7 +141,9 @@ class vkSession(object):
self.db[name]["items"] = [] self.db[name]["items"] = []
first_addition = True first_addition = True
for i in data: for i in data:
if i.has_key("type") and (i["type"] == "wall_photo" or i["type"] == "photo_tag"): continue if i.has_key("type") and (i["type"] == "wall_photo" or i["type"] == "photo_tag"):
log.debug("Skipping unsupported item... %r" % (i,))
continue
if find_item(self.db[name]["items"], i) == False: if find_item(self.db[name]["items"], i) == False:
# if i not in self.db[name]["items"]: # if i not in self.db[name]["items"]:
if first_addition == True or show_nextpage == True: if first_addition == True or show_nextpage == True:
@ -151,7 +153,7 @@ class vkSession(object):
if self.settings["general"]["reverse_timelines"] == False: self.db[name]["items"].insert(0, i) if self.settings["general"]["reverse_timelines"] == False: self.db[name]["items"].insert(0, i)
else: self.db[name]["items"].append(i) else: self.db[name]["items"].append(i)
num = num+1 num = num+1
print len(self.db[name]["items"]) log.debug("There are %d items in the %s buffer" % (len(self.db[name]["items"]), name))
return num return num
def __init__(self, session_id): def __init__(self, session_id):
@ -200,12 +202,15 @@ class vkSession(object):
def post_wall_status(self, message, *args, **kwargs): def post_wall_status(self, message, *args, **kwargs):
""" Sends a post to an user, group or community wall.""" """ Sends a post to an user, group or community wall."""
log.debug("Making a post to the user's wall with the following params: %r" % (kwargs,))
response = self.vk.client.wall.post(message=message, *args, **kwargs) response = self.vk.client.wall.post(message=message, *args, **kwargs)
def get_newsfeed(self, name="newsfeed", show_nextpage=False, endpoint="", *args, **kwargs): def get_newsfeed(self, name="newsfeed", show_nextpage=False, endpoint="", *args, **kwargs):
log.debug("Updating news feed...")
if show_nextpage == True and self.db[name].has_key("cursor"): if show_nextpage == True and self.db[name].has_key("cursor"):
log.debug("user has requested previous items")
kwargs["start_from"] = self.db[name]["cursor"] kwargs["start_from"] = self.db[name]["cursor"]
print kwargs log.debug("Params for sending to vk: %r" % (kwargs,))
data = getattr(self.vk.client.newsfeed, "get")(*args, **kwargs) data = getattr(self.vk.client.newsfeed, "get")(*args, **kwargs)
if data != None: if data != None:
if show_nextpage == False: if show_nextpage == False:
@ -213,7 +218,7 @@ class vkSession(object):
# else: # else:
# print data.keys(), len(data["items"]), data["next_from"] # print data.keys(), len(data["items"]), data["next_from"]
num = self.order_buffer(name, data["items"], show_nextpage) num = self.order_buffer(name, data["items"], show_nextpage)
print data.keys() log.debug("Keys of the returned data for debug purposes: %r" % (data.keys(),))
if data.has_key("next_from"): if data.has_key("next_from"):
self.db[name]["cursor"] = data["next_from"] self.db[name]["cursor"] = data["next_from"]
return num return num
@ -224,6 +229,7 @@ class vkSession(object):
p = kwargs["parent_endpoint"] p = kwargs["parent_endpoint"]
kwargs.pop("parent_endpoint") kwargs.pop("parent_endpoint")
p = getattr(self.vk.client, p) p = getattr(self.vk.client, p)
log.debug("Calling endpoint %s with params %r" % (p, kwargs,))
data = getattr(p, endpoint)(*args, **kwargs) data = getattr(p, endpoint)(*args, **kwargs)
if data != None: if data != None:
if type(data) == dict: if type(data) == dict:
@ -247,6 +253,7 @@ class vkSession(object):
return "no specified community" return "no specified community"
def get_users(self, user_ids=None, group_ids=None): def get_users(self, user_ids=None, group_ids=None):
log.debug("Getting user information from the VK servers")
if user_ids != None: if user_ids != None:
u = self.vk.client.users.get(user_ids=user_ids, fields="uid, first_name, last_name") u = self.vk.client.users.get(user_ids=user_ids, fields="uid, first_name, last_name")
for i in u: for i in u:
@ -257,12 +264,14 @@ class vkSession(object):
self.db["groups"][i["id"]] = i["name"] self.db["groups"][i["id"]] = i["name"]
def process_usernames(self, data): def process_usernames(self, data):
log.debug("Adding usernames to the local database...")
for i in data["profiles"]: for i in data["profiles"]:
self.db["users"][i["id"]] = u"{0} {1}".format(i["first_name"], i["last_name"]) self.db["users"][i["id"]] = u"{0} {1}".format(i["first_name"], i["last_name"])
for i in data["groups"]: for i in data["groups"]:
self.db["groups"][i["id"]] = i["name"] self.db["groups"][i["id"]] = i["name"]
def get_my_data(self): def get_my_data(self):
log.debug("Getting user identifier...")
user = self.vk.client.users.get(fields="uid, first_name, last_name") user = self.vk.client.users.get(fields="uid, first_name, last_name")
self.user_id = user[0]["id"] self.user_id = user[0]["id"]
self.db["users"][self.user_id] = u"{0} {1}".format(user[0]["first_name"], user[0]["last_name"]) self.db["users"][self.user_id] = u"{0} {1}".format(user[0]["first_name"], user[0]["last_name"])

View File

@ -17,9 +17,11 @@ class sessionManagerController(object):
log.debug("Setting up the session manager.") log.debug("Setting up the session manager.")
self.fill_list() self.fill_list()
if not hasattr(self, "session"): if not hasattr(self, "session"):
log.debug("the session list is empty, creating a new one...")
self.manage_new_account() self.manage_new_account()
def fill_list(self): def fill_list(self):
log.debug("Filling the session list...")
for i in os.listdir(paths.config_path()): for i in os.listdir(paths.config_path()):
if os.path.isdir(paths.config_path(i)): if os.path.isdir(paths.config_path(i)):
log.debug("Adding session %s" % (i,)) log.debug("Adding session %s" % (i,))
@ -47,6 +49,7 @@ class sessionManagerController(object):
sys.exit() sys.exit()
def get_authorisation(self, c): def get_authorisation(self, c):
log.debug("Starting the authorisation process...")
dl = view.newSessionDialog() dl = view.newSessionDialog()
if dl.ShowModal() == widgetUtils.OK: if dl.ShowModal() == widgetUtils.OK:
c.settings["vk"]["user"] = dl.get_email() c.settings["vk"]["user"] = dl.get_email()

View File

@ -1,19 +1,25 @@
#!/usr/bin/python #!/usr/bin/python
import keys import keys
import logging
from vk import API, AuthSession, Session from vk import API, AuthSession, Session
log = logging.getLogger("vkSessionHandler")
class vkObject(object): class vkObject(object):
def __init__(self): def __init__(self):
self.api_key = keys.keyring.get_api_key() self.api_key = keys.keyring.get_api_key()
self.api_version = 5.45 self.api_version = 5.45
log.debug("Created vkSession using VK API Version %s" % (self.api_version,))
def login(self, user, password): def login(self, user, password):
log.debug("Logging in vk using user/password authentication")
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") 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, v=self.api_version) self.client = API(s, v=self.api_version)
log.debug("Getting tokens for 24 hours...")
self.client.account.getProfileInfo() self.client.account.getProfileInfo()
def login_access_token(self, token): def login_access_token(self, token):
log.debug("Logging in VK using stored tokens...")
s = Session(access_token=token) s = Session(access_token=token)
self.client = API(s, v=self.api_version) self.client = API(s, v=self.api_version)
return self.client.account.getProfileInfo() return self.client.account.getProfileInfo()