Skip to content

Commit

Permalink
Add background cache refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
fniephaus committed Aug 12, 2014
1 parent b057ac8 commit ea3f932
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 142 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ This workflow lets you manage your Pocket list with Alfred.
- Actions to copy, visit and archive, archive and delete links from your Pocket list (```fn```, ```ctrl```, ```alt``` and ```cmd```)
- Hotkey to add new links from Chrome, Safari or your clipboard (```ctrl + L```)
- Action to deauthorize the workflow (```shift```)
- Keyword to refresh cache (```pocket-refresh```)
- Background cache refresh
- Supports notifications
- Uses OAuth 2.0 to authorize the workflow
- Saves your access_token securely in OS X's keychain
Expand Down
68 changes: 0 additions & 68 deletions src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -65,28 +65,6 @@
</array>
<key>739C48C5-6C99-4B62-AAB4-E23DCD2035B5</key>
<array/>
<key>B4CEA177-3AB3-4953-852F-BB45F267E156</key>
<array>
<dict>
<key>destinationuid</key>
<string>CA0E10C6-6C92-47E1-9A24-4AC6D507FA31</string>
<key>modifiers</key>
<integer>0</integer>
<key>modifiersubtext</key>
<string></string>
</dict>
</array>
<key>CA0E10C6-6C92-47E1-9A24-4AC6D507FA31</key>
<array>
<dict>
<key>destinationuid</key>
<string>94B5A64D-BE8D-43B8-847A-F84CA4214C44</string>
<key>modifiers</key>
<integer>0</integer>
<key>modifiersubtext</key>
<string></string>
</dict>
</array>
<key>DF3A17F0-109C-498C-953A-1EA26ABBE2E2</key>
<array>
<dict>
Expand Down Expand Up @@ -409,42 +387,6 @@
<key>version</key>
<integer>1</integer>
</dict>
<dict>
<key>config</key>
<dict>
<key>argumenttype</key>
<integer>2</integer>
<key>keyword</key>
<string>pocket-refresh</string>
<key>text</key>
<string>Refresh Pocket Cache</string>
<key>withspace</key>
<false/>
</dict>
<key>type</key>
<string>alfred.workflow.input.keyword</string>
<key>uid</key>
<string>B4CEA177-3AB3-4953-852F-BB45F267E156</string>
<key>version</key>
<integer>0</integer>
</dict>
<dict>
<key>config</key>
<dict>
<key>escaping</key>
<integer>102</integer>
<key>script</key>
<string>python pocket_refresh.py</string>
<key>type</key>
<integer>0</integer>
</dict>
<key>type</key>
<string>alfred.workflow.action.script</string>
<key>uid</key>
<string>CA0E10C6-6C92-47E1-9A24-4AC6D507FA31</string>
<key>version</key>
<integer>0</integer>
</dict>
</array>
<key>readme</key>
<string></string>
Expand Down Expand Up @@ -485,16 +427,6 @@
<key>ypos</key>
<real>250</real>
</dict>
<key>B4CEA177-3AB3-4953-852F-BB45F267E156</key>
<dict>
<key>ypos</key>
<real>790</real>
</dict>
<key>CA0E10C6-6C92-47E1-9A24-4AC6D507FA31</key>
<dict>
<key>ypos</key>
<real>790</real>
</dict>
<key>DF3A17F0-109C-498C-953A-1EA26ABBE2E2</key>
<dict>
<key>ypos</key>
Expand Down
66 changes: 31 additions & 35 deletions src/pocket_alfred.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import sys
import datetime
from pocket import Pocket, RateLimitException, AuthException
from requests.exceptions import ConnectionError
import sys
from pocket import Pocket, RateLimitException
from pocket_refresh import get_list
from workflow import Workflow, PasswordNotFound
from workflow.background import run_in_background, is_running

import config


Expand All @@ -16,15 +18,17 @@ def main(wf):

try:
wf.get_password('pocket_access_token')
item_list = wf.cached_data(
'pocket_list', data_func=get_list, max_age=60)
if item_list is None and len(wf._items) == 0:
wf.clear_cache()
item_list = wf.cached_data(
'pocket_list', data_func=get_list, max_age=60)
item_list = wf.cached_data('pocket_list', None, max_age=0)
if item_list is not None:
if len(item_list) == 0:
wf.add_item('Your Pocket list is empty!', valid=False)
elif item_list == "error1":
wf.add_item(
"There was a problem receiving your Pocket list...",
"The workflow has been deauthorized automatically. Please try again!", valid=False)
elif item_list == "error2":
wf.add_item("Could not contact getpocket.com...",
"Please check your Internet connection and try again!", valid=False)
else:
for index, item in enumerate(item_list):
if all(x in item for x in ['item_id', 'given_title', 'resolved_url', 'time_added']):
Expand All @@ -40,6 +44,13 @@ def main(wf):
if user_input.lower() in title.lower() or user_input.lower() in subtitle.lower():
wf.add_item(
title, subtitle, arg=argument, valid=True)
else:
wf.add_item("Could receive your Pocket list.",
"Please try again or file a bug report!", valid=False)

# Update Pocket list in background
if not wf.cached_data_fresh('pocket_list', max_age=10):
refresh_list(wf)

