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

Python3 compatibility (draft) #14

Closed
wants to merge 2 commits into from
Closed
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
97 changes: 48 additions & 49 deletions src/alfred-confluence.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import sys
import logging
from base64 import b64encode
from HTMLParser import HTMLParser
import html
from lib.workflow import Workflow, ICON_INFO, web, PasswordNotFound
from os.path import expanduser
from urlparse import urlparse
from urllib.parse import urlparse

log = logging

Expand All @@ -17,51 +17,52 @@
VERSION = '1.0.3'


def getConfluenceBaseUrl():
def get_confluence_base_url():
if wf.settings.get(PROP_BASEURL):
return wf.settings[PROP_BASEURL].strip('/')
else:
wf.add_item(title='No Confluence Base URL set.',
subtitle='Type confluence_baseurl <baseUrl> and hit enter.',
valid=False
)
wf.add_item(title='No Confluence Base URL set.',
subtitle='Type confluence_baseurl <baseUrl> and hit enter.',
valid=False
)
wf.send_feedback()
return 0


def getConfluenceUsername():
def get_confluence_username():
if wf.settings.get(PROP_USERNAME):
return wf.settings[PROP_USERNAME]
else:
wf.add_item(
title='No Confluence Username set. Please run confluence_username',
title='No Confluence Username set. Please run confluence_username',
subtitle='Type confluence_username <username> and hit enter.',
valid=False
)
)
wf.send_feedback()
return 0


def getConfluencePassword():
def get_confluence_password():
try:
return wf.get_password(PROP_PASSWORD)
except PasswordNotFound:
wf.add_item(
title='No Confluence Password set. Please run confluence_password',
subtitle='Type confluence_password <password> and hit enter.',
valid=False
)
)
wf.send_feedback()
return 0


def checkConfig(config):
def check_config(config):
log.info('~~ Checking config..')
log.info('~~ baseUrl: ' + config['baseUrl'])
log.info('~~ username: ' + config['username'])
log.info('~~ password: ' + config['password'])

r = web.get(config['baseUrl'] + '/rest/api/user/current', headers=dict(Authorization='Basic ' + b64encode(config['username'] + ':' + config['password'])))
r = web.get(config['baseUrl'] + '/rest/api/user/current',
headers=dict(Authorization='Basic ' + str(b64encode(config['username'] + ':' + config['password']))))

if not ((r.status_code == 200) and (r.json()['type'] == 'known')):
log.info('~~ Status code: %d', r.status_code)
Expand All @@ -77,111 +78,109 @@ def checkConfig(config):
log.info('~~ ... Ok.')


def main(wf):
def main(workflow):
parser = argparse.ArgumentParser()
parser.add_argument('--baseUrl', dest='baseUrl', nargs='?', default=None)
parser.add_argument('--username', dest='username', nargs='?', default=None)
parser.add_argument('--password', dest='password', nargs='?', default=None)
parser.add_argument('query', nargs='?', default=None)
args = parser.parse_args(wf.args)

args = parser.parse_args(workflow.args)

if args.baseUrl:
wf.settings[PROP_BASEURL] = args.baseUrl
workflow.settings[PROP_BASEURL] = args.baseUrl
return 0

if args.username:
wf.settings[PROP_USERNAME] = args.username
workflow.settings[PROP_USERNAME] = args.username
return 0

if args.password:
wf.save_password(PROP_PASSWORD, args.password)
return 0
workflow.save_password(PROP_PASSWORD, args.password)
return 0

try:
# lookup config for system
args = wf.args[0].split()
config = findConfig(args)
args = workflow.args[0].split()
config = find_config(args)

if config.get('isFallback') is None:
query = ' '.join(args[1:])
else:
query = ' '.join(args)
except:
query = wf.args[0]
query = workflow.args[0]
config = dict(
baseUrl=getConfluenceBaseUrl(),
baseUrl=get_confluence_base_url(),
prefix='',
username=getConfluenceUsername(),
password=getConfluencePassword()
)
username=get_confluence_username(),
password=get_confluence_password()
)

checkConfig(config)
check_config(config)

