Skip to content

Commit

Permalink
Improve code, add Quicklook support and update alfred-workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
fniephaus committed Mar 30, 2016
1 parent 6beb1ba commit 21157b4
Show file tree
Hide file tree
Showing 17 changed files with 605 additions and 150 deletions.
28 changes: 12 additions & 16 deletions src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,6 @@
<string></string>
</dict>
</array>
<key>739C48C5-6C99-4B62-AAB4-E23DCD2035B5</key>
<array/>
<key>D377451B-43B5-45EF-9C57-7A18A8DDD55D</key>
<array>
<dict>
Expand All @@ -102,7 +100,7 @@
<array>
<dict>
<key>destinationuid</key>
<string>739C48C5-6C99-4B62-AAB4-E23DCD2035B5</string>
<string>CF8C3438-7AD9-4AE3-9462-3F17FC50809B</string>
<key>modifiers</key>
<integer>0</integer>
<key>modifiersubtext</key>
Expand Down Expand Up @@ -185,19 +183,17 @@
<dict>
<key>config</key>
<dict>
<key>concurrently</key>
<key>plusspaces</key>
<false/>
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>python pocket_launcher.py "{query}"</string>
<key>type</key>
<integer>0</integer>
<key>url</key>
<string>{query}</string>
<key>utf8</key>
<true/>
</dict>
<key>type</key>
<string>alfred.workflow.action.script</string>
<string>alfred.workflow.action.openurl</string>
<key>uid</key>
<string>739C48C5-6C99-4B62-AAB4-E23DCD2035B5</string>
<string>CF8C3438-7AD9-4AE3-9462-3F17FC50809B</string>
<key>version</key>
<integer>0</integer>
</dict>
Expand Down Expand Up @@ -500,15 +496,15 @@
<key>ypos</key>
<real>230</real>
</dict>
<key>739C48C5-6C99-4B62-AAB4-E23DCD2035B5</key>
<key>94B5A64D-BE8D-43B8-847A-F84CA4214C44</key>
<dict>
<key>ypos</key>
<real>10</real>
<real>250</real>
</dict>
<key>94B5A64D-BE8D-43B8-847A-F84CA4214C44</key>
<key>CF8C3438-7AD9-4AE3-9462-3F17FC50809B</key>
<dict>
<key>ypos</key>
<real>250</real>
<real>10</real>
</dict>
<key>D377451B-43B5-45EF-9C57-7A18A8DDD55D</key>
<dict>
Expand Down
15 changes: 6 additions & 9 deletions src/pocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def add_items(links, user_input):
links.values(), key=lambda x: int(x['time_updated']), reverse=True)
for index, link in enumerate(links):
required_keys = [
'item_id', 'given_title', 'resolved_url', 'time_updated']
'item_id', 'given_title', 'given_url', 'time_updated']
if all(x in link for x in required_keys):
# prepare title
if len(link.get('resolved_title', '')) > 0:
Expand All @@ -110,19 +110,16 @@ def add_items(links, user_input):
subtitle = get_subtitle(
link_count,
link['time_updated'],
link['resolved_url'],
link['given_url'],
tags
)
# prepare argument
argument = '%s %s' % (
link['resolved_url'], link['item_id'])

if (user_input.lower() in title.lower() or
user_input.lower() in subtitle.lower()):
WF.add_item(
title,
subtitle,
arg=argument,
arg=link['given_url'],
valid=True
)

Expand All @@ -133,10 +130,10 @@ def add_items(links, user_input):
)


