Example #1
0
    def do_toggle(self):
        """Toggle generators on/off."""
        wf = self.wf
        args = self.args
        gen_id = args.get('<genid>')

        log.debug('toggling=%r', gen_id)

        # Strength bar toggle
        if gen_id == 'strength_bar':
            if wf.settings.get('strength_bar'):
                log.debug('Turning strength bar off...')
                wf.settings['strength_bar'] = False
                mode = 'off'
            else:
                log.debug('Turning strength bar on...')
                wf.settings['strength_bar'] = True
                mode = 'on'
            print('Turned strength bar {0}'.format(mode))

        # Notifications toggle
        elif gen_id == 'notifications':
            if wf.settings.get('suppress_notifications'):
                log.debug('Turning notifications on...')
                del wf.settings['suppress_notifications']
                mode = 'on'
            else:
                log.debug('Turning notifications off...')
                wf.settings['suppress_notifications'] = True
                mode = 'off'

        else:  # Generator toggles

            self.load_user_generators()

            gen = None
            for g in get_generators():
                if g.id == gen_id:
                    gen = g
                    break
            if not gen:
                log.critical('Unknown generator : %s', gen_id)
                return 1

            active_generators = wf.settings.get('generators', [])[:]
            if gen_id in active_generators:
                active_generators.remove(gen_id)
                log.info('Turned generator `%s` off', gen.name)
                mode = 'off'
            else:
                active_generators.append(gen_id)
                log.info('Turned generator `%s` on', gen.name)
                mode = 'on'
            log.debug('Active generators : %s', active_generators)
            wf.settings['generators'] = active_generators

            print("Turned generator '{0}' {1}".format(gen.name, mode))

        run_trigger('conf')
        return 0
Example #2
0
    def do_set(self):
        """Set password strength/length."""
        wf = self.wf
        args = self.args
        key = args.get('<key>')
        value = args.get('<value>')
        if not value:
            return run_trigger(key, arg='')

        if not value.isdigit():
            msg = '`{0}` is not a number'.format(value)
            log.critical(msg)
            print('ERROR : {0}'.format(msg))
            run_trigger('conf')
            return 1

        value = int(value)

        if key == 'pw_strength':
            wf.settings['pw_strength'] = value
            print('Set default password strength to {0}'.format(value))
        if key == 'pw_length':
            wf.settings['pw_length'] = value
            print('Set default password length to {0}'.format(value))

        return 0
Example #3
0
def do_set_default(args):
    """Set site as default."""
    from workflow.util import run_trigger, set_config
    from workflow.notify import notify
    s = site_from_env()
    log.debug('[default] site=%r', s)
    set_config('site_id', s.id, exportable=True)
    set_config('site_name', s.name, exportable=True)
    run_trigger('search')
    notify(u'Updated Settings',
           u'Default site changed to “{s.name}”'.format(s=s))
Example #4
0
def handle_delimited_query(query):
    """Process sub-commands.

    Args:
        query (str): User query

    """
    # Currencies or decimal places
    if query.endswith(DELIMITER):  # User deleted trailing space
        run_trigger('config')
        # subprocess.call(['osascript', '-e', ALFRED_AS])
        # return

    mode, query = [s.strip() for s in query.split(DELIMITER)]

    if mode == 'currencies':

        currencies = sorted([(name, symbol)
                             for (symbol, name) in CURRENCIES.items()] +
                            [(name, symbol)
                             for (symbol, name) in CRYPTO_CURRENCIES.items()])

        if query:
            currencies = wf.filter(query,
                                   currencies,
                                   key=lambda t: ' '.join(t),
                                   match_on=MATCH_ALL ^ MATCH_ALLCHARS,
                                   min_score=30)

        else:  # Show last update time
            age = wf.cached_data_age(CURRENCY_CACHE_NAME)
            if age > 0:  # Exchange rates in cache
                td = timedelta(seconds=age)
                wf.add_item('Exchange rates updated {}'.format(
                    human_timedelta(td)),
                            icon=ICON_INFO)

        if not currencies:
            wf.add_item('No matching currencies',
                        'Try a different query',
                        icon=ICON_WARNING)

        for name, symbol in currencies:
            wf.add_item(u'{} // {}'.format(name, symbol),
                        u'Use `{}` in conversions'.format(symbol),
                        copytext=symbol,
                        valid=False,
                        icon=ICON_CURRENCY)

        wf.send_feedback()
