Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add hello world example in wox #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.credentials
*.DS_STORE
*.pyc
Binary file added Images/app.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
# Logtively-Wox
## Installation:
* clone the repo `git clone https://github.com/lobolabs/logtivly-wox.git`
* copy your clone to `<WoxDirectory>\Plugins\<YourPluginDirectory>`, i.e.: C:\Users\evex\AppData\Local\Wox\app-1.3.183\Plugins
* restart Wox

## Usage:
To use Logitvely on Wox, start wox and type `log`
1 change: 1 addition & 0 deletions client_secret.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"installed":{"client_id":"66116113965-ipj165bgcbsocir05oqee795inoh2en3.apps.googleusercontent.com","project_id":"divine-anthem-155809","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"MB8lFXAYQNT64ymiR9FDtf_8","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
Empty file added credentials/__init__.py
Empty file.
67 changes: 67 additions & 0 deletions credentials/credentials.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from __future__ import print_function
import httplib2
import os
import sys

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
CREDS_FILENAME = 'sheets.googleapis.com-python-quickstart.json'
SPREADSHEET_ID = "17MlCBBriFSKC3gfWEIK0_6ENfLiIIB8E21hoDJRrPO8"

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('.')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
CREDS_FILENAME)

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
return credentials

def get_service_and_spreadsheetId():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)

spreadsheetId = SPREADSHEET_ID
sys.stderr.write("\nspreadsheetId %s\n" % (spreadsheetId))

return service, spreadsheetId

def main():
"""Shows basic usage of the Sheets API.

Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())

if __name__ == '__main__':
main()
118 changes: 118 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-

from wox import Wox, WoxAPI
from credentials import credentials
import json, datetime, sys, os.path, subprocess

def get_sheet_title_and_column(service, spreadsheetId):
spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheetId).execute()
dateCells = "C15:I15"
for sheet in spreadsheet['sheets']:
sheetTitle = sheet['properties']['title']
rangeName = "%s!%s" % (sheetTitle, dateCells)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values',[])
colNum = 0
# TODO: replace current year with actual cell year, see http://stackoverflow.com/q/42216491/766570
for row in values:
for column in row:
dateStr = "%s %s" % (column, datetime.date.today().year)
try:
cellDate = datetime.datetime.strptime(dateStr, '%b %d %Y')
if cellDate.date() == datetime.date.today():
return sheetTitle, colNum
except ValueError:
continue

colNum +=1
return sheetTitle, colNum

def get_projects_and_hours():
service, spreadsheetId = credentials.get_service_and_spreadsheetId()
sheetTitle, colNum = get_sheet_title_and_column(service, spreadsheetId)
projectCells = 'B16:I19'
initialProjectCellIndex = 16
rangeName = "%s!%s" % (sheetTitle, projectCells)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName, majorDimension='COLUMNS').execute()
values = result.get('values',[])
return (
colNum
, sheetTitle
, values and values[0]
, values and values[colNum+1]
)

def get_project_cell(projectStr, sheetTitle, colNum):
service, spreadsheetId = credentials.get_service_and_spreadsheetId()
cols = ['c','d','e','f','g','h','i']
columnLetter = cols[colNum]
# it's not likely that there wil be more than 4 projects at a time
# but if there is, do logic that fetches all rows before the "total hours" row starts
projectCells = 'B16:%s19' % columnLetter
initialProjectCellIndex = 16
rangeName = "%s!%s" % (sheetTitle, projectCells)
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName, majorDimension='COLUMNS').execute()
values = result.get('values',[])
projectNames = list(map((lambda x: x.lower()), values and values[0]))
rowIndex = [i for i, s in enumerate(projectNames) if projectStr.lower() in s] or [0]
initialCellValue = values[colNum+1][rowIndex[0]] if len(values) > 1 and rowIndex else 0
return '%s%s' % (columnLetter, initialProjectCellIndex + rowIndex[0]), float(initialCellValue), projectNames[rowIndex[0]] if projectNames else ''

class Logtively(Wox):
def AutoComplete(self, project):
WoxAPI.change_query("log " + project)

def query(self, query):
if not os.path.isfile('.credentials\\'+credentials.CREDS_FILENAME):
subprocess.Popen(['python', 'credentials\credentials.py'], creationflags=8, close_fds=True)
return [{
"Title": "Logtively",
"SubTitle": "Login with your google account and try again",
"IcoPath": "Images/app.png",
}]

colNum, sheetTitle, projects, hours = get_projects_and_hours()

if query == '':
index = 0
results = []
for project in projects:
results.append({
"Title":project
, "SubTitle": "hours logged: "+hours[index]
, "IcoPath": "Images/app.png"
, "JsonRPCAction":{
"method": "AutoComplete"
, "parameters":[project]
, "dontHideAfterAction":True
}
})
index+=1
return results

args = query.split(' ')
if len(args) >= 2:
input_project, input_hours = (' '.join(args[0:-1]), int(args[-1]))
if type(input_hours) in [int, float] and input_hours not in [0, 0.0]:
cell, initialCellValue, retrievedProjectStr = get_project_cell(input_project, sheetTitle, colNum)
rangeName = '%s!%s:%s' % (sheetTitle, cell, cell)
sys.stderr.write("updating range" + rangeName)
values = [[initialCellValue + float(input_hours)]]
body = {
'values': values
}

service, spreadsheetId = credentials.get_service_and_spreadsheetId()
service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=rangeName, body=body, valueInputOption="USER_ENTERED").execute()
return [{
"Title": "Logtively",
"SubTitle": "Added %s hours to %s" % (input_hours, input_project),
"IcoPath": "Images/app.png",
}]

if __name__ == "__main__":
Logtively()
12 changes: 12 additions & 0 deletions plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"ID":"2f4e384e-76ce-45c3-aea2-b16f5e5c528f",
"ActionKeyword":"log",
"Name":"Logtively",
"Description":"Logtively",
"Author":"evex",
"Version":"1.0",
"Language":"python",
"Website":"https://github.com/Wox-launche/Wox",
"IcoPath":"Images\\app.png",
"ExecuteFileName":"main.py"
}