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 -*-
import os
import widgetUtils
import logging
from wxUI.dialogs import attach as gui
log = logging.getLogger("controller.attach")
class attach(object):
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.remove, widgetUtils.BUTTON_PRESSED, self.remove_attachment)
self.dialog.get_response()
log.debug("Attachments controller started.")
def upload_image(self, *args, **kwargs):
image, description = self.dialog.get_image()
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)]
self.dialog.attachments.insert_item(False, *info)
self.dialog.remove.Enable(True)
def remove_attachment(self, *args, **kwargs):
current_item = self.dialog.attachments.get_selected()
log.debug("Removing item %d" % (current_item,))
if current_item == -1: current_item = 0
self.attachments.pop(current_item)
self.dialog.attachments.remove_item(current_item)
self.check_remove_status()
log.debug("Removed")
def check_remove_status(self):
if len(self.attachments) == 0 and self.dialog.attachments.get_count() == 0:

View File

@ -6,6 +6,7 @@ import utils
import posts
import player
import output
import logging
from wxUI.tabs import home
from pubsub import pub
from sessionmanager import session
@ -14,6 +15,8 @@ from wxUI import commonMessages
from vk import upload
from vk.exceptions import VkAPIMethodError
log = logging.getLogger("controller.buffers")
class baseBuffer(object):
""" 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):

View File

@ -2,7 +2,10 @@
import requests
import paths
import os
import logging
log = logging.getLogger("fixes.fix_requests")
def fix():
log.debug("Applying fix for requests...")
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 -*-
import logging
log = logging.getLogger("keyring")
keyring = None
@ -6,6 +8,7 @@ def setup():
global keyring
if keyring == None:
keyring = Keyring()
log.debug("Keyring started")
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 config
import output
import logger
import logging
import keys
import application
@ -24,10 +25,12 @@ def setup():
log.debug("config path is %s" % (paths.config_path(),))
output.setup()
languageHandler.setLanguage(config.app["app-settings"]["language"])
log.debug("Language set to %s" % (languageHandler.getLanguage()))
keys.setup()
from controller import mainController
from sessionmanager import sessionManager
app = widgetUtils.mainLoopObject()
log.debug("Created Application mainloop object")
sm = sessionManager.sessionManagerController()
del sm
r = mainController.Controller()

View File

@ -7,34 +7,34 @@ import vkSessionHandler
import logging
import utils
from config_utils import Configuration, ConfigurationResetException
log = logging.getLogger("vk.session")
log = logging.getLogger("session")
sessions = {}
# Saves possible set of identifier keys for VK'S data types
# 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.
identifiers = ["date", "aid", "gid", "uid", "pid", "id", "post_id", "nid", "date"]
# 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 = ["aid", "gid", "uid", "pid", "id", "post_id", "nid", "date"]
def find_item(list, item):
""" Finds an item in a list by taking an identifier"""
# determines the kind of identifier that we are using
global identifiers
identifier = "date"
# for i in identifiers:
# if item.has_key(i):
# identifier = i
# break
identifier = None
for i in identifiers:
if item.has_key(i):
identifier = i
break
if identifier == None:
# 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:
if i.has_key(identifier) and i[identifier] == item[identifier]:
return True
return False
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."""
msg = u""
if attachment["type"] == "link":
@ -141,7 +141,9 @@ class vkSession(object):
self.db[name]["items"] = []
first_addition = True
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 i not in self.db[name]["items"]:
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)
else: self.db[name]["items"].append(i)
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
def __init__(self, session_id):
@ -200,12 +202,15 @@ class vkSession(object):
def post_wall_status(self, message, *args, **kwargs):
""" 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)
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"):
log.debug("user has requested previous items")
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)
if data != None:
if show_nextpage == False:
@ -213,7 +218,7 @@ class vkSession(object):
# else:
# print data.keys(), len(data["items"]), data["next_from"]
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"):
self.db[name]["cursor"] = data["next_from"]
return num
@ -224,6 +229,7 @@ class vkSession(object):
p = kwargs["parent_endpoint"]
kwargs.pop("parent_endpoint")
p = getattr(self.vk.client, p)
log.debug("Calling endpoint %s with params %r" % (p, kwargs,))
data = getattr(p, endpoint)(*args, **kwargs)
if data != None:
if type(data) == dict:
@ -247,6 +253,7 @@ class vkSession(object):
return "no specified community"
def get_users(self, user_ids=None, group_ids=None):
log.debug("Getting user information from the VK servers")
if user_ids != None:
u = self.vk.client.users.get(user_ids=user_ids, fields="uid, first_name, last_name")
for i in u:
@ -257,12 +264,14 @@ class vkSession(object):
self.db["groups"][i["id"]] = i["name"]
def process_usernames(self, data):
log.debug("Adding usernames to the local database...")
for i in data["profiles"]:
self.db["users"][i["id"]] = u"{0} {1}".format(i["first_name"], i["last_name"])
for i in data["groups"]:
self.db["groups"][i["id"]] = i["name"]
def get_my_data(self):
log.debug("Getting user identifier...")
user = self.vk.client.users.get(fields="uid, first_name, last_name")
self.user_id = user[0]["id"]
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.")
self.fill_list()
if not hasattr(self, "session"):
log.debug("the session list is empty, creating a new one...")
self.manage_new_account()
def fill_list(self):
log.debug("Filling the session list...")
for i in os.listdir(paths.config_path()):
if os.path.isdir(paths.config_path(i)):
log.debug("Adding session %s" % (i,))
@ -47,6 +49,7 @@ class sessionManagerController(object):
sys.exit()
def get_authorisation(self, c):
log.debug("Starting the authorisation process...")
dl = view.newSessionDialog()
if dl.ShowModal() == widgetUtils.OK:
c.settings["vk"]["user"] = dl.get_email()

View File

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