Example #5
0
def handle_delimited_query(query):
    """Process sub-commands.

    Args:
        query (str): User query

    """
    # Currencies or decimal places
    if query.endswith(DELIMITER):  # User deleted trailing space
        run_trigger('config')
        # subprocess.call(['osascript', '-e', ALFRED_AS])
        # return

    mode, query = [s.strip() for s in query.split(DELIMITER)]

    if mode == 'currencies':

        currencies = sorted([(name, symbol) for (symbol, name)
                            in CURRENCIES.items()] +
                            [(name, symbol) for (symbol, name)
                            in CRYPTO_CURRENCIES.items()])

        if query:
            currencies = wf.filter(query, currencies,
                                   key=lambda t: ' '.join(t),
                                   match_on=MATCH_ALL ^ MATCH_ALLCHARS,
                                   min_score=30)

        else:  # Show last update time
            age = wf.cached_data_age(CURRENCY_CACHE_NAME)
            if age > 0:  # Exchange rates in cache
                td = timedelta(seconds=age)
                wf.add_item('Exchange rates updated {}'.format(
                            human_timedelta(td)),
                            icon=ICON_INFO)

        if not currencies:
            wf.add_item('No matching currencies',
                        'Try a different query',
                        icon=ICON_WARNING)

        for name, symbol in currencies:
            wf.add_item(u'{} // {}'.format(name, symbol),
                        u'Use `{}` in conversions'.format(symbol),
                        copytext=symbol,
                        valid=False,
                        icon=ICON_CURRENCY)

        wf.send_feedback()
Example #6
0
def test_run_trigger(alfred4):
    """Call External Trigger"""
    name = "test"
    bundleid = "com.example.workflow"
    arg = "test arg"

    # With bundle ID
    script = ('Application("com.runningwithcrayons.Alfred")'
              '.runTrigger("test", '
              '{"inWorkflow": "com.example.workflow"});')
    cmd = ["/usr/bin/osascript", "-l", "JavaScript", "-e", script]
    with MockCall() as m:
        run_trigger(name, bundleid)
        assert m.cmd == cmd

    # With arg
    script = ('Application("com.runningwithcrayons.Alfred")'
              '.runTrigger("test", '
              '{"inWorkflow": "com.example.workflow", '
              '"withArgument": "test arg"});')
    cmd = ["/usr/bin/osascript", "-l", "JavaScript", "-e", script]
    with MockCall() as m:
        run_trigger(name, bundleid, arg)
        assert m.cmd == cmd

    # With bundle ID from env
    script = ('Application("com.runningwithcrayons.Alfred")'
              '.runTrigger("test", '
              '{"inWorkflow": "net.deanishe.alfred-workflow"});')
    cmd = ["/usr/bin/osascript", "-l", "JavaScript", "-e", script]
    with MockCall() as m:
        run_trigger(name)
        assert m.cmd == cmd
Example #7
0
def test_run_trigger():
    """Call External Trigger."""
    name = 'test'
    bundleid = 'net.deanishe.alfred-workflow'
    arg = 'test arg'
    argclause = 'with argument "test arg"'

    # With bundle ID
    script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg='')
    cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid)
        assert m.cmd == cmd

    # With arg
    script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg=argclause)
    cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid, arg)
        assert m.cmd == cmd

    # With bundle ID from env
    os.environ['alfred_workflow_bundleid'] = bundleid
    try:
        script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg='')
        cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
        with MockCall() as m:
            run_trigger(name)
            assert m.cmd == cmd
    finally:
        del os.environ['alfred_workflow_bundleid']
Example #8
0
def test_run_trigger():
    """Call External Trigger."""
    name = 'test'
    bundleid = 'net.deanishe.alfred-workflow'
    arg = 'test arg'
    argclause = 'with argument "test arg"'

    # With bundle ID
    script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg='')
    cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid)
        assert m.cmd == cmd

    # With arg
    script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg=argclause)
    cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid, arg)
        assert m.cmd == cmd

    # With bundle ID from env
    os.environ['alfred_workflow_bundleid'] = bundleid
    try:
        script = AS_TRIGGER.format(name=name, bundleid=bundleid, arg='')
        cmd = ['/usr/bin/osascript', '-l', 'AppleScript', '-e', script]
        with MockCall() as m:
            run_trigger(name)
            assert m.cmd == cmd
    finally:
        del os.environ['alfred_workflow_bundleid']
    def do_search_folders(self):
        """List/search all Smart Folders and return results to Alfred."""
        if not self.query and self.wf.update_available:
            self.wf.add_item(u'A new version of Smart Folders is available',
                             u'↩ or ⇥ to upgrade',
                             autocomplete='workflow:update',
                             valid=False,
                             icon=ICON_SYNC)

        try:
            folder, query = self._parse_query(self.query)
        except Backup:
            return run_trigger('search')

        if folder:  # search within folder
            self.query = query
            return self.do_search_in_folder(folder)

        elif query:  # filter folder list
            folders = self.wf.filter(query,
                                     self.folders,
                                     key=lambda t: t[0],
                                     min_score=30)
        else:  # show all folders
            folders = self.folders

        # Show results
        if not folders:
            self._add_message('No matching Smart Folders',
                              'Try a different query',
                              icon=ICON_WARNING)
        i = 0
        for name, path in folders:
            subtitle = path.replace(os.getenv('HOME'), '~')
            self.wf.add_item(name,
                             subtitle,
                             uid=path,
                             arg=path,
                             autocomplete=u'{} {} '.format(name, DELIMITER),
                             valid=True,
                             icon=path,
                             icontype='fileicon',
                             type='file')
            i += 1
            if i == MAX_RESULTS:
                break

        self.wf.send_feedback()