except PasswordNotFound:
wf.add_item(
Expand All @@ -49,32 +60,6 @@ def main(wf):
wf.send_feedback()


def get_list():
access_token = wf.get_password('pocket_access_token')
pocket_instance = Pocket(config.CONSUMER_KEY, access_token)
try:
get = pocket_instance.get()
get_list = get[0]['list']
if get_list == []:
return None

# unpack and sort items
item_list = []
for i in reversed(sorted(get_list.keys())):
item_list.append(get_list[i])

return item_list
except AuthException:
wf.delete_password('pocket_access_token')
wf.add_item('There was a problem receiving your Pocket list.',
'The workflow has been deauthenticated automatically. Please try again!', valid=False)

except ConnectionError:
wf.add_item('Could not contact getpocket.com.',
'Please check your Internet connection and try again!', valid=False)
return None


def get_auth_url(wf):
request_token = Pocket.get_request_token(
consumer_key=config.CONSUMER_KEY, redirect_uri=config.REDIRECT_URI)
Expand All @@ -98,10 +83,21 @@ def authorize():

# We don't need the cache anymore. clear it for security reasons
wf.clear_cache()

def wrapper():
return get_list(wf, user_credentials['access_token'])

wf.cached_data('pocket_list', data_func=wrapper, max_age=1)
except RateLimitException:
pass


def refresh_list(wf):
if not is_running('pocket_refresh'):
cmd = ['/usr/bin/python', wf.workflowfile('pocket_refresh.py')]
run_in_background('pocket_refresh', cmd)


if __name__ == '__main__':
wf = Workflow()
sys.exit(wf.run(main))
69 changes: 36 additions & 33 deletions src/pocket_launcher.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import sys
import argparse
import os
import sys
from pocket import Pocket
from requests.exceptions import ConnectionError
from pocket_alfred import refresh_list
from workflow import Workflow
import argparse
from workflow.background import run_in_background

import config


Expand All @@ -22,35 +24,36 @@ def execute(wf):
parser.add_argument('query', nargs='?', default=None)
args = parser.parse_args(wf.args)

query = args.query.split()
if len(query) > 0:
url = query[0]
if len(query) > 1:
item_id = query[1]
if args.query is not None:
query = args.query.split()
if len(query) > 0:
url = query[0]
if len(query) > 1:
item_id = query[1]

if args.copy:
print set_clipboard(url)
return 0
elif args.visit_archive:
open_url(url)
wf.clear_cache()
print archive_item(item_id)
return 0
elif args.archive:
wf.clear_cache()
print archive_item(item_id)
return 0
elif args.delete:
wf.clear_cache()
print delete_item(item_id)
return 0
elif args.deauthorize:
wf.delete_password('pocket_access_token')
print "Workflow deauthorized"
return 0
else:
open_url(url)
return 0
if args.copy:
print set_clipboard(url)
return 0
elif args.visit_archive:
open_url(url)
refresh_list(wf)
print archive_item(item_id)
return 0
elif args.archive:
refresh_list(wf)
print archive_item(item_id)
return 0
elif args.delete:
refresh_list(wf)
print delete_item(item_id)
return 0
elif args.deauthorize:
wf.delete_password('pocket_access_token')
print "Workflow deauthorized"
return 0
else:
open_url(url)
return 0


def open_url(url):
Expand All @@ -69,7 +72,7 @@ def archive_item(item_id):
try:
pocket_instance.archive(item_id, wait=False)
return 'Link archived'
except ConnectionError:
except Exception:
return 'Connection error'


Expand All @@ -79,7 +82,7 @@ def delete_item(item_id):
try:
pocket_instance.delete(item_id, wait=False)
return 'Link deleted'
except ConnectionError:
except Exception:
return 'Connection error'


Expand Down
46 changes: 41 additions & 5 deletions src/pocket_refresh.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,46 @@
from workflow import Workflow
from pocket import Pocket, AuthException
from workflow import Workflow, PasswordNotFound

from pocket_alfred import get_list
import config


def get_list(wf, access_token):
pocket_instance = Pocket(config.CONSUMER_KEY, access_token)
try:
get = pocket_instance.get()
get_list = get[0]['list']
if get_list == []:
return None

# Unpack and sort items
item_list = []
for i in reversed(sorted(get_list.keys())):
item_list.append(get_list[i])

return item_list

except AuthException:
return "error1"
wf.delete_password('pocket_access_token')
wf.logger.error(
'There was a problem receiving your Pocket list. The workflow has been deauthenticated automatically. Please try again!')
except Exception:
return "error2"
wf.logger.error(
'Could not contact getpocket.com. Please check your Internet connection and try again!')

return None

if __name__ == '__main__':
wf = Workflow()
print "Cache refreshed."
wf.clear_cache()
wf.cached_data('pocket_list', data_func=get_list, max_age=60)

try:
access_token = wf.get_password('pocket_access_token')

def wrapper():
return get_list(wf, access_token)

wf.cached_data('pocket_list', data_func=wrapper, max_age=1)

except PasswordNotFound:
wf.logger.error('Password not found!')

0 comments on commit ea3f932

Please sign in to comment.