def get_subtitle(item_count, time_updated, resolved_url, tags=None):
def get_subtitle(item_count, time_updated, given_url, tags=None):
time_updated = datetime.datetime.fromtimestamp(
int(time_updated)).strftime('%Y-%m-%d %H:%M')
short_url = resolved_url.replace(
short_url = given_url.replace(
'http://', '').replace('https://', '')

subtitle_elements = ['#%s' % item_count, time_updated, short_url]
Expand Down Expand Up @@ -190,7 +187,7 @@ def get_icon(name):

def is_dark():
rgb = [int(x) for x in WF.alfred_env['theme_background'][5:-6].split(',')]
return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2] ) / 255 < 0.5
return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]) / 255 < 0.5


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion src/pocket_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@
'Could not find access token...',
'Please try again or file a bug report!'
]
}
}
73 changes: 40 additions & 33 deletions src/pocket_launcher.py
Original file line number Diff line number Diff line change
@@ -1,105 +1,112 @@
import argparse
import os
import sys
import subprocess
from pocket_api import Pocket, PocketException
from pocket import refresh_list
from workflow import Workflow
from workflow.background import run_in_background

import config

WF = Workflow()
POCKET_URL = 'http://getpocket.com/a/read/%s'


def execute():
args = parse_args(WF.args)

if args.query is None:
print "No argument provided"
return 0

query = args.query.split()
if len(query) != 2:
return 0

url = query[0]
item_id = query[1]
url = args.query

if args.copy:
print set_clipboard(url)
elif args.visit_archive:
subprocess.call(['open', url])
refresh_list()
print archive_item(item_id)
print archive_item(url)
elif args.archive:
refresh_list()
print archive_item(item_id)
print archive_item(url)
open_alfred()
elif args.delete:
refresh_list()
print delete_item(item_id)
print delete_item(url)
open_alfred()
elif args.website:
subprocess.call(['open', 'http://getpocket.com/a/read/%s' % item_id])
subprocess.call(['open', POCKET_URL % get_id(url)])
else:
subprocess.call(['open', url])
print "An error occured"


def get_id(url):
links = WF.cached_data('pocket_list', max_age=0)
if url not in links:
return None
return links[url]['item_id']


def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument(
'--copy', dest='copy', action='store_true', default=None)
parser.add_argument(
'--visit-and-archive', dest='visit_archive', action='store_true', default=None)
parser.add_argument(
'--archive', dest='archive', action='store_true', default=None)
parser.add_argument(
'--delete', dest='delete', action='store_true', default=None)
parser.add_argument(
'--website', dest='website', action='store_true', default=None)
parser.add_argument('--copy', dest='copy', action='store_true',
default=None)
parser.add_argument('--visit-and-archive', dest='visit_archive',
action='store_true', default=None)
parser.add_argument('--archive', dest='archive', action='store_true',
default=None)
parser.add_argument('--delete', dest='delete', action='store_true',
default=None)
parser.add_argument('--website', dest='website', action='store_true',
default=None)
parser.add_argument('query', nargs='?', default=None)
return parser.parse_args(args)


def set_clipboard(url):
clipboard = os.popen(
""" osascript -e 'set the clipboard to "%s"' """ % url).readline()
os.popen("osascript -e 'set the clipboard to \"%s\"'" % url).readline()
return 'Link copied to clipboard'


def archive_item(item_id):
def archive_item(url):
item_id = get_id(url)
if not item_id:
return '"item_id" not found'
access_token = WF.get_password('pocket_access_token')
pocket_instance = Pocket(config.CONSUMER_KEY, access_token)
try:
pocket_instance.archive(item_id, wait=False)
remove_from_cache(item_id)
remove_from_cache(url)
return 'Link archived'
except PocketException:
return 'Connection error'


def delete_item(item_id):
def delete_item(url):
item_id = get_id(url)
if not item_id:
return '"item_id" not found'
access_token = WF.get_password('pocket_access_token')
pocket_instance = Pocket(config.CONSUMER_KEY, access_token)
try:
pocket_instance.delete(item_id, wait=False)
remove_from_cache(item_id)
remove_from_cache(url)
return 'Link deleted'
except PocketException:
return 'Connection error'


def remove_from_cache(item_id):
def remove_from_cache(url):
# remove entry in cache
links = WF.cached_data('pocket_list', max_age=0)
if type(links) is dict and links:
del links[item_id]
del links[url]
WF.cache_data('pocket_list', links)


