Skip to content
This repository has been archived by the owner on Apr 23, 2023. It is now read-only.

Commit

Permalink
added new workflow directory from https://github.com/NorthIsUp/alf…
Browse files Browse the repository at this point in the history
…red-workflow-py3` for python3 support. Auto-updating is not working now.
  • Loading branch information
atticusmatticus committed Mar 16, 2022
1 parent bb5aff6 commit 2cbbc15
Show file tree
Hide file tree
Showing 26 changed files with 193 additions and 895 deletions.
Binary file modified MullvadVPN.alfredworkflow
Binary file not shown.
2 changes: 1 addition & 1 deletion src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
<key>runningsubtext</key>
<string>Wait for it...</string>
<key>script</key>
<string>python mullvad.py "{query}"</string>
<string>python3 mullvad.py "{query}"</string>
<key>scriptargtype</key>
<integer>0</integer>
<key>scriptfile</key>
Expand Down
34 changes: 18 additions & 16 deletions src/mullvad.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# python 2
# python 3
# encoding: utf-8

import os
Expand Down Expand Up @@ -32,6 +32,7 @@ def execute(cmdList):
cmd, err = subprocess.Popen(cmdList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True, # output from commands is type `str` instead of `byte`
env=newEnv).communicate() # .communicate() returns cmd and err as a tuple
if err:
return err
Expand Down Expand Up @@ -63,7 +64,7 @@ def get_lan():


def get_kill_switch():
""" Get Mullvad Kill-Switch Status
""" Get Mullvad Always-require-vpn Status
Arguments:
None
Expand All @@ -90,7 +91,7 @@ def get_version():
supported = True
elif supported == 'false':
supported = False
# print supported
# print('supported:', supported)
currentVersion = mullVersion.splitlines()[0].split(':')[1].strip()
# print currentVersion
latestVersion = mullVersion.splitlines()[3].split(':')[1].strip()
Expand All @@ -114,7 +115,7 @@ def connection_status():
countryString, cityString = get_country_city()
# print '{} to: {} {}'.format(stat, cityString, countryString).decode('utf8')
# print ' '.join(status.split()[4:])+'. Select to Disconnect.'
wf.add_item('{} to: {} {}'.format(stat, cityString, countryString).decode('utf8'),
wf.add_item('{} to: {} {}'.format(stat, cityString, countryString), #.decode('utf8'),
subtitle=' '.join(status.split()[4:])+'. Select to Disconnect. Type "relay" to change.',
arg='/usr/local/bin/mullvad disconnect',
valid=True,
Expand Down Expand Up @@ -171,7 +172,7 @@ def get_connection():


def check_connection():
wf.add_item('check',
wf.add_item('Check',
subtitle='Check security of connection',
arg='open https://mullvad.net/en/check/',
valid=True,
Expand All @@ -184,7 +185,7 @@ def set_kill_switch():
killStat = ['Enabled', 'off', 'green']
elif status == 'Network traffic will be allowed when the VPN is disconnected':
killStat = ['Disabled', 'on', 'red']
wf.add_item('Kill switch: ' + killStat[0],
wf.add_item('Always Require VPN: ' + killStat[0],
subtitle=status + '. Select to switch',
arg='/usr/local/bin/mullvad always-require-vpn set {}'.format(killStat[1]),
valid=True,
Expand All @@ -197,8 +198,8 @@ def get_protocol():

def protocol_status():
status = get_protocol().split(':')[1].split()[0]
wf.add_item('Tunnel-protocol: {}'.format(status),
subtitle='Change tunnel-protocol',
wf.add_item('Protocol: {}'.format(status),
subtitle='Change protocol',
autocomplete='protocol',
valid=False,
icon='icons/{}.png'.format(status.lower()))
Expand Down Expand Up @@ -240,7 +241,7 @@ def set_lan():
subtitle=status + '. Select to switch',
arg='/usr/local/bin/mullvad lan set {}'.format(lanStat[1]),
valid=True,
icon='icons/lan_{}.png'.format(lanStat[2])) #TODO two monitors with connecting wires red and green
icon='icons/lan_{}.png'.format(lanStat[2]))


def set_reconnect():
Expand Down Expand Up @@ -273,6 +274,7 @@ def update_mullvad():

def get_account():
getAcct = execute(['mullvad', 'account', 'get']).splitlines()
# print('DEBUG:', type(getAcct[1].split()[3]), type('%Y-%m-%d'))
deltaDays = (datetime.strptime(getAcct[1].split()[3], '%Y-%m-%d') - datetime.utcnow()).days
return [getAcct[0].split()[2], deltaDays]

Expand All @@ -281,7 +283,7 @@ def add_time_account():
formulas = wf.cached_data('mullvad_account',
get_account,
max_age=86400)
wf.add_item('Account: {} expires in: {} days'.format(formulas[0], formulas[1]),
wf.add_item('Account #: {} expires in: {} days'.format(formulas[0], formulas[1]),
subtitle='Open mullvad account website and copy account number to clipboard',
arg='echo {} | pbcopy && open https://mullvad.net/en/account/'.format(formulas[0]), # copy account number to clipboard and open mullvad account login screen
valid=True,
Expand Down Expand Up @@ -334,7 +336,7 @@ def get_country_list():
get_relay_list,
max_age=432000)
for formula in formulas:
countries.append(formula[0].decode('utf8'))
countries.append(formula[0]) #.decode('utf8'))
return countries


Expand Down Expand Up @@ -383,7 +385,7 @@ def get_city_list(wf, countryCode):
index = [i for i, s in enumerate(countries) if countryCodeSearch in s][0]
cities = []
for city in relayList[index][1:]:
cities.append(city[0].decode('utf8'))
cities.append(city[0]) #.decode('utf8'))
wf.cache_data('mullvad_cities_list', cities)


Expand Down Expand Up @@ -445,7 +447,7 @@ def main(wf):
if query and query.startswith('check'):
check_connection()

elif query and any(query.startswith(x) for x in ['kill-switch', 'block-when-disconnected']):
elif query and any(query.startswith(x) for x in ['always-require-vpn', 'block-when-disconnected']):
set_kill_switch()

elif query and query.startswith('relay'):
Expand Down Expand Up @@ -473,7 +475,7 @@ def main(wf):
protocol_status()

elif query:
#TODO change from actions dictionary to a filter function
# TODO change from actions dictionary to a filter function
actions = mullvad_actions.ACTIONS
# filter actions by query
if query:
Expand Down Expand Up @@ -503,7 +505,7 @@ def main(wf):
wf.send_feedback()

# refresh cache
cmd = ['/usr/bin/python', wf.workflowfile('mullvad_refresh.py')]
cmd = ['/usr/bin/python3', wf.workflowfile('mullvad_refresh.py')]
run_in_background('mullvad_refresh', cmd)
# run_in_background('cache_account', cache_account)

Expand All @@ -513,5 +515,5 @@ def main(wf):
#############################

if __name__ == '__main__':
wf = Workflow(update_settings={'github_slug': GITHUB_SLUG})
wf = Workflow() #update_settings={'github_slug': GITHUB_SLUG})
sys.exit(wf.run(main))
Binary file modified src/mullvad.pyc
Binary file not shown.
14 changes: 11 additions & 3 deletions src/mullvad_actions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
ACTIONS = [
{
'name': 'block-when-disconnected',
'description': 'Kill-switch settings',
'autocomplete': 'block-when-disconnected ',
'name': 'always-require-vpn',
'description': 'Always-require-vpn settings',
'autocomplete': 'always-require-vpn ',
'arg': '',
'icon': 'icons/skull_green.png',
'valid': False
Expand Down Expand Up @@ -47,6 +47,14 @@
'icon': 'icons/chevron-right-dark.png',
'valid': False
},
{
'name': 'protocol',
'description': 'Display and alter tunnel-protocol',
'autocomplete': 'protocol ',
'arg': '',
'icon': 'icons/any.png',
'valid': False
},
{
'name': 'account',
'description': 'Display and alter account information',
Expand Down
2 changes: 1 addition & 1 deletion src/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.10.5
0.10.6
Binary file removed src/workflow/__init__.pyc
Binary file not shown.
Binary file added src/workflow/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added src/workflow/__pycache__/util.cpython-310.pyc
Binary file not shown.
Binary file added src/workflow/__pycache__/workflow.cpython-310.pyc
Binary file not shown.
Binary file not shown.
19 changes: 10 additions & 9 deletions src/workflow/background.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2014 [email protected]
Expand All @@ -17,7 +16,6 @@
and examples.
"""

from __future__ import print_function, unicode_literals

import signal
import sys
Expand Down Expand Up @@ -97,7 +95,10 @@ def _job_pid(name):
return

with open(pidfile, 'rb') as fp:
pid = int(fp.read())
read = fp.read()
print(str(read))
pid = int.from_bytes(read, sys.byteorder)
print(pid)

if _process_exists(pid):
return pid
Expand Down Expand Up @@ -141,7 +142,7 @@ def _fork_and_exit_parent(errmsg, wait=False, write=False):
if write: # write PID of child process to `pidfile`
tmp = pidfile + '.tmp'
with open(tmp, 'wb') as fp:
fp.write(str(pid))
fp.write(pid.to_bytes(4, sys.byteorder))
os.rename(tmp, pidfile)
if wait: # wait for child process to exit
os.waitpid(pid, 0)
Expand All @@ -162,9 +163,9 @@ def _fork_and_exit_parent(errmsg, wait=False, write=False):

# Now I am a daemon!
# Redirect standard file descriptors.
si = open(stdin, 'r', 0)
so = open(stdout, 'a+', 0)
se = open(stderr, 'a+', 0)
si = open(stdin, 'r', 1)
so = open(stdout, 'a+', 1)
se = open(stderr, 'a+', 1)
if hasattr(sys.stdin, 'fileno'):
os.dup2(si.fileno(), sys.stdin.fileno())
if hasattr(sys.stdout, 'fileno'):
Expand Down Expand Up @@ -230,9 +231,9 @@ def run_in_background(name, args, **kwargs):
_log().debug('[%s] command cached: %s', name, argcache)

# Call this script
cmd = ['/usr/bin/python', __file__, name]
cmd = [sys.executable, '-m', 'workflow.background', name]
_log().debug('[%s] passing job to background runner: %r', name, cmd)
retcode = subprocess.call(cmd)
retcode = subprocess.call(cmd, env={'PYTHONPATH': ':'.join(sys.path)})

if retcode: # pragma: no cover
_log().error('[%s] background runner failed with %d', name, retcode)
Expand Down
Binary file removed src/workflow/background.pyc
Binary file not shown.
27 changes: 15 additions & 12 deletions src/workflow/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,22 @@
icon and then calls the application to post notifications.
"""

from __future__ import print_function, unicode_literals


from multiprocessing import process
import os
import plistlib
from re import sub
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from typing import List
import uuid

import workflow
from . import workflow


_wf = None
Expand Down Expand Up @@ -209,6 +213,8 @@ def notify(title='', text='', sound=None):
log().error('Notify.app exited with status {0}.'.format(retcode))
return False

def usr_bin_env(*args: str) -> List[str]:
return ['/usr/bin/env', f'PATH={os.environ["PATH"]}'] + list(args)

def convert_image(inpath, outpath, size):
"""Convert an image file using ``sips``.
Expand All @@ -221,14 +227,10 @@ def convert_image(inpath, outpath, size):
Raises:
RuntimeError: Raised if ``sips`` exits with non-zero status.
"""
cmd = [
b'sips',
b'-z', str(size), str(size),
inpath,
b'--out', outpath]
cmd = ['sips', '-z', str(size), str(size), inpath, '--out', outpath]
# log().debug(cmd)
with open(os.devnull, 'w') as pipe:
retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)
retcode = subprocess.call(cmd, shell=True, stdout=pipe, stderr=subprocess.STDOUT)

if retcode != 0:
raise RuntimeError('sips exited with %d' % retcode)
Expand Down Expand Up @@ -275,10 +277,11 @@ def png_to_icns(png_path, icns_path):
convert_image(png_path, outpath, size)

cmd = [
b'iconutil',
b'-c', b'icns',
b'-o', icns_path,
iconset]
'iconutil',
'-c', 'icns',
'-o', icns_path,
iconset
]

retcode = subprocess.call(cmd)
if retcode != 0:
Expand Down
Loading

0 comments on commit 2cbbc15

Please sign in to comment.