Example #10
0
def test_run_trigger(alfred4):
    """Call External Trigger"""
    name = 'test'
    bundleid = 'net.deanishe.alfred-workflow'
    arg = 'test arg'

    # With bundle ID
    script = (
        'Application("com.runningwithcrayons.Alfred")'
        '.runTrigger("test", '
        '{"inWorkflow": "net.deanishe.alfred-workflow"});'
    )
    cmd = ['/usr/bin/osascript', '-l', 'JavaScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid)
        assert m.cmd == cmd

    # With arg
    script = (
        'Application("com.runningwithcrayons.Alfred")'
        '.runTrigger("test", '
        '{"inWorkflow": "net.deanishe.alfred-workflow", '
        '"withArgument": "test arg"});'
    )
    cmd = ['/usr/bin/osascript', '-l', 'JavaScript', '-e', script]
    with MockCall() as m:
        run_trigger(name, bundleid, arg)
        assert m.cmd == cmd

    # With bundle ID from env
    script = (
        'Application("com.runningwithcrayons.Alfred")'
        '.runTrigger("test", '
        '{"inWorkflow": "net.deanishe.alfred-workflow"});'
    )
    os.environ['alfred_workflow_bundleid'] = bundleid
    try:
        cmd = ['/usr/bin/osascript', '-l', 'JavaScript', '-e', script]
        with MockCall() as m:
            run_trigger(name)
            assert m.cmd == cmd
    finally:
        del os.environ['alfred_workflow_bundleid']
Example #11
0
def paste():
    """Simulate CMD+V to paste clipboard."""
    run_trigger('paste')
Example #12
0
def main(wf):
    """Run workflow."""
    if wf.update_available:
        wf.add_item('A newer version is available',
                    u'↩ to install update',
                    autocomplete='workflow:update',
                    icon='update-available.png')

    query = None

    if len(wf.args):
        query = wf.args[0]

    log.debug('query=%r', query)

    count = 0

    if DELIMITER in query:
        if query.endswith(DELIMITER):
            # Back up to empty query
            run_trigger('fake')
            return

        query, count = [s.strip() for s in query.split(DELIMITER)]

        if count:
            if not count.isdigit():
                wf.add_item(u'Not a number : ' + count,
                            'Please enter a number',
                            icon=ICON_WARNING)
                wf.send_feedback()
                return

            count = int(count)
        else:
            count = 1

        fake_data = get_fake_data(names=[query], count=count)

    else:
        # Save last query so we can jump back to it if user backs up
        # wf.cache_data('last_query', query, session=True)

        fake_data = get_fake_data()

        if query:

            fake_data = wf.filter(query,
                                  fake_data,
                                  lambda t: t[0],
                                  match_on=MATCH_ALL ^ MATCH_ALLCHARS,
                                  min_score=20)

    log.debug('count=%d', count)

    if not fake_data:
        wf.add_item('No matching fakers',
                    'Try a different query',
                    icon=ICON_WARNING)

    for name, data in fake_data:

        subtitle = data
        if count:
            example = data.split('\n')[0].strip()
            subtitle = u'{} ✕ e.g. "{}"'.format(count, example)

        it = wf.add_item(name,
                         subtitle,
                         arg=data,
                         autocomplete=u'{} {} '.format(name, DELIMITER),
                         valid=True,
                         largetext=data,
                         copytext=data)

        it.setvar('title', 'Copied to Clipboard')
        it.setvar('text', data)

        if SNIPPET_MODE:
            it.setvar('paste', 1)
        else:
            mod = it.add_modifier('cmd', 'Paste to frontmost application')
            mod.setvar('paste', 1)
            mod.setvar('SHOW_NOTIFICATIONS', 0)

    wf.send_feedback()