def open_alfred():
os.system(
""" osascript -e 'tell application "Alfred 2" to run trigger "open" in workflow "com.fniephaus.pocket"' """)
os.system("osascript -e 'tell application \"Alfred 2\" to run trigger "
"\"open\" in workflow \"com.fniephaus.pocket\"'")


if __name__ == '__main__':
Expand Down
21 changes: 12 additions & 9 deletions src/pocket_refresh.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from time import time

from urllib2 import URLError
from pocket_api import Pocket, AuthException, PocketException
from workflow import Workflow, PasswordNotFound
Expand All @@ -23,11 +21,13 @@ def main():
# fetch cached links if since is not 0
if since > 0:
links = wf.cached_data('pocket_list', max_age=0) or {}

# Only use delta syncing if dict is not empty
if links:
state = 'all'

print links

next_since = 0
offset = 0
while True:
Expand Down Expand Up @@ -68,14 +68,17 @@ def main():


def sync_data(links, data):
for item_id in data.keys():
if data[item_id]['status'] == u'0':
for item in data.values():
print item
key = item['given_url']
if item['status'] == u'0':
# Add item
links[item_id] = data[item_id]
elif item_id in links:
links[key] = item
elif key in links:
# Remove item
del links[item_id]
del links[key]
return links


if __name__ == '__main__':
main() # pragma: no cover
main() # pragma: no cover
28 changes: 16 additions & 12 deletions src/pocket_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ def main(wf):
if len(wf.args) and len(wf.args[0]):
tags += [str(s.strip()) for s in wf.args[0].split(',')]

current_app = os.popen(
""" osascript -e 'application (path to frontmost application as text)' """).readline().rstrip()
current_app = os.popen("osascript -e 'application (path to frontmost "
"application as text)'").readline().rstrip()
if current_app in ['Google Chrome', 'Safari']:
if not add_item(get_browser_item(current_app), tags):
print "%s link invalid." % current_app
Expand All @@ -34,22 +34,26 @@ def main(wf):


def frontmost_app():
return os.popen(""" osascript -e 'application (path to frontmost application as text)' """).readline().rstrip()
return os.popen("osascript -e 'application (path to frontmost application"
"as text)'").readline().rstrip()


def get_browser_item(browser):
url = title = None
if browser == 'Google Chrome':
#specific the chrome on the mac not the chrome on my parralled desktop by path
url = os.popen(
""" osascript -e 'tell application "/Applications/Google Chrome.app" to return URL of active tab of front window' """).readline()
title = os.popen(
""" osascript -e 'tell application "/Applications/Google Chrome.app" to return title of active tab of front window' """).readline()
url = os.popen("osascript -e 'tell application "
"\"/Applications/Google Chrome.app\" to return URL of "
"active tab of front window'").readline()
title = os.popen("osascript -e 'tell application "
"\"/Applications/Google Chrome.app\" to return title "
"of active tab of front window'").readline()
elif browser == 'Safari':
url = os.popen(
""" osascript -e 'tell application "/Applications/Safari.app" to return URL of front document' """).readline()
title = os.popen(
""" osascript -e 'tell application "/Applications/Safari.app" to return name of front document' """).readline()
url = os.popen("osascript -e 'tell application "
"\"/Applications/Safari.app\" to return URL of front "
"document'").readline()
title = os.popen("osascript -e 'tell application "
"\"/Applications/Safari.app\" to return name of "
"front document'").readline()
if url is None:
return None
return {
Expand Down
5 changes: 4 additions & 1 deletion src/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def get_normal():
}
}


def get_refresh_initial():
return {
u'status': 1,
Expand All @@ -63,6 +64,7 @@ def get_refresh_initial():
u'list': get_normal()
}


def get_refresh_delta(since):
return {
u'status': 1,
Expand Down Expand Up @@ -107,11 +109,12 @@ def get_refresh_delta(since):
}
}


def get_refresh_end(since):
return {
u'status': 0,
u'error': None,
u'complete': 0,
u'since': since + 10,
u'list': {}
}
}
Loading

0 comments on commit 21157b4

Please sign in to comment.