def refresh_cache(): wf = Workflow() # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets( config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE) http = httplib2.Http() try: credentials = OAuth2Credentials.from_json( wf.get_password('gmail_credentials')) if credentials is None or credentials.invalid: credentials = run(flow, PseudoStorage(), http=http) wf.save_password('gmail_credentials', credentials.to_json()) wf.logger.debug('Credentials securely updated') # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http) wf.cache_data('gmail_list', get_list(wf, http, gmail_service)) except PasswordNotFound: wf.logger.debug('Credentials not found') credentials = run(flow, PseudoStorage(), http=http) wf.save_password('gmail_credentials', credentials.to_json()) wf.logger.debug('New Credentials securely saved')
def main(): wf = Workflow() error = None try: # initialize client access_token = wf.get_password('pocket_access_token') pocket_instance = Pocket(config.CONSUMER_KEY, access_token) since = wf.cached_data('pocket_since', max_age=0) or 0 links = wf.cached_data('pocket_list', max_age=0) or {} next_since = 0 offset = 0 while True: get = pocket_instance.get( detailType='complete', since=since, state='all', count=LINK_LIMIT, offset=offset )[0] data = get['list'] next_since = get['since'] if get['status'] != 1 or len(data) == 0: break links.update(data) offset += LINK_LIMIT # Delete obsolete entries for item_id in links.keys(): if links[item_id]['status'] == '2': del links[item_id] wf.cache_data('pocket_since', next_since) wf.cache_data('pocket_list', links) tags = list(set([t for l in links.values() if 'tags' in l for t in l['tags'].keys()])) wf.cache_data('pocket_tags', tags) except (AuthException, URLError, PocketException, PasswordNotFound), e: error = type(e).__name__ wf.cache_data('pocket_error', error) # delete token if authentication failed if error == 'AuthException': wf.delete_password('pocket_access_token')
def test_install_update(httpserver, infopl, alfred4): """Update is installed.""" key = '__workflow_latest_version' # Clear any cached data wf = Workflow() wf.reset() # Assert cache was cleared assert wf.cached_data(key) is None with fakeresponse(httpserver, RELEASES_JSON, HTTP_HEADERS_JSON): # No update because no update status has been cached assert update.install_update() is False # Check for updates v = update.check_update(TEST_REPO, RELEASE_CURRENT) assert v is True # Verify new workflow is downloaded and installed with WorkflowMock() as c: assert update.install_update() is True assert c.cmd[0] == 'open' assert re.search(r'\.alfred(\d+)?workflow$', c.cmd[1]) assert wf.cached_data(key)['available'] is False # Test mangled update data status = wf.cached_data(key) assert status['available'] is False assert status['download'] is None assert status['version'] is None # Flip available bit, but leave rest invalid status['available'] = True wf.cache_data(key, status) with WorkflowMock(): assert update.install_update() is False
def test_install_update(httpserver, infopl, alfred4): """Update is installed.""" key = "__workflow_latest_version" # Clear any cached data wf = Workflow() wf.reset() # Assert cache was cleared assert wf.cached_data(key) is None with fakeresponse(httpserver, RELEASES_JSON, HTTP_HEADERS_JSON): # No update because no update status has been cached assert update.install_update() is False # Check for updates v = update.check_update(TEST_REPO, RELEASE_CURRENT) assert v is True # Verify new workflow is downloaded and installed with WorkflowMock() as c: assert update.install_update() is True assert c.cmd[0] == "open" assert re.search(r"\.alfred(\d+)?workflow$", c.cmd[1]) assert wf.cached_data(key)["available"] is False # Test mangled update data status = wf.cached_data(key) assert status["available"] is False assert status["download"] is None assert status["version"] is None # Flip available bit, but leave rest invalid status["available"] = True wf.cache_data(key, status) with WorkflowMock(): assert update.install_update() is False
def main(): wf = Workflow() error = None try: # initialize client access_token = wf.get_password('pocket_access_token') pocket_instance = Pocket(config.CONSUMER_KEY, access_token) state = None since = wf.cached_data('pocket_since', max_age=0) or 0 links = {} # 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' next_since = 0 offset = 0 while True: get = pocket_instance.get( sort='newest', detailType='complete', since=since, state=state, count=LINK_LIMIT, offset=offset )[0] data = get['list'] next_since = get['since'] if get['status'] != 1 or len(data) == 0: break links = sync_data(links, data) offset += LINK_LIMIT wf.cache_data('pocket_since', next_since) wf.cache_data('pocket_list', links) except (AuthException, URLError, PocketException, PasswordNotFound), e: error = type(e).__name__ wf.cache_data('pocket_error', error) # delete token if authentication failed if error == 'AuthException': wf.delete_password('pocket_access_token')
import mullvad from workflow import Workflow if __name__ == '__main__': wf = Workflow() # execute('mullvad_update_relay_list', mullvad.update_relay_list()) wf.cache_data('mullvad_relay_list', mullvad.get_relay_list()) wf.cache_data('mullvad_country_list', get_country_list(wf)) # wf.cache_data('mullvad_account', mullvad.get_account())
class RatesCurrencyTest(unittest.TestCase): def setUp(self): self.wf = Workflow() self.wf.clear_settings() self.wf.clear_data() self.wf.clear_cache() rates.log = self.wf.logger def tearDown(self): pass def testLoadCurrencyInfo(self): currency_info = rates.get_currencies() # Checks if all itens have all info that is used by the script for currency, info in currency_info.iteritems(): self.assertIn('Id', info, 'No ID for currency {}'.format(info)) self.assertTrue(info['Id'], 'None ID specified for currency {}'.format(info)) self.assertIn('Name', info, 'No Name for currency {}'.format(info)) self.assertTrue(info['Name'], 'No Name for currency {}'.format(info)) self.assertIn('Code', info, 'No Code for currency {}'.format(info)) self.assertTrue(info['Code'], 'No Code for currency {}'.format(info)) self.assertIn('Simbol', info, 'No Simbol for currency {}'.format(info)) self.assertTrue(info['Simbol'], 'No Simbol for currency {}'.format(info)) self.assertIn('Country', info, 'No Country for currency {}'.format(info)) self.assertTrue(info['Country'], 'No Country for currency {}'.format(info)) self.assertIn('Flag', info, 'No Flag for currency {}'.format(info)) def test_is_float(self): tests = [(1, True), ('asd', False), (1.5, True), ('1', True), ('1', True)] for test in tests: self.assertEqual(rates.is_float(test[0]), test[1]) def test_validate_currencies(self): currencies = rates.get_currencies() self.assertTrue(rates.validate_currencies([], 'BRL', 'USD', currencies, self.wf)) self.assertFalse(rates.validate_currencies([], 'BRL', 'USDD', currencies, self.wf)) self.assertFalse(rates.validate_currencies([], 'BRLL', 'USD', currencies, self.wf)) def test_clear_caches(self): self.wf.cache_data('test_cache', 'testing cache') self.wf.store_data('test_store', 'testing store') with patch.object(sys, 'argv', 'program --clear'.split()): rates.main(self.wf) self.assertEqual(len(self.wf._items), 1) self.assertEqual(self.wf._items[0].title, 'Caches cleared!') self.assertIsNone(self.wf.stored_data('test_store')) self.assertIsNone(self.wf.cached_data('test_cache')) def test_evaluate_math(self): tests = [ (['100*3', '100'], ['300', '100']), (['135.3*2', '234.5-5'], ['270.6', '229.5']), (['123/2', '61.5*50'], ['61.5', '3075.0']), (['123.5*2.5'], ['308.75']), # (['123', '/2', '61.5*50'], ['61.5', '3075.0']), # (['123', '/', '2', '61.5*50'], ['61.5', '3075.0']), # (['123', '/2', '/', '2', '61.5*50'], ['30.75', '3075.0']), # (['123', '/2', '/', '2', '61.5*50', '/3', '*2'], ['30.75', '2050.0']) # (['123*', '2'], ['246']) # (['100*2', 'usd', 'brl'], ['200', 'usd', 'brl']) ] for t in tests: result = rates.evaluate_math(t[0]) self.assertEqual(result, t[1]) def test_fmt_number(self): tests = [ ('100.00', '.', '100.00'), ('100.00', ',', '100,00'), ('1.000,00', '.', '1,000.00'), ('100', None, '100') ] for t in tests: result = rates.fmt_number(t[0], t[1]) self.assertEqual(result, t[2])
import cask from workflow import Workflow if __name__ == '__main__': wf = Workflow() wf.cache_data('cask_all_casks', cask.get_all_casks()) wf.cache_data('cask_installed_casks', cask.get_installed_casks()) wf.cache_data('cask_outdated_casks', cask.get_outdated_casks())
from workflow import Workflow, PasswordNotFound def get_all_casks(): result = execute_cask_command('search') return result.splitlines()[1:] def get_installed_casks(): result = execute_cask_command('list') return result.splitlines() def execute_cask_command(command): if command not in ['search', 'list', 'alfred status']: return None # workaround PATH problems result, err = subprocess.Popen('export PATH=/usr/local/bin:$PATH && /usr/local/bin/brew cask %s' % command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() if err != '': return err return result if __name__ == '__main__': wf = Workflow() wf.cache_data('cask_all_casks', get_all_casks()) wf.cache_data('cask_installed_casks', get_installed_casks())
import subprocess from workflow import Workflow, PasswordNotFound def get_all_packages(): cmd, _ = subprocess.Popen(['/usr/local/bin/brew', 'search'], stdout=subprocess.PIPE).communicate() return cmd.splitlines() def get_installed_packages(): cmd, _ = subprocess.Popen(['/usr/local/bin/brew', 'list', '--versions'], stdout=subprocess.PIPE).communicate() return cmd.splitlines() def get_info(): cmd, _ = subprocess.Popen(['/usr/local/bin/brew', 'info'], stdout=subprocess.PIPE).communicate() return cmd if __name__ == '__main__': wf = Workflow() wf.cache_data('brew_all_formulas', get_all_packages()) wf.cache_data('brew_installed_formulas', get_installed_packages()) wf.cache_data('brew_info', get_info())
offset += LINK_LIMIT next_since = get['since'] if get['status'] != 1 or get['list'] == []: break # Unpack and sort items for item in sorted(get['list'].values(), key=lambda x: int(x['item_id'])): if item['status'] == u'0': item_list.append(item) else: # Remove item item_list[:] = [ d for d in item_list if d.get('item_id') != item['item_id']] if next_since > since: wf.cache_data('pocket_since', next_since) wf.cache_data('pocket_list', item_list) except AuthException: error = 'AuthException' wf.cache_data('pocket_list', error) wf.delete_password('pocket_access_token') except (URLError, PocketException, PasswordNotFound), e: error = type(e).__name__ wf.cache_data('pocket_list', error) if error: wf.logger.error(error)
WF.add_item( 'Cask does not seem to be installed!', 'Hit enter to see what you need to do...', arg='open http://caskroom.io/ && exit', valid=True, icon='cask.png' ) WF.add_item( 'I trust this workflow', 'Hit enter to install cask...', arg='brew install caskroom/cask/brew-cask', valid=True, icon='cask.png' ) # delete cached file WF.cache_data('cask_not_installed', None) elif WF.cached_data('cask_not_configured', cask_not_configured, max_age=0): WF.add_item( 'Cask does not seem to be properly configured!', 'Hit enter to see what you need to do...', arg='open https://github.com/fniephaus/alfred-homebrew && exit', valid=True, icon='cask.png' ) WF.add_item( ACTIONS[8]['name'], ACTIONS[8]['description'], uid=ACTIONS[8]['name'], autocomplete=ACTIONS[8]['autocomplete'], arg=ACTIONS[8]['arg'], valid=ACTIONS[8]['valid'], icon=get_icon("chevron-right"),
import brew from workflow import Workflow if __name__ == '__main__': wf = Workflow() wf.cache_data('brew_all_formulae', brew.get_all_formulae()) wf.cache_data('brew_installed_formulae', brew.get_installed_formulae()) wf.cache_data('brew_pinned_formulae', brew.get_pinned_formulae()) wf.cache_data('brew_outdated_formulae', brew.get_outdated_formulae())
import cask from workflow import Workflow if __name__ == "__main__": wf = Workflow() wf.cache_data("cask_all_casks", cask.get_all_casks()) wf.cache_data("cask_installed_casks", cask.get_installed_casks())
from workflow import Workflow from workflow import web if __name__ == '__main__': wf = Workflow() if not wf.cached_data_fresh('hackernews_top_10', 60): items = web.get( 'https://hacker-news.firebaseio.com/v0/topstories.json').json() top_stories = [] i = 1 for item_id in items[:50]: item = web.get( 'https://hacker-news.firebaseio.com/v0/item/%s.json' % item_id).json() top_stories.append((item_id, item)) if i % 10 == 0: wf.cache_data('hackernews_top_%s0' % (i / 10), top_stories) top_stories = [] i += 1
import subprocess from workflow import Workflow, PasswordNotFound def get_all_packages(): cmd, _ = subprocess.Popen( ['/usr/local/bin/brew', 'search'], stdout=subprocess.PIPE).communicate() return cmd.splitlines() def get_installed_packages(): cmd, _ = subprocess.Popen( ['/usr/local/bin/brew', 'list', '--versions'], stdout=subprocess.PIPE).communicate() return cmd.splitlines() def get_info(): cmd, _ = subprocess.Popen( ['/usr/local/bin/brew', 'info'], stdout=subprocess.PIPE).communicate() return cmd if __name__ == '__main__': wf = Workflow() wf.cache_data('brew_all_formulas', get_all_packages()) wf.cache_data('brew_installed_formulas', get_installed_packages()) wf.cache_data('brew_info', get_info())
from workflow import Workflow from workflow import web if __name__ == '__main__': wf = Workflow() if not wf.cached_data_fresh('hackernews_top_10', 60): items = web.get('https://hacker-news.firebaseio.com/v0/topstories.json').json() top_stories = [] i = 1 for item_id in items[:50]: item = web.get('https://hacker-news.firebaseio.com/v0/item/%s.json' % item_id).json() top_stories.append((item_id, item)) if i % 10 == 0: wf.cache_data('hackernews_top_%s0' % (i / 10), top_stories) top_stories = [] i += 1
valid=False, icon=get_icon("cloud-download")) if WF.cached_data('brew_not_installed', brew_not_installed, max_age=0): WF.add_item('Brew does not seem to be installed!', 'Hit enter to see what you need to do...', arg='open http://brew.sh/#install && exit', valid=True) WF.add_item( 'I trust this workflow', 'Hit enter to install brew...', arg= 'ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"', valid=True) # delete cached file WF.cache_data('brew_not_installed', None) else: # extract query query = WF.args[0] if len(WF.args) else None if query and query.startswith('install'): for formula in get_all_packages(query): WF.add_item(formula, "Install formula", arg='brew install %s' % formula, valid=True, icon=get_icon("package")) elif query and query.startswith('search'): for formula in get_all_packages(query): WF.add_item(formula, "Open formula on GitHub",
os.environ['PATH'] += os.pathsep + '/usr/local/bin' opts = WF.settings.get('HOMEBREW_CASK_OPTS', None) options = '' if opts: if all(k in opts for k in ('appdir', 'caskroom')): options = '--appdir=%s --caskroom=%s' % (opts['appdir'], opts['caskroom']) else: err = 'Config' result, err = subprocess.Popen('/usr/local/bin/brew cask %s %s' % (options, command), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() if 'sudo' in result: err = 'Config' if err != '': return err return result if __name__ == '__main__': WF.cache_data('cask_all_casks', get_all_casks()) WF.cache_data('cask_installed_casks', get_installed_casks())
if WF.cached_data('brew_not_installed', brew_not_installed, max_age=0): WF.add_item( 'Brew does not seem to be installed!', 'Hit enter to see what you need to do...', arg='open http://brew.sh/#install && exit', valid=True ) WF.add_item( 'I trust this workflow', 'Hit enter to install brew...', arg='ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"', valid=True ) # delete cached file WF.cache_data('brew_not_installed', None) else: # extract query query = WF.args[0] if len(WF.args) else None if query and query.startswith('install'): for formula in get_all_packages(query): WF.add_item( formula, "Install formula", arg='brew install %s' % formula, valid=True, icon=get_icon("package") ) elif query and query.startswith('search'): for formula in get_all_packages(query): WF.add_item(
import zebra from workflow import Workflow if __name === '__main__': wf = Workflow() wf.cache_data('zebra_all_projects', zebra.get_all_projects()) wf.cache_data('zebra_aliased_activities', zebra.get_aliased_activities())