# query Confluence
r = web.get(config['baseUrl'] + '/rest/quicknav/1/search',
params=dict(query=query),
headers=dict(Authorization='Basic ' + b64encode(config['username'] + ':' + config['password'])))
headers=dict(Authorization='Basic ' + str(b64encode(config['username'] + ':' + config['password']))))

# throw an error if request failed
# Workflow will catch this and show it to the user
r.raise_for_status()

# Parse the JSON returned by pinboard and extract the posts
result = r.json()
contentGroups = result['contentNameMatches']
content_groups = result['contentNameMatches']

# Loop through the returned posts and add an item for each to
# the list of results for Alfred
for contentGroup in contentGroups:
for contentGroup in content_groups:
for content in contentGroup:
# filter results to only contain pages and blog posts (and search site link)
if content['className'] in ['content-type-page', 'content-type-blogpost', 'search-for']:
if (content.get('spaceName')):
if content.get('spaceName'):
subtitle = content['spaceName']
else:
subtitle = 'Use full Confluence Search'


wf.add_item(title=htmlParser.unescape(content['name']),
workflow.add_item(
title=html.unescape(content['name']),
subtitle=config['prefix'] + subtitle,
arg=getBaseUrlWithoutPath(config['baseUrl']) + content['href'],
arg=get_base_url_without_path(config['baseUrl']) + content['href'],
valid=True,
icon='assets/' + content['className'] + '.png')
icon='assets/' + content['className'] + '.png'
)

# Send the results to Alfred as XML
wf.send_feedback()
workflow.send_feedback()


def findConfig(args):
homeDir = expanduser('~')
with open(homeDir + '/.alfred-confluence.json') as configFile:
def find_config(args):
home_dir = expanduser('~')
with open(home_dir + '/.alfred-confluence.json') as configFile:
configs = json.load(configFile)


if len(args) > 1:
for config in configs:
if args[0].lower() == config['key'].lower():
return config

# Fallback to first entry
configs[0]['isFallback'] = True
configs[0]['baseUrl'] = configs[0]['baseUrl'].strip('/')
return configs[0]


def getBaseUrlWithoutPath(baseUrl):
parsedBaseUrl = urlparse(baseUrl)
baseUrlWithoutPath = parsedBaseUrl.scheme + '://' + parsedBaseUrl.netloc
return baseUrlWithoutPath.strip('/')
def get_base_url_without_path(base_url):
parsed_base_url = urlparse(base_url)
base_url_without_path = parsed_base_url.scheme + '://' + parsed_base_url.netloc
return base_url_without_path.strip('/')


if __name__ == u'__main__':
wf = Workflow(update_settings={
'github_slug': 'skleinei/alfred-confluence',
'version': VERSION
})
htmlParser = HTMLParser()
})
log = wf.logger

if wf.update_available:
Expand Down
14 changes: 7 additions & 7 deletions src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@
<key>runningsubtext</key>
<string>Searching...</string>
<key>script</key>
<string>python alfred-confluence.py "{query}"</string>
<string>python3 alfred-confluence.py "{query}"</string>
<key>scriptargtype</key>
<integer>0</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -222,7 +222,7 @@
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>python alfred-confluence.py --baseUrl "{query}"</string>
<string>python3 alfred-confluence.py --baseUrl "{query}"</string>
<key>scriptargtype</key>
<integer>0</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -266,7 +266,7 @@
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>python alfred-confluence.py --username "{query}"</string>
<string>python3 alfred-confluence.py --username "{query}"</string>
<key>scriptargtype</key>
<integer>0</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -310,7 +310,7 @@
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>python alfred-confluence.py --password "{query}"</string>
<string>python3 alfred-confluence.py --password "{query}"</string>
<key>scriptargtype</key>
<integer>0</integer>
<key>scriptfile</key>
Expand Down Expand Up @@ -373,13 +373,13 @@

The Alfred Confluence workflow makes the Confluence Quick search available in the Alfred App.

Just hit `⌘ Space` and type `c Employee Records` to search for Confluence page.
Just hit `⌘ Space` and type `c Employee Records` to search for Confluence page.


---

The Alfred Confluence workflow was build by Stefan Kleineikenscheidt
(@skleinei).
The Alfred Confluence workflow was build by Stefan Kleineikenscheidt
(@skleinei).

---

Expand Down