Skip to content

Commit

Permalink
Update Alfred-Workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
deanishe committed Sep 19, 2017
1 parent 112bbcd commit de9927a
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 72 deletions.
Binary file not shown.
4 changes: 3 additions & 1 deletion src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
<dict>
<key>alfredfiltersresults</key>
<false/>
<key>alfredfiltersresultsmatchmode</key>
<integer>0</integer>
<key>argumenttrimmode</key>
<integer>0</integer>
<key>argumenttype</key>
Expand Down Expand Up @@ -124,7 +126,7 @@ Requires Viscosity app from https://www.sparklabs.com/viscosity/</string>
</dict>
</dict>
<key>version</key>
<string>2.0.2</string>
<string>2.1</string>
<key>webaddress</key>
<string></string>
</dict>
Expand Down
Binary file modified src/scripts/connect_vpn.scpt
Binary file not shown.
Binary file modified src/scripts/disconnect_vpn.scpt
Binary file not shown.
Binary file modified src/scripts/get_connections.scpt
Binary file not shown.
78 changes: 47 additions & 31 deletions src/viscosity.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@
from __future__ import print_function, absolute_import

from collections import namedtuple
from contextlib import contextmanager
from operator import attrgetter
import pipes
import subprocess
import sys
from time import time

import docopt
from workflow import Workflow3, ICON_WARNING
Expand All @@ -42,24 +44,35 @@
VPN = namedtuple('VPN', ['name', 'active'])


@contextmanager
def timed(name=None):
"""Context manager that logs execution time."""
name = name or ''
start_time = time()
yield
log.debug('[%0.2fs] %s', time() - start_time, name)


def run_script(script_name, *args):
"""Return output of script `script_name`.
Script must reside in `./scripts` subdirectory and
have extension `.scpt`.
"""
script = wf.workflowfile('scripts/{0}.scpt'.format(script_name))
cmd = ['/usr/bin/osascript', script.encode('utf-8')]
cmd += [a.encode('utf-8') for a in args]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
proc.wait()
if proc.returncode != 0:
raise RuntimeError('Script `{0}` returned {1}'.format(
script, proc.returncode))
output = wf.decode(proc.stdout.read())
log.debug('Script : %r', script)
log.debug('Output : %r', output)
with timed('ran script ' + script_name):
script = wf.workflowfile('scripts/{0}.scpt'.format(script_name))
cmd = ['/usr/bin/osascript', script.encode('utf-8')]
cmd += [a.encode('utf-8') for a in args]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
proc.wait()
if proc.returncode != 0:
raise RuntimeError('Script `{0}` returned {1}'.format(
script, proc.returncode))
output = wf.decode(proc.stdout.read())
# log.debug('Script : %r', script)
# log.debug('Output : %r', output)

return output


Expand All @@ -69,22 +82,24 @@ def _load_connections():
Returns a list of VPN tuples.
"""
connections = []
output = run_script('get_connections').strip()
for line in output.split('\n'):
if '\t' not in line:
log.warning('Bad line : %r', line)
continue
name, status = line.split('\t')
if status == 'Connected':
status = True
else:
status = False
vpn = VPN(name, status)
connections.append(vpn)
log.info(vpn)

connections.sort(key=attrgetter('name'))
with timed('loaded connections from Viscosity'):
connections = []
output = run_script('get_connections').strip()
for line in output.split('\n'):
if '\t' not in line:
log.warning('Bad line : %r', line)
continue
name, status = line.split('\t')
if status == 'Connected':
status = True
else:
status = False
vpn = VPN(name, status)
connections.append(vpn)
# log.info(vpn)

connections.sort(key=attrgetter('name'))
log.debug('%d total connection(s)', len(connections))

return connections

Expand Down Expand Up @@ -143,8 +158,9 @@ def do_list(args):
# ---------------------------------------------------------
# Filter inactive connections
if query:
connections = wf.filter(query, connections, attrgetter('name'),
min_score=30)
with timed('filtered connections'):
connections = wf.filter(query, connections, attrgetter('name'),
min_score=30)

if not connections:
wf.add_item('No matching connections.',
Expand Down Expand Up @@ -189,7 +205,7 @@ def do_connect(args):
name = args.get('<name>')
connections = filter_connections(False, name)
for con in connections:
log.debug(u'Connecting `%s` ...', con.name)
log.debug(u'connecting "%s" ...', con.name)
run_script('connect_vpn', con.name)


Expand All @@ -198,7 +214,7 @@ def do_disconnect(args):
name = args.get('<name>')
connections = filter_connections(True, name)
for con in connections:
log.debug(u'Disconnecting `%s` ...', con.name)
log.debug(u'disconnecting "%s" ...', con.name)
run_script('disconnect_vpn', con.name)


Expand Down
2 changes: 1 addition & 1 deletion src/workflow/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.27
1.28.1
43 changes: 21 additions & 22 deletions src/workflow/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1959,10 +1959,8 @@ def filter(self, query, items, key=lambda x: x, ascending=False,
``query`` is case-insensitive. Any item that does not contain the
entirety of ``query`` is rejected.
.. warning::
If ``query`` is an empty string or contains only whitespace,
a :class:`ValueError` will be raised.
If ``query`` is an empty string or contains only whitespace,
all items will match.
:param query: query to test items against
:type query: ``unicode``
Expand Down Expand Up @@ -2055,13 +2053,13 @@ def filter(self, query, items, key=lambda x: x, ascending=False,
"""
if not query:
raise ValueError('Empty `query`')
return items

