Skip to content

Commit

Permalink
logging fully implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
domstoppable committed Dec 20, 2016
1 parent c69ac5e commit 31add9a
Show file tree
Hide file tree
Showing 15 changed files with 184 additions and 75 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ ui/*.py
settings.ini
default.js
plugins/Selenium/chromedriver*
plugins/GoogleApps/credentials.dat

# Distribution / packaging
env/
build/
dist/

logs/
39 changes: 39 additions & 0 deletions Logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import logging

import os
import datetime

from config import settings

logLevels = {
'Critical': logging.CRITICAL,
'Error': logging.ERROR,
'Warning': logging.WARNING,
'Info': logging.INFO,
'Debug': logging.DEBUG,
}

class LogFormatter(logging.Formatter):
def format(self, record):
thisPath = os.path.dirname(__file__)
if record.pathname.find(thisPath) == 0:
record.pathname = record.pathname[len(thisPath)+1:]

if isinstance(record.msg, str):
record.msg = record.msg.replace("\n", "\\n")

formatted = super().format(record)
#print(formatted)
print(record.msg)

return formatted

if not os.path.exists('logs'):
os.makedirs('logs')

logger = logging.getLogger('')

logger.setLevel(logLevels[settings.value('logLevel', 'Debug')])
handler = logging.FileHandler(os.path.join('logs', '{0:%Y-%m-%d_%H%M%S}.log'.format(datetime.datetime.now())))
handler.setFormatter(LogFormatter('[%(levelname)-8s] [%(asctime)s] [%(pathname)40s:%(lineno)3s - %(funcName)24s] %(message)s'))
logger.addHandler(handler)
23 changes: 4 additions & 19 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# -*- coding: utf-8 -*-

import os, sys
import logging, datetime
import datetime

import logging
import Logger

from PySide import QtCore, QtGui

Expand All @@ -12,24 +15,6 @@
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtGui.QApplication(sys.argv)

logLevels = {
'Critical': logging.CRITICAL,
'Error': logging.ERROR,
'Warning': logging.WARNING,
'Info': logging.INFO,
'Debug': logging.DEBUG,
}

if not os.path.exists('logs'):
os.makedirs('logs')

logFile = os.path.join('logs', '{0:%Y-%m-%d_%H%M%S}.log'.format(datetime.datetime.now()))
logging.basicConfig(
format='%(levelname)-8s %(asctime)s %(message)s',
filename=logFile,
level=logLevels[settings.value('logLevel', 'Debug')]
)

logging.debug('Logging started')

ui.setPlugins(plugins.loadAllFromPath())
Expand Down
42 changes: 25 additions & 17 deletions plugins/Facebook/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

import logging

import time
import html2text
import re
Expand All @@ -9,7 +11,6 @@
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait


import ui

def load():
Expand Down Expand Up @@ -57,63 +58,70 @@ def createEvent(self, event):

Selenium.goto(self.getSetting('Events page URL', 'https://facebook.com/events'))
if self.getSetting('Email') is not None and self.getSetting('Password') is not None:
print('Attempting auto login...')
logging.debug('Attempting auto login...')
self.setValue(Selenium.waitForID('email'), self.getSetting('Email'))
self.setValue(Selenium.waitForID('pass'), self.getSetting('Password'))
self.click(Selenium.waitForID('u_0_1'))
else:
print('Please login...')
logging.debug('Please login...')

print('Adding event')
logging.debug('Adding event')
self.click(Selenium.waitForXPath('//*[@data-testid="event-create-button"]'))

print('Setting title')
logging.debug('Setting title')
self.setValue(Selenium.waitForXPath('//*[@placeholder="Add a short, clear name"]'), event['title'])

print('Setting location')
logging.debug('Setting location')
if '1500 E Douglas' not in event['location']:
self.setValue(Selenium.waitForXPath('//*[@placeholder="Include a place or address"]'), event['location'])

print('Setting start time')
print(event['startTime'])
logging.debug('Setting start time')
self.setValue(Selenium.waitForXPath('//input[@placeholder="mm/dd/yyyy"]'), event['startTime'].toString('M/d/yyyy'))
self.setValue(Selenium.waitForXPath('//span[@aria-label="hours"]/preceding-sibling::input'), event['startTime'].toString('h a').split(' ')[0]) # have to add the am/pm for a 12-hour clock
self.setValue(Selenium.waitForXPath('//span[@aria-label="minutes"]/preceding-sibling::input'), event['startTime'].toString('mm'))
self.setValue(Selenium.waitForXPath('//span[@aria-label="meridiem"]/preceding-sibling::input'), event['startTime'].toString('a'))

print('Adding end time')
logging.debug('Adding end time')
self.click(Selenium.waitForXPath('//*[@data-tooltip-content="Time zone set by the location"]/following-sibling::a'))

print('Setting end time')
logging.debug('Setting end time')
self.setValue(Selenium.waitForXPath('(//input[@placeholder="mm/dd/yyyy"])[2]'), event['stopTime'].toString('M/d/yyyy'))
self.setValue(Selenium.waitForXPath('(//span[@aria-label="hours"])[2]/preceding-sibling::input'), event['stopTime'].toString('h a').split(' ')[0])
self.setValue(Selenium.waitForXPath('(//span[@aria-label="minutes"])[2]/preceding-sibling::input'), event['stopTime'].toString('mm'))
self.setValue(Selenium.waitForXPath('(//span[@aria-label="meridiem"])[2]/preceding-sibling::input'), event['stopTime'].toString('a'))

print('Set category')
logging.debug('Set category')
self.click(Selenium.waitForXPath('//div/a[contains(.,"Select Category")]'))
self.click(Selenium.waitForXPath('//*[@data-section="Learning"]/a'))
if 'class' in event['title'].lower():
self.click(Selenium.waitForXPath('//*[@data-parent="Learning" and contains(., "Class")]'))
else:
self.click(Selenium.waitForXPath('//*[@data-parent="Learning" and contains(., "Workshop")]'))

print('Setting description')
logging.debug('Setting description')
self.setValue(Selenium.waitForXPath('//div[@contenteditable="true"]'), description)
time.sleep(2)

if event['registrationURL'] is not None:
print('Set ticket URL')
if event['registrationURL'] is not None and event['registrationURL'] != '':
logging.debug('Set ticket URL')
self.setValue(Selenium.waitForXPath('//*[@placeholder="Add a link to your ticketing website"]'), event['registrationURL'])

print('Saving...')
logging.debug('Saving...')
oldURL = driver.current_url
if self.getSetting('Publish immediately'):
self.click(Selenium.waitForXPath('//button[contains("Publish")]'))
else:
self.click(Selenium.waitForXPath('//button[contains(.,"Publish")]/following-sibling::div/a'))
self.click(Selenium.waitForXPath('//a[contains(.,"Save Draft")]'))

time.sleep(2)
return driver.current_url
logging.debug('Waiting for page to load')
waitCount = 0
while driver.current_url == oldURL and waitCount < 20:
time.sleep(0.5)
waitCount -= 1

url = driver.current_url
driver.close()
return url

return FacebookPlugin()
7 changes: 5 additions & 2 deletions plugins/Gmail/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

import logging

import httplib2
import base64
import ui
Expand Down Expand Up @@ -39,6 +41,7 @@ def __init__(self):
ui.addTarget(self.name, self, self.createDraftMessage)

def createDraftMessage(self, event):
logging.debug('Creating draft message')
if settings.value('timezone') is not None and settings.value('timezone') != '':
timezoneOffset = settings.value('timezone').split(' UTC')[1]
tzName = ' ' + settings.value('timezone').split(' ')[-2]
Expand All @@ -61,13 +64,13 @@ def createDraftMessage(self, event):
msg = self._createMessage(self.getSetting('Destinations'), subject, htmlBody)

self.checkForInterruption()
#http = GoogleApps.getCredentials().authorize(httplib2.Http())
http = GoogleApps.credentials.authorize(httplib2.Http())
http = GoogleApps.getCredentials().authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)

self.checkForInterruption()
draft = service.users().drafts().create(userId='me', body=msg).execute()

logging.debug('Draft created: ' + draft['message']['id'])
return 'https://mail.google.com/mail/#drafts?compose=%s' % draft['message']['id']

def _createMessage(self, to, subject, body):
Expand Down
32 changes: 24 additions & 8 deletions plugins/GoogleApps/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-

import logging
import httplib2
import os
import time
Expand All @@ -18,7 +19,6 @@
from . import codeReceiver

credentialsPath = os.path.join(os.path.dirname(__file__), 'credentials.dat')
credentials = None
instance = None
waitForAuthDialog = None

Expand All @@ -40,27 +40,36 @@ def __init__(self, name='GoogleApps'):
}
]

self.waitingForCredentials = False

if name == 'GoogleApps' and instance is None:
instance = self
ui.addAction(self.name, 'Reauthorize', self.reauthorize)

def reauthorize(self):
global credentials
# global credentials

if os.path.exists(credentialsPath):
logging.debug('Deleting credentials')
os.remove(credentialsPath)

self._getCredentials()

def _getCredentials(self, callback=None):
global credentials
# global credentials

self.waitingForCredentials = True

storage = Storage(credentialsPath)
credentials = storage.get()

if credentials is None or credentials.invalid:
logging.debug('Missing or bad credentials. Authorization required')

flow = OAuth2WebServerFlow(
client_id = self.getSetting('Client ID'),
client_secret = self.getSetting('Client secret'),
prompt = 'consent',
scope = [
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/gmail.compose',
Expand All @@ -78,15 +87,22 @@ def _getCredentials(self, callback=None):
def codeReceived(code):
dialog.hide()
credentials = flow.step2_exchange(code)
storage.put(credentials)
if callback is not None:
callback(credentials)
self.waitingForCredentials = False

codeReceiver.waitForCode(codeReceived)
elif callback is not None:
callback(credentials)

def prepare(self):
instance._getCredentials()
else:
if callback is not None:
callback(credentials)

self.waitingForCredentials = False

return credentials

def prepare(self, callback=None):
instance._getCredentials(callback)

def showWaitForCodeDialog():
global waitForAuthDialog
Expand Down
6 changes: 6 additions & 0 deletions plugins/GoogleApps/codeReceiver.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from http.server import BaseHTTPRequestHandler, HTTPServer

from PySide import QtCore
Expand All @@ -12,6 +14,8 @@ class CodeHandler(BaseHTTPRequestHandler):
def do_GET(self):
global code, server

logging.debug('Received: ' + self.path)

code = self.path.split('=')[1]

self.send_response(200)
Expand All @@ -32,6 +36,7 @@ def run(self):
global server
server = HTTPServer(('', self.port), CodeHandler)
server.allow_reuse_address = 1
logging.debug('Waiting for request')
server.handle_request()

if code != 'CANCEL':
Expand All @@ -48,4 +53,5 @@ def cancel():
global server

if server is not None:
logging.debug('Sending CANCEL request')
urllib.request.urlopen('http://%s:%s/action=CANCEL' % server.server_address)
6 changes: 5 additions & 1 deletion plugins/GoogleCalendar/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

import logging

import httplib2
import json

Expand Down Expand Up @@ -33,6 +35,7 @@ def __init__(self):

resourceJSON = self.getSetting('Resources')
if resourceJSON != '':
logging.debug('Loading resources from settings')
self._setResourceObjects(json.loads(resourceJSON))

def _setResourceObjects(self, objs):
Expand All @@ -46,6 +49,8 @@ def _setResourceObjects(self, objs):

def refreshResources(self):
def credentialsReceived(credentials):
logging.debug('Downloading resources')

http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', http=http)

Expand Down Expand Up @@ -96,5 +101,4 @@ def createEvent(self, event):

return event['htmlLink']

#def load():
return GoogleCalendarPlugin()
4 changes: 4 additions & 0 deletions plugins/MakerspaceAuthorizations/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

import logging

import ui

from plugins import Plugin
Expand All @@ -22,6 +24,8 @@ def __init__(self):
ui.addTarget(self.name, self, self.updateDescription)

def updateDescription(self, event):
logging.debug('Adding authorizations to description')

auths = event['tags']['Required auth\'s']
if len(auths) > 0:
event['description'] += '\n\nRequired authorizations: ' + ','.join(auths)
Expand Down
2 changes: 2 additions & 0 deletions plugins/Meetup/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

import logging

import meetup.api
import ui

Expand Down
Loading

0 comments on commit 31add9a

Please sign in to comment.