# Remove preceding/trailing spaces
query = query.strip()

if not query:
raise ValueError('`query` contains only whitespace')
return items

# Use user override if there is one
fold_diacritics = self.settings.get('__workflow_diacritic_folding',
Expand Down Expand Up @@ -2244,15 +2242,16 @@ def run(self, func, text_errors=False):
# Call workflow's entry function/method within a try-except block
# to catch any errors and display an error message in Alfred
try:

if self.version:
self.logger.debug('workflow version: %s', self.version)
self.logger.debug('---------- %s (%s) ----------',
self.name, self.version)
else:
self.logger.debug('---------- %s ----------', self.name)

# Run update check if configured for self-updates.
# This call has to go in the `run` try-except block, as it will
# initialise `self.settings`, which will raise an exception
# if `settings.json` isn't valid.

if self._update_settings:
self.check_update()

Expand All @@ -2275,7 +2274,7 @@ def run(self, func, text_errors=False):
self._items = []
if self._name:
name = self._name
elif self._bundleid:
elif self._bundleid: # pragma: no cover
name = self._bundleid
else: # pragma: no cover
name = os.path.dirname(__file__)
Expand All @@ -2286,7 +2285,7 @@ def run(self, func, text_errors=False):
return 1

finally:
self.logger.debug('workflow finished in %0.3f seconds',
self.logger.debug('---------- finished in %0.3fs ----------',
time.time() - start)

return 0
Expand Down Expand Up @@ -2524,12 +2523,12 @@ def check_update(self, force=False):
if self.prereleases:
cmd.append('--prereleases')

self.logger.info('Checking for update ...')
self.logger.info('checking for update ...')

run_in_background('__workflow_update_check', cmd)

else:
self.logger.debug('Update check not due')
self.logger.debug('update check not due')

def start_update(self):
"""Check for update and download and install new workflow file.
Expand Down Expand Up @@ -2564,7 +2563,7 @@ def start_update(self):
if self.prereleases:
cmd.append('--prereleases')

self.logger.debug('Downloading update ...')
self.logger.debug('downloading update ...')
run_in_background('__workflow_update_install', cmd)

return True
Expand Down Expand Up @@ -2598,14 +2597,14 @@ def save_password(self, account, password, service=None):
try:
self._call_security('add-generic-password', service, account,
'-w', password)
self.logger.debug('Saved password : %s:%s', service, account)
self.logger.debug('saved password : %s:%s', service, account)

except PasswordExists:
self.logger.debug('Password exists : %s:%s', service, account)
self.logger.debug('password exists : %s:%s', service, account)
current_password = self.get_password(account, service)

if current_password == password:
self.logger.debug('Password unchanged')
self.logger.debug('password unchanged')

else:
self.delete_password(account, service)
Expand Down Expand Up @@ -2648,7 +2647,7 @@ def get_password(self, account, service=None):
if h:
password = unicode(binascii.unhexlify(h), 'utf-8')

self.logger.debug('Got password : %s:%s', service, account)
self.logger.debug('got password : %s:%s', service, account)

return password

Expand All @@ -2670,7 +2669,7 @@ def delete_password(self, account, service=None):

self._call_security('delete-generic-password', service, account)

self.logger.debug('Deleted password : %s:%s', service, account)
self.logger.debug('deleted password : %s:%s', service, account)

####################################################################
# Methods for workflow:* magic args
Expand Down Expand Up @@ -2773,7 +2772,7 @@ def list_magic():
for name in sorted(self.magic_arguments.keys()):
if name == 'magic':
continue
arg = '{0}{1}'.format(self.magic_prefix, name)
arg = self.magic_prefix + name
self.logger.debug(arg)

if not isatty:
Expand Down Expand Up @@ -2814,7 +2813,7 @@ def clear_settings(self):
"""Delete workflow's :attr:`settings_path`."""
if os.path.exists(self.settings_path):
os.unlink(self.settings_path)
self.logger.debug('Deleted : %r', self.settings_path)
self.logger.debug('deleted : %r', self.settings_path)

def reset(self):
"""Delete workflow settings, cache and data.
Expand Down Expand Up @@ -2951,7 +2950,7 @@ def _delete_directory_contents(self, dirpath, filter_func):
shutil.rmtree(path)
else:
os.unlink(path)
self.logger.debug('Deleted : %r', path)
self.logger.debug('deleted : %r', path)

def _load_info_plist(self):
"""Load workflow info from ``info.plist``."""
Expand Down
Loading

0 comments on commit de9927a

Please sign in to comment.