Пример #1
0
def main():
    q = sys.argv

    # Load todos from file
    todo_file = q.pop(1)  # Path to todo.txt file

    feedback = []
    line = ""

    # Build command line.
    line = build_line(q, 1)
    addItem = I(title="Add Todo", subtitle=line, arg=u"add {0}".format(line), valid=True)

    # No words written
    if len(q) == 1:
        tmpfeedback.append(addItem)
    # Exactly one word written.
    elif len(q) == 2:
        feedback.append(addItem)
    # More than one word:
    else:
        if len(q[1]) == 1 and q[1].isalpha():
            pri = "(" + q[1].upper() + ") "
            line = pri + build_line(q, 2)
        addItem = I(title="Add Todo", subtitle=line, arg=u"add {0}".format(line), valid=True)
        feedback.append(addItem)

    alp.feedback(feedback)
Пример #2
0
    def __init__(self):
        routes = alp.jsonLoad(alp.local('routes.json'), [])
        try:
            config = alp.jsonLoad(alp.storage('config.json'))
        except Exception:
            config = {}
            alp.jsonDump(config, alp.storage('config.json'))

        self.hubid = config.get('hubid')

        alp_args = alp.args()
        args_len = len(alp_args)

        if args_len > 0:
            # Allow resetting HubId.
            config_mode = alp_args[0].isdigit()
            if self.hubid is None or config_mode:
                hubid = alp_args[0]

                return alp.feedback(alp.Item(title='Press Ctrl + Enter to set your HubId to %s' % hubid, arg=hubid, uid=hubid))

            search = alp_args[0].lower()
            routes = filter(lambda route: search in route.get('title').lower() or search in route.get('description', '').lower(), routes)
        elif self.hubid is None:
            return alp.feedback([config_item()])

        items = map(self.build_item, routes)
        return alp.feedback(items)
Пример #3
0
def main():
    cmds = {
        'init': 'initialize the DB',
        'readme': 'show the project\'s README'
    }

    argv = sys_argv
    argc = len(argv)
    items = []

    if argc > 1:
        argv = argv[:1] + argv[1].split()
        argc = len(argv)

    if argv[1] == '>':
        if argc > 2:
            for c in alp.fuzzy_search(argv[2], cmds.keys()):
                t = cmd_title(c)
                i = Item(title=t, autocomplete='> '+c, \
                            subtitle=cmds[c], valid=True, arg=cmd_arg(c))
                items.append(i)
        else:
            for c, st in cmds.iteritems():
                t = cmd_title(c)
                i = Item(title=t, autocomplete='> '+c, \
                            subtitle=st, valid=True, arg=cmd_arg(c))
                items.append(i)
        alp.feedback(items)
        return

    li = get_list()

    for p in li:
        if 'fuzzy' not in p:
            p['fuzzy'] = p['name']

    u2ascii = lambda s: unidecode(s.decode('utf-8'))

    qry = ' '.join(map(u2ascii, argv[1:])).strip()

    ppl = alp.fuzzy_search(qry, li, lambda x: x['fuzzy'])

    for p in ppl:
        kw = {}
        kw['title'] = p['name']
        kw['autocomplete'] = p['name']
        kw['subtitle'] = p['info'] if 'info' in p else ''
        if 'url' in p:
            kw['valid'] = True
            kw['arg'] = url_arg(p['url'])
        else:
            kw['valid'] = False

        if 'icon' in p:
            kw['icon'] = alp.local('icons/'+p['icon'])
            #kw['fileIcon'] = True

        items.append(Item(**kw))

    alp.feedback(items)
Пример #4
0
def pypi_query(query, pip=False):
    client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi')
    results = client.search({'name': query})
    items = []

    results.sort(key = lambda item: item['_pypi_ordering'], reverse=True)
    results = results[:30]

    for i, result in enumerate(results, start=1):
        subtitle = u'Version: {0} | {1}'.format(
            result.get('version'),
            result.get('summary'))

        arg = 'https://pypi.python.org/pypi/{0}/'.format(result.get('name'))
        if pip:
            arg = 'pip install {0}=={1}'.format(
                result.get('name'),
                result.get('version'))

        item = alp.Item(
            uid=str(i),
            arg=arg,
            valid=True,
            title=result.get('name'),
            subtitle=subtitle)
        items.append(item)

    alp.feedback(items)
Пример #5
0
def query( keyword ):

  keyword = '%'+keyword.strip()+'%'
  c.execute('''SELECT OID,* FROM jsapi WHERE name LIKE ? LIMIT 10''', ( keyword, ))

  nameMatch = c.fetchall()

  c.execute('''SELECT OID,* FROM jsapi WHERE t2 LIKE ? LIMIT 10''', ( keyword, ))
  t2Match = c.fetchall()

  allMatch = nameMatch + t2Match
  allMatch = uniMatch( allMatch )[0:10]

  items = []

  if hasNewVersion():
    item = alp.Item( title="The new js api workflow is avaliable", icon="update-icon.png", subtitle = "please choose this to download", uid="0", valid= True, autocomplete="", arg="https://github.com/allenm/jsapi-workflow")
    items.append(item)

  for index ,match in enumerate(allMatch):
    title = match[3] + ' ('+ match[2] +')'
    item = alp.Item( title= title , subtitle = match[4], uid= str(index+1 ), valid=True, autocomplete = match[3], arg= match[5] )
    items.append( item )

  alp.feedback( items )
Пример #6
0
def output_feedbackItems(tasks, top=True):
    # --name --no-id  --size --status --progress --download-url --n
    # n: t['#']
    # name: t['name'].encode(default_encoding)
    # size: from lixian_util import format_size
    #       format_size(t['size'])
    # progress: t['progress']
    # download-url: t['xunlei_url']

    items = []
    for i, t in enumerate(tasks):
        # [Task_Name: progress]
        isBT = True if t['type'] == 'bt' else False
        seqNum = str(t['#'] if top else t.get('index', t['id']))
        feedTitle = ' '.join([seqNum, t['name']])
        subTitles = [format_size(t['size']), t['status_text'], t['progress']]
        feedsubTitle = ' '.join(str(subT) for subT in subTitles)
        d_url = t['xunlei_url']
        items.append(alp_item(title=feedTitle,
                                subtitle=feedsubTitle,
                                arg=(str(t['#']) + '/' if top and isBT else d_url),
                                # autocomplete=(str(t['#']) + '/@' if top and isBT else ''),
                                fileType = True if top and isBT else False,
                                icon = 'org.bittorrent.torrent' if top and isBT else 'icon.png',
                                valid=True))


    if len(items):
        alp.feedback(items)
    else:
        alp.feedback(alp_item(title="没有找到",
                                subtitle="修改[关键字],或使用 [ID]来检索",
                                valid=False,
                                fileIcon=True,
                                icon="/System/Library/CoreServices/Problem Reporter.app"))
Пример #7
0
def list_installables(query=None,
                      paths=Installable.PATHS,
                      types=Installable.TYPES):
    """
    searches for Installables in 'path' and generates Alfred-Feedback

    Args:
        query: Filters the resuls using a substring search
        paths: List of paths that are searched for Installables
        types: List of types that are used for Installables

    Returns:
        Returns Alfred Feedback XML containing one Item per Installable
    """

    apps = Installable.get_installables(paths, types)

    # Sort by Creation time; Newest come first
    apps = sorted(apps,
                  key=lambda f: os.path.getctime(f.path),
                  reverse=True)

    fb = []
    for a in apps:
        if query and string.find(str(a).lower(), query.lower()) == -1:
            continue

        fb.append(alp.Item(**{
            'title': "Install %s" % os.path.splitext(str(a))[0],
            'subtitle': "Install this %s" % a.ext.lstrip('.'),
            'arg': a.path,
            'filetype': a.path,
        }))

    alp.feedback(fb)
Пример #8
0
def main():
    q = sys.argv[1]
    # args = q.split(" ", maxsplit=1)

    thoughts = alp.jsonLoad("thoughts.json", default=[])

    feedback = []
    uid = str(uuid.uuid4())
    addItem = I(title="Add a Thought", subtitle=q,
                arg=u"save \"{0}\" \"{1}\"".format(uid, q), valid=True)

    if len(thoughts) == 0:
        feedback.append(addItem)
    elif len(thoughts) and len(q):
        feedback.append(addItem)
        t = alp.fuzzy_search(q, thoughts, key=lambda x: x["thought"])
        for r in t:
            feedback.append(I(title=r["thought"], subtitle="Copy to clipboard.",
                            arg=u"copy \"{0}\"".format(r["uuid"]), valid=True))
    elif len(thoughts):
        for r in thoughts:
            feedback.append(I(title=r["thought"], subtitle="Copy to clipboard.",
                            arg=u"copy \"{0}\"".format(r["uuid"]), valid=True))

    alp.feedback(feedback)
Пример #9
0
def doSearch():
    q = sys.argv[1:]
    q = ' '.join(q)

    requestList = [
        "Operation=ItemSearch",
        "SearchIndex=KindleStore",
        "Sort=relevancerank"
    ]
    # requestList.append(urllib.urlencode({"Keywords": q}))
    # kw = q.replace(" ", ",")
    # requestList.append("Keywords=%s" % kw)

    requestDict = encodeRequestList(requestList, "ItemIds", keywords=q)

    searchRequest = alp.Request("http://webservices.amazon.com/onca/xml", requestDict)
    soup = searchRequest.souper()

    resultsFeedback = []
    if soup.find("error"):
        e = soup.error.message.string
        resultsFeedback.append(I(title="Bad Request", subtitle=e, valid=False))

    else:
        asins = soup.find_all("asin")

        for asin in asins:
            aResult = getData(asin.string)
            resultsFeedback.append(I(**aResult))

    if len(resultsFeedback) == 0:
        alp.feedback(I(title="No Results", subtitle="Your query returned 0 results.",
                        valid=False))
    else:
        alp.feedback(resultsFeedback)
Пример #10
0
def main():
    q = sys.argv[1]
    # args = q.split(" ", maxsplit=1)

    thoughts = alp.jsonLoad("thoughts.json", default=[])

    feedback = []
    uid = str(uuid.uuid4())
    addItem = I(title="Add a Thought",
                subtitle=q,
                arg=u"save \"{0}\" \"{1}\"".format(uid, q),
                valid=True)

    if len(thoughts) == 0:
        feedback.append(addItem)
    elif len(thoughts) and len(q):
        feedback.append(addItem)
        t = alp.fuzzy_search(q, thoughts, key=lambda x: x["thought"])
        for r in t:
            feedback.append(
                I(title=r["thought"],
                  subtitle="Copy to clipboard.",
                  arg=u"copy \"{0}\"".format(r["uuid"]),
                  valid=True))
    elif len(thoughts):
        for r in thoughts:
            feedback.append(
                I(title=r["thought"],
                  subtitle="Copy to clipboard.",
                  arg=u"copy \"{0}\"".format(r["uuid"]),
                  valid=True))

    alp.feedback(feedback)
def main():
	home = expanduser("~")
	stream = open("%s/.alfred-url-mapper.yaml" % home, 'r')
	configuration = yaml.load(stream)

	commands = {}
	collect_entries(commands, configuration)

	input_key = ''
	parameters = []
	if len(sys.argv) > 1:
		input = sys.argv[1]
		if len(input) > 0:
			split_input = input.split()
			input_key = split_input[0]
			parameters = split_input[1:]

	alp_entries = []
	for key in commands:
		(matches, new_key) = match(input_key, key)
		command_entry = commands[key]
		command_entry.key = new_key
		if matches:
			add_alp_entry(alp_entries, command_entry, parameters)
	
	# Add code to search for entered key and create the alp entries with add_alp_entry
	alp.feedback(alp_entries)
Пример #12
0
def list_installables(query=None,
                      paths=Installable.PATHS,
                      types=Installable.TYPES):
    """
    searches for Installables in 'path' and generates Alfred-Feedback

    Args:
        query: Filters the resuls using a substring search
        paths: List of paths that are searched for Installables
        types: List of types that are used for Installables

    Returns:
        Returns Alfred Feedback XML containing one Item per Installable
    """

    apps = Installable.get_installables(paths, types)

    # Sort by Creation time; Newest come first
    apps = sorted(apps, key=lambda f: os.path.getctime(f.path), reverse=True)

    fb = []
    for a in apps:
        if query and string.find(str(a).lower(), query.lower()) == -1:
            continue

        fb.append(
            alp.Item(
                **{
                    'title': "Install %s" % os.path.splitext(str(a))[0],
                    'subtitle': "Install this %s" % a.ext.lstrip('.'),
                    'arg': a.path,
                    'filetype': a.path,
                }))

    alp.feedback(fb)
Пример #13
0
def complete(query, maxresults=_MAX_RESULTS):
	#alp.log("query: " + str(query))
	#alp.log("maxresults: " + str(maxresults))
	txt = get_suggests_txt(query.decode('utf-8'))
	#alp.log("get xml: " + txt.encode('utf-8'))
	word_list = get_word_list(txt, maxresults)
	Items = get_filefilter(word_list)
	alp.feedback(Items)
Пример #14
0
def main():
    q = sys.argv

    # Load todos from file
    todo_file = q.pop(1) # Path to todo.txt file
    f = codecs.open(todo_file,'r',encoding='utf-8')
    todos = f.readlines()
    f.close()

    feedback = []
    line = ''

    # Build command line.
    line = build_line(q,1)

    # No words written
    if len(q)==1:
        if len(todos):
            tmpfeedback = []
            for r in todos:
                if not r.strip():
                    continue
                if r[0] == '(' and r[2] == ')' and r[1]:
                    pri = r[1].upper()
                else:
                    pri = 'z'
                tmpfeedback.append((pri,I(title=format(todos.index(r)+1)+':'+r, subtitle="Mark as Done", arg=u"do {0}".format(todos.index(r)+1), valid=True)))
        tmpfeedback.sort(key=lambda reg: reg[0])
        feedback = [tmpfeedback[i][1] for i in range(len(tmpfeedback))]
    # Exactly one word written.
    elif len(q)==2:
        if len(todos):
            t = alp.fuzzy_search(line, todos, key=lambda x: x)
            tmpfeedback = []
            for r in t:
                if r[0] == '(' and r[2] == ')' and r[1]:
                    pri = r[1].upper()
                else:
                    pri = 'z'
                tmpfeedback.append((pri,I(title=format(todos.index(r)+1)+':'+r, subtitle="Mark as Done", arg=u"do {0}".format(todos.index(r)+1), valid=True)))
            tmpfeedback.sort(key=lambda reg: reg[0] )
            for i in range(len(tmpfeedback)):
                feedback.append(tmpfeedback[i][1])
    # More than one word:
    else:
        t = alp.fuzzy_search(line, todos, key=lambda x: x)
        tmpfeedback = []
        for r in t:
            if r[0] == '(' and r[2] == ')' and r[1]:
                pri = r[1].upper()
            else:
                pri = 'z'
            tmpfeedback.append((pri,I(title=format(todos.index(r)+1)+':'+r, subtitle="Mark as Done", arg=u"do {0}".format(todos.index(r)+1), valid=True)))
        tmpfeedback.sort(key=lambda reg: reg[0] )
        for i in range(len(tmpfeedback)):
            feedback.append(tmpfeedback[i][1])

    alp.feedback(feedback)
Пример #15
0
def do_feedback():
    args = alp.args()
    path = args[0]
    feedback = []
    for n, color in COLORS.items():
        icon = os.path.join(alp.local(), "icons", "{0}.png".format(color))
        feedback.append(I(title=color, subtitle=u"Set Finder label to {0}".format(color),
                        icon=icon, valid=True, arg=u"\"{0}\" \"{1}\"".format(path, n)))
    alp.feedback(feedback)
Пример #16
0
def handle_error(title, subtitle, icon = "icon-no.png", debug = ""):
    """
    Output an error message in a form suitable for Alfred to show something.
    Send the error and any debug info supplied to the log file.
    """
    i = alp.Item(title = title, subtitle = subtitle, icon = icon)
    alp.feedback(i)
    alp.log("Handled error: %s, %s\n%s" % (title, subtitle, debug))
    sys.exit(0)
Пример #17
0
def handle_error(title, subtitle, icon="icon-no.png", debug=""):
    """
    Output an error message in a form suitable for Alfred to show something.
    Send the error and any debug info supplied to the log file.
    """
    i = alp.Item(title=title, subtitle=subtitle, icon=icon)
    alp.feedback(i)
    alp.log("Handled error: %s, %s\n%s" % (title, subtitle, debug))
    sys.exit(0)
Пример #18
0
def list_accounts():

    files = os.listdir(path)
    items = []
    for f in files:
        if f.startswith('cn') and os.path.isdir(path + f) and os.path.isfile(path + f + '/db/contact.db'):
            item = alp.Item(title=u'设置帐号 \'%s\'' % f, subtitle='', arg=f, valid=True)
            items.append(item)
    if items.count == 0:
        item = alp.Item(title=u'没有找到可用帐号', subtitle=u'尚未登录过旺旺或者已登录旺旺好友列表已加密', valid=False)
        items.append(item)
    alp.feedback(items)
Пример #19
0
def do_feedback():
    args = alp.args()
    path = args[0]
    feedback = []
    for n, color in COLORS.items():
        icon = os.path.join(alp.local(), "icons", "{0}.png".format(color))
        feedback.append(
            I(title=color,
              subtitle=u"Set Finder label to {0}".format(color),
              icon=icon,
              valid=True,
              arg=u"\"{0}\" \"{1}\"".format(path, n)))
    alp.feedback(feedback)
Пример #20
0
def do_feedback():
    args = alp.args()
    downloads = find_downloads()
    downloads = sorted(downloads, key=lambda x: x[2], reverse=True)

    def format_results(dl):
        title = dl[1]
        passed = time.time() - dl[2]

        if passed >= 86400:
            mod = passed % 86400
            t = (passed - mod) / 86400
            s = "" if t == 1 else "s"
            tstr = "{0} day{1}".format(int(t), s)
        elif passed >= 3600:
            mod = passed % 3600
            t = (passed - mod) / 3600
            s = "" if t == 1 else "s"
            tstr = "{0} hour{1}".format(int(t), s)
        elif passed >= 60:
            mod = passed % 60
            t = (passed - mod) / 60
            s = "" if t == 1 else "s"
            tstr = "{0} minute{1}".format(int(t), s)
        else:
            s = "" if passed == 1 else "s"
            tstr = "{0} second{1}".format(int(passed), s)

        subtitle = "Downloaded: {0} ago. Color: {1}. Tags: {2}.".format(
            tstr, dl[3], dl[4])
        return alp.Item(title=title,
                        subtitle=subtitle,
                        icon=dl[0],
                        fileIcon=True,
                        valid=True,
                        arg=dl[0])

    feedback = []
    if args[0] == "":
        for dl in downloads:
            item = format_results(dl)
            feedback.append(item)
    else:
        results = alp.fuzzy_search(
            args[0], downloads, key=lambda x: u"{0} - {1}".format(x[1], x[4]))
        for r in results:
            item = format_results(r)
            feedback.append(item)
    alp.feedback(feedback)
Пример #21
0
def iTunesSearch():
    q = alp.args()[0]

    items = map(lambda x: resultParse(x), search_for(q))

    results = []
    default_search = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?" + urllib.urlencode({"term": q})
    results.append(I(title="Search in iTunes", subtitle="Open iTunes Store and search for \"{0}\"".format(q),
                        arg=default_search, valid=True))
    if len(items):
        for anItem in items:
            results.append(I(**anItem))
    else:
        results.append(I(title="No Results", subtitle="Your search did not return any results", valid=False))

    alp.feedback(results)
Пример #22
0
def tag(tags):
    url = subprocess.check_output('pbpaste')

    # borrow from django
    regex = re.compile(
            r'^(?:http|ftp)s?://' # http:// or https://
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
            r'localhost|' #localhost...
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
            r'(?::\d+)?' # optional port
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    if re.match(regex, url):
        description = alp.Item(title="Tag " + " ".join(tags), subtitle=url, valid=True, arg=" ".join(tags))
        alp.feedback(description)
    else:
        notice = alp.Item(title="Please Copy URL to Clipboard", valid=False)
        alp.feedback(notice)
Пример #23
0
def tag(tags):
    url = subprocess.check_output('pbpaste')

    # borrow from django
    regex = re.compile(
            r'^(?:http|ftp)s?://' # http:// or https://
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
            r'localhost|' #localhost...
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
            r'(?::\d+)?' # optional port
            r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    if re.match(regex, url):
        description = alp.Item(title="Tag " + " ".join(tags), subtitle=url, valid=True, arg=" ".join(tags))
        alp.feedback(description)
    else:
        notice = alp.Item(title="Please Copy URL to Clipboard", valid=False)
        alp.feedback(notice)
Пример #24
0
def list_accounts():

    files = os.listdir(path)
    items = []
    for f in files:
        if f.startswith('cn') and os.path.isdir(path + f) and os.path.isfile(
                path + f + '/db/contact.db'):
            item = alp.Item(title=u'设置帐号 \'%s\'' % f,
                            subtitle='',
                            arg=f,
                            valid=True)
            items.append(item)
    if items.count == 0:
        item = alp.Item(title=u'没有找到可用帐号',
                        subtitle=u'尚未登录过旺旺或者已登录旺旺好友列表已加密',
                        valid=False)
        items.append(item)
    alp.feedback(items)
Пример #25
0
def do_feedback():
    args = alp.args()
    downloads = find_downloads()
    downloads = sorted(downloads, key=lambda x: x[2], reverse=True)

    def format_results(dl):
        title = dl[1]
        passed = time.time() - dl[2]
        
        if passed >= 86400:
            mod = passed % 86400
            t = (passed - mod) / 86400
            s = "" if t == 1 else "s"
            tstr = "{0} day{1}".format(int(t), s)
        elif passed >= 3600:
            mod = passed % 3600
            t = (passed - mod) / 3600
            s = "" if t == 1 else "s"
            tstr = "{0} hour{1}".format(int(t), s)
        elif passed >= 60:
            mod = passed % 60
            t = (passed - mod) / 60
            s = "" if t == 1 else "s"
            tstr = "{0} minute{1}".format(int(t), s)
        else:
            s = "" if passed == 1 else "s"
            tstr = "{0} second{1}".format(int(passed), s)

        subtitle = "Downloaded: {0} ago. Color: {1}. Tags: {2}.".format(tstr, dl[3], dl[4])
        return alp.Item(title=title, subtitle=subtitle, icon=dl[0], fileIcon=True,
                        valid=True, arg=dl[0])

    feedback = []
    if args[0] == "":
        for dl in downloads:
            item = format_results(dl)
            feedback.append(item)
    else:
        results = alp.fuzzy_search(args[0], downloads, key=lambda x: u"{0} - {1}".format(x[1], x[4]))
        for r in results:
            item = format_results(r)
            feedback.append(item)
    alp.feedback(feedback)
Пример #26
0
def main():
    routes = alp.jsonLoad(alp.local('routes.json'), [])

    alp_args = alp.args()
    if len(alp_args) > 0:
        search = alp.args()[0].lower()
        routes = filter(lambda route: search in route.get('title').lower() or search in route.get('description', '').lower(), routes)

    items = map(item, routes)
    return alp.feedback(items)
Пример #27
0
def ads_open(q=""):
    import alp
    import urllib

    item = alp.Item(
        title="Open ADS for search",
        subtitle="Search on the ADS website for '" + q + "'",
        arg=encode_arguments(type='url',
                             value="http://ui.adsabs.harvard.edu/#search/" +
                             urllib.urlencode({'q': q})))

    return alp.feedback(item)
Пример #28
0
def main():
    routes = alp.jsonLoad(alp.local('routes.json'), [])

    alp_args = alp.args()
    if len(alp_args) > 0:
        search = alp.args()[0].lower()
        routes = filter(
            lambda route: search in route.get('title').lower() or search in
            route.get('description', '').lower(), routes)

    items = map(item, routes)
    return alp.feedback(items)
Пример #29
0
def local_search(search=""):
    """Performs a local search"""

    import os

    words       = search.lower().split(" ")
    ldir        = get_local_dir()
    files       = []
    fileitems   = []

    # Get all files in the local directory.
    for (dirpath, dirnames, filenames) in os.walk(ldir):
        files.extend(filenames)
        break
    # Loop over them to fill 'fileitems'.
    for f in files:
        filename, ext = os.path.splitext(f)
        filenamelower = filename.lower()
        if ext != ".pdf":
            continue
        # Search for the words in the input query
        match = True
        for word in words:
            if word not in filenamelower:
                match = False
                break
        if not match:
            continue
        # Make the alp item.
        filenamesplit = filename.split(" - ")
        fileitems.append(alp.Item(
            title    = filenamesplit[1],
            subtitle = filenamesplit[0],
            type     = 'file',
            icon     = "com.adobe.pdf",
            fileType = True,
            uid      = filename,
            arg      = encode_arguments(
                type    = "open",
                value   = os.path.join(ldir, f)
            )
        ))
    # Lastly, append an alp item that searches INSPIRE
    fileitems.append(alp.Item(
        title    = "Search INSPIRE for '" + search + "'",
        subtitle = "Searches the INSPIRE database",
        arg      = encode_arguments(
            type    = "inspiresearch",
            value   = search 
        )
    ))
    # And return.
    return alp.feedback(fileitems)
Пример #30
0
def search(tags):
    conn = sqlite3.connect(alp.local(join=DB))
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    rows = []

    for tag in tags:
        c.execute('''
            SELECT DISTINCT urls.* FROM urls
            JOIN tags ON tags.url_id = urls.id
            WHERE tags.tag LIKE ?
        ''', ('%'+tag+'%', ))

        rows += c.fetchall()


    items = []
    for row in rows:
        icon = row['icon']

        sha224 = hashlib.sha224(icon).hexdigest()
        icon_path = alp.local(join=os.path.join('icon_cache', sha224))

        if not os.path.exists(icon_path):
            with open(icon_path, 'w') as f:
                f.write(icon)

        c.execute('SELECT * FROM tags WHERE url_id = ?', (row['id'],))
        url_tags = c.fetchall()
        item = alp.Item(
                title=row['url'],
                subtitle=" ".join(map(lambda tag: tag['tag'], url_tags)),
                valid=True,
                icon=icon_path,
                arg=row['url']
                )
        items.append(item)

    alp.feedback(items)
Пример #31
0
def query(keyword):

    account = get_account()
    if not account:
        item = alp.Item(title=u'您还没有设置旺旺帐号', subtitle=u'请先使用\'setww\'命令设置旺旺帐号', valid=False)
        alp.feedback([item])
        return
    db = path + account + '/db/contact.db'
    if not os.path.exists(db):
        item = alp.Item(title=u'查询失败', subtitle=u'好友列表不存在或已加密,您可以尝试setww重新选择其他帐号', valid=False)
        alp.feedback([item])
        return
    items = []
    conn = sqlite3.connect(db)
    c = conn.cursor()
    keyword = '%%%s%%' % keyword.strip()
    try:
        c.execute('''SELECT OID,* FROM contact WHERE nickname_pinyin LIKE ? LIMIT 10''', (keyword, ))
        result = c.fetchall()
    except:
        result = []
        item = alp.Item(title=u'暂不支持中文查询,请使用拼音', valid=False)
        items.append(item)
    for index, value in enumerate(result):
        userid = value[2]
        nickname = value[4]
        signature = value[5]
        pinyin = value[6]
        item = alp.Item(title=u'旺旺 \'%s\'' % nickname, subtitle=signature, uid=str(
            index+1), icon='%s%s/CustomHeadImages/%s.jpg' % (path, account, userid), arg='aliim:sendmsg?touid=%s' % userid, valid=True, autocomplete=pinyin)
        items.append(item)
    if len(items) == 0:
        item = alp.Item(title=u'没有查找到匹配好友', valid=False)
        items.append(item)
    alp.feedback(items)
Пример #32
0
def main():
    """
    Everything dispatches from this function.
    """
    global settings

    # Create default settings if necessary
    createSettingsFile()

    # Read settings
    settings = alp.readPlist(SETTINGS_PATH)

    # Process the settings
    if settings["firstRun"] == "true":
        udpateDatabaseFromKippt()
        settings["firstRun"] = "false"
        settings["credentialsChanged"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)
    elif settings["credentialsChanged"] == "true":
        udpateDatabaseFromKippt()
        settings["credentialsChanged"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)
    elif settings["updateClips"] == "true":
        udpateDatabaseFromKippt()
        settings["updateClips"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)

    # Get the keywords
    args = alp.args()
    if len(args) < 1:
        return

    # Execute the search
    items = search(args)
    if items is not None:
        alp.feedback(items)
    else:
        print "No items found"
Пример #33
0
def main():
    """
    Everything dispatches from this function.
    """
    global settings

    # Create default settings if necessary
    createSettingsFile()

    # Read settings
    settings = alp.readPlist(SETTINGS_PATH)

    # Process the settings
    if settings["firstRun"] == "true":
        udpateDatabaseFromKippt()
        settings["firstRun"] = "false"
        settings["credentialsChanged"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)
    elif settings["credentialsChanged"] == "true":
        udpateDatabaseFromKippt()
        settings["credentialsChanged"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)
    elif settings["updateClips"] == "true":
        udpateDatabaseFromKippt()
        settings["updateClips"] = "false"
        alp.writePlist(settings, SETTINGS_PATH)

    # Get the keywords
    args = alp.args()
    if len(args) < 1:
        return

    # Execute the search
    items = search(args)
    if items is not None:
        alp.feedback(items)
    else:
        print "No items found"
Пример #34
0
def main():
    query = ' '.join(alp.args()).strip()
    items = []
    password = show(query)
    if password is not None:
        items.append(
            Item(title=password,
                 subtitle='Press enter to copy',
                 valid=True,
                 arg=password))
        items.append(
            Item(title='Update: %s' % query,
                 subtitle='Randomly generate a 32 character password',
                 valid=True,
                 arg='pass generate --in-place --no-symbols %s 32' % query))
        items.append(
            Item(title='Remove: %s' % query,
                 subtitle='Delete this password from the store',
                 valid=True,
                 arg='pass rm --force %s' % query))
    else:
        for m in find(query):
            try:
                subtitle, title = m.rsplit('/', 1)
            except:
                title = m
                subtitle = ''
            items.append(
                Item(title=title,
                     subtitle=subtitle,
                     valid=False,
                     autocomplete=m))
        items.append(
            Item(title='Insert: %s' % query,
                 subtitle='Randomly generate a 32 character password',
                 valid=True,
                 arg='pass generate --no-symbols %s 32' % query))
    alp.feedback(items)
Пример #35
0
def query(keyword):

    keyword = '%' + keyword.strip() + '%'
    c.execute('''SELECT OID,* FROM jsapi WHERE name LIKE ? LIMIT 10''',
              (keyword, ))

    nameMatch = c.fetchall()

    c.execute('''SELECT OID,* FROM jsapi WHERE t2 LIKE ? LIMIT 10''',
              (keyword, ))
    t2Match = c.fetchall()

    allMatch = nameMatch + t2Match
    allMatch = uniMatch(allMatch)[0:10]

    items = []

    if hasNewVersion():
        item = alp.Item(title="The new js api workflow is avaliable",
                        icon="update-icon.png",
                        subtitle="please choose this to download",
                        uid="0",
                        valid=True,
                        autocomplete="",
                        arg="https://github.com/allenm/jsapi-workflow")
        items.append(item)

    for index, match in enumerate(allMatch):
        title = match[3] + ' (' + match[2] + ')'
        item = alp.Item(title=title,
                        subtitle=match[4],
                        uid=str(index + 1),
                        valid=True,
                        autocomplete=match[3],
                        arg=match[5])
        items.append(item)

    alp.feedback(items)
Пример #36
0
def main():
    query = ' '.join(alp.args()).strip()
    items = []
    password = show(query)
    if password is not None:
        items.append(Item(
            title=password,
            subtitle='Press enter to copy',
            valid=True,
            arg=password))
        items.append(Item(
            title='Update: %s' % query,
            subtitle='Randomly generate a 32 character password',
            valid=True,
            arg='pass generate --in-place --no-symbols %s 32' % query))
        items.append(Item(
            title='Remove: %s' % query,
            subtitle='Delete this password from the store',
            valid=True,
            arg='pass rm --force %s' % query))
    else:
        for m in find(query):
            try:
                subtitle, title = m.rsplit('/', 1)
            except:
                title = m
                subtitle = ''
            items.append(Item(
                title=title,
                subtitle=subtitle,
                valid=False,
                autocomplete=m))
        items.append(Item(
            title='Insert: %s' % query,
            subtitle='Randomly generate a 32 character password',
            valid=True,
            arg='pass generate --no-symbols %s 32' % query))
    alp.feedback(items)
Пример #37
0
def fetchTimers():
    if tkn is None:
        return 'Please set Token via \'tgl token <TOKEN>\''
    else:
        timers = requests.get('https://www.toggl.com/api/v8/time_entries', auth=(tkn, 'api_token'))
        if timers.status_code == 200:
            items = []
            for timer in timers.json:
                subtitle = 'No longer running'
                if timer['duration'] < 0:
                    subtitle = 'Currently running'
                items.append(alp.Item(title=timer['description'], subtitle=subtitle, valid=timer['duration'] >= 0, arg='start %s' % timer['description']))

            return alp.feedback(items)
Пример #38
0
def iTunesSearch():
    q = alp.args()[0]

    items = map(lambda x: resultParse(x), search_for(q))

    results = []
    default_search = "macappstore://ax.search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?" + urllib.urlencode(
        {"q": q})
    results.append(
        I(title="Search in App Store",
          subtitle="Open Mac App Store and search for \"{0}\"".format(q),
          arg=default_search,
          valid=True))
    if len(items):
        for anItem in items:
            results.append(I(**anItem))
    else:
        results.append(
            I(title="No Results",
              subtitle="Your search did not return any results",
              valid=False))

    alp.feedback(results)
Пример #39
0
def iTunesSearch():
    q = alp.args()[0]

    items = map(lambda x: resultParse(x), search_for(q))

    feedback = []
    default_search = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search?" + urllib.urlencode(
        {"term": q})
    feedback.append(
        I(title="Search in iTunes",
          subtitle="Open iTunes Store and search for \"{0}\"".format(q),
          arg=default_search,
          valid=True))
    if len(items):
        for anItem in items:
            feedback.append(I(**anItem))
    else:
        feedback.append(
            I(title="No Results",
              subtitle="Your search did not return any results",
              valid=False))

    alp.feedback(feedback)
Пример #40
0
def output_feedbackItems(tasks, top=True):
    # --name --no-id  --size --status --progress --download-url --n
    # n: t['#']
    # name: t['name'].encode(default_encoding)
    # size: from lixian_util import format_size
    #       format_size(t['size'])
    # progress: t['progress']
    # download-url: t['xunlei_url']

    items = []
    for i, t in enumerate(tasks):
        # [Task_Name: progress]
        isBT = True if t['type'] == 'bt' else False
        seqNum = str(t['#'] if top else t.get('index', t['id']))
        feedTitle = ' '.join([seqNum, t['name']])
        subTitles = [format_size(t['size']), t['status_text'], t['progress']]
        feedsubTitle = ' '.join(str(subT) for subT in subTitles)
        d_url = t['xunlei_url']
        items.append(
            alp_item(
                title=feedTitle,
                subtitle=feedsubTitle,
                arg=(str(t['#']) + '/' if top and isBT else d_url),
                # autocomplete=(str(t['#']) + '/@' if top and isBT else ''),
                fileType=True if top and isBT else False,
                icon='org.bittorrent.torrent' if top and isBT else 'icon.png',
                valid=True))

    if len(items):
        alp.feedback(items)
    else:
        alp.feedback(
            alp_item(title="没有找到",
                     subtitle="修改[关键字],或使用 [ID]来检索",
                     valid=False,
                     fileIcon=True,
                     icon="/System/Library/CoreServices/Problem Reporter.app"))
Пример #41
0
def doSearch():
    q = sys.argv[1:]
    q = ' '.join(q)

    requestList = [
        "Operation=ItemSearch", "SearchIndex=KindleStore", "Sort=relevancerank"
    ]
    # requestList.append(urllib.urlencode({"Keywords": q}))
    # kw = q.replace(" ", ",")
    # requestList.append("Keywords=%s" % kw)

    requestDict = encodeRequestList(requestList, "ItemIds", keywords=q)

    searchRequest = alp.Request("http://webservices.amazon.com/onca/xml",
                                requestDict)
    soup = searchRequest.souper()

    resultsFeedback = []
    if soup.find("error"):
        e = soup.error.message.string
        resultsFeedback.append(I(title="Bad Request", subtitle=e, valid=False))

    else:
        asins = soup.find_all("asin")

        for asin in asins:
            aResult = getData(asin.string)
            resultsFeedback.append(I(**aResult))

    if len(resultsFeedback) == 0:
        alp.feedback(
            I(title="No Results",
              subtitle="Your query returned 0 results.",
              valid=False))
    else:
        alp.feedback(resultsFeedback)
Пример #42
0
def local_search(search=""):
    """Performs a local search"""

    import os

    words = search.lower().split(" ")
    ldir = get_local_dir()
    files = []
    fileitems = []

    # Get all files in the local directory.
    for (dirpath, dirnames, filenames) in os.walk(ldir):
        files.extend(filenames)
        break
    # Loop over them to fill 'fileitems'.
    for f in files:
        filename, ext = os.path.splitext(f)
        filenamelower = filename.lower()
        if ext != ".pdf":
            continue
        # Search for the words in the input query
        match = True
        for word in words:
            if word not in filenamelower:
                match = False
                break
        if not match:
            continue
        # Make the alp item.
        filenamesplit = filename.split(" - ")
        fileitems.append(
            alp.Item(title=filenamesplit[1],
                     subtitle=filenamesplit[0],
                     type='file',
                     icon="com.adobe.pdf",
                     fileType=True,
                     uid=filename,
                     arg=encode_arguments(type="open",
                                          value=os.path.join(ldir, f))))
    # Lastly, append an alp item that searches INSPIRE
    fileitems.append(
        alp.Item(title="Search INSPIRE for '" + search + "'",
                 subtitle="Searches the INSPIRE database",
                 arg=encode_arguments(type="inspiresearch", value=search)))
    # And return.
    return alp.feedback(fileitems)
Пример #43
0
def ads_main(q=""):
    """Refers to ads search."""

    search = q.decode('utf-8')
    num_delims = search.count(alfred_delim)
    searchsplit = search.split(alfred_delim)

    # If the user hasn't typed anything, give some instructions and the
    # option to open the settings menu.
    if (get_token_setting() == ''):
        result = [
            alp.Item(title="No ADS API token",
                     subtitle="Please set API token by ADS setting",
                     valid="no",
                     autocomplete="settings" + alfred_delim)
        ]

    if search.strip() == "":
        result = [
            alp.Item(title="Search ADS",
                     subtitle="Begin typing to search ADS",
                     valid="no",
                     autocomplete=""),
            alp.Item(title="Settings",
                     subtitle="Change ADS's settings",
                     valid="no",
                     autocomplete="settings" + alfred_delim)
        ]
    # Settings menu.
    elif searchsplit[0] == "settings":
        result = settings_menu(searchsplit[1:])
    # If the search has no delimiters the user is still typing the query:
    elif num_delims == 0:
        result = typing_ads_menu(searchsplit[0])
    # Has the string one delimiter? Then perform a regular Inspire search.
    elif num_delims == 1:
        result = ads_search(searchsplit[0].strip())
    # Are there two delimiters? Then it's a context menu.
    elif num_delims == 2:
        result = context_ads_menu(searchsplit[1], searchsplit[0])
    # Three delimiters? Then it's an author search menu.
    elif num_delims == 3:
        result = author_ads_menu(searchsplit[1], searchsplit[2])

    return alp.feedback(result)
Пример #44
0
def fetchTimers():
    if tkn is None:
        return 'Please set Token via \'tgl token <TOKEN>\''
    else:
        timers = requests.get('https://www.toggl.com/api/v8/time_entries',
                              auth=(tkn, 'api_token'))
        if timers.status_code == 200:
            items = []
            for timer in timers.json:
                subtitle = 'No longer running'
                if timer['duration'] < 0:
                    subtitle = 'Currently running'
                items.append(
                    alp.Item(title=timer['description'],
                             subtitle=subtitle,
                             valid=timer['duration'] >= 0,
                             arg='start %s' % timer['description']))

            return alp.feedback(items)
Пример #45
0
def main(q=""):
    """Refers to one of the main methods."""

    search      = q.decode('utf-8')
    num_delims  = search.count(alfred_delim)
    searchsplit = search.split(alfred_delim)

    # If the user hasn't typed anything, give some instructions and the
    # option to open the settings menu.
    if search.strip() == "":
        result = [
            alp.Item(
                title        = "Search INSPIRE",
                subtitle     = "Begin typing to search INSPIRE",
                valid        = "no",
                autocomplete = ""
            ),
            alp.Item(
                title        = "Settings",
                subtitle     = "Change ainspire's settings",
                valid        = "no",
                autocomplete = "settings" + alfred_delim
            )
        ]
    # Settings menu.
    elif searchsplit[0] == "settings":
        result = settings_menu(searchsplit[1:])
    # If the search has no delimiters the user is still typing the query:
    elif num_delims == 0:
        result = typing_menu(searchsplit[0])
    # Has the string one delimiter? Then perform a regular Inspire search.
    elif num_delims == 1:
        result = inspire_search(searchsplit[0].strip())
    # Are there two delimiters? Then it's a context menu.
    elif num_delims == 2:
        result = context_menu(searchsplit[1],searchsplit[0])
    # Three delimiters? Then it's an author search menu.
    elif num_delims == 3:
        result = author_menu(searchsplit[2])

    return alp.feedback(result)
Пример #46
0
def query(keyword):

    account = get_account()
    if not account:
        item = alp.Item(title=u'您还没有设置旺旺帐号',
                        subtitle=u'请先使用\'setww\'命令设置旺旺帐号',
                        valid=False)
        alp.feedback([item])
        return
    db = path + account + '/db/contact.db'
    if not os.path.exists(db):
        item = alp.Item(title=u'查询失败',
                        subtitle=u'好友列表不存在或已加密,您可以尝试setww重新选择其他帐号',
                        valid=False)
        alp.feedback([item])
        return
    items = []
    conn = sqlite3.connect(db)
    c = conn.cursor()
    keyword = '%%%s%%' % keyword.strip()
    try:
        c.execute(
            '''SELECT OID,* FROM contact WHERE nickname_pinyin LIKE ? LIMIT 10''',
            (keyword, ))
        result = c.fetchall()
    except:
        result = []
        item = alp.Item(title=u'暂不支持中文查询,请使用拼音', valid=False)
        items.append(item)
    for index, value in enumerate(result):
        userid = value[2]
        nickname = value[4]
        signature = value[5]
        pinyin = value[6]
        item = alp.Item(title=u'旺旺 \'%s\'' % nickname,
                        subtitle=signature,
                        uid=str(index + 1),
                        icon='%s%s/CustomHeadImages/%s.jpg' %
                        (path, account, userid),
                        arg='aliim:sendmsg?touid=%s' % userid,
                        valid=True,
                        autocomplete=pinyin)
        items.append(item)
    if len(items) == 0:
        item = alp.Item(title=u'没有查找到匹配好友', valid=False)
        items.append(item)
    alp.feedback(items)
Пример #47
0
def find_projects():
    q = alp.args()[0] if len(alp.args()) else ""

    if os.path.exists("/Applications/Sublime Text.app"):
        session_path = "~/Library/Application Support/Sublime Text 3/Local/Session.sublime_session"
        session_path = os.path.expanduser(session_path)
    elif os.path.exists("/Applications/Sublime Text 2.app"):
        session_path = "~/Library/Application Support/Sublime Text 2/Settings/Session.sublime_session"
        session_path = os.path.expanduser(session_path)
    else:
        alp.feedback(I(title="No Sublime Installation",
                        subtitle="Sublime Text 2 or 3 is required.",
                        valid=False))
        return

    with codecs.open(session_path, "r", "utf-8") as f:
        projects = json.load(f)["workspaces"]["recent_workspaces"]

    projectNames = []
    for project in projects:
        projPath = project
        (projPath, projFile) = os.path.split(projPath)
        (projTitle, _) = projFile.rsplit(".", 1)
        projPath = os.path.join(projPath, projTitle + ".sublime-project")
        projectNames.append((projPath, projTitle))

    items = []
    for path, title in projectNames:
        if re.match("(?i).*%s.*" % q, path) or re.match("(?i).*%s.*" % q, title) or len(q) == 0:
            items.append(I(title=title,
                            subtitle=path,
                            arg=path,
                            valid=True,
                            uid=path))

    if len(items):
        alp.feedback(items)
    else:
        alp.feedback(I(title="No Matches",
                        subtitle="No recent projects matched your query.",
                        valid=False))
Пример #48
0
def find_projects():
    q = alp.args()[0] if len(alp.args()) else ""

    if os.path.exists("/Applications/Sublime Text.app"):
        session_path = "~/Library/Application Support/Sublime Text 3/Local/Session.sublime_session"
        session_path = os.path.expanduser(session_path)
    elif os.path.exists("/Applications/Sublime Text 2.app"):
        session_path = "~/Library/Application Support/Sublime Text 2/Settings/Session.sublime_session"
        session_path = os.path.expanduser(session_path)
    else:
        alp.feedback(
            I(title="No Sublime Installation",
              subtitle="Sublime Text 2 or 3 is required.",
              valid=False))
        return

    with codecs.open(session_path, "r", "utf-8") as f:
        projects = json.load(f)["workspaces"]["recent_workspaces"]

    projectNames = []
    for project in projects:
        projPath = project
        (projPath, projFile) = os.path.split(projPath)
        (projTitle, _) = projFile.rsplit(".", 1)
        projPath = os.path.join(projPath, projTitle + ".sublime-project")
        projectNames.append((projPath, projTitle))

    items = []
    for path, title in projectNames:
        if re.match("(?i).*%s.*" % q, path) or re.match(
                "(?i).*%s.*" % q, title) or len(q) == 0:
            items.append(
                I(title=title, subtitle=path, arg=path, valid=True, uid=path))

    if len(items):
        alp.feedback(items)
    else:
        alp.feedback(
            I(title="No Matches",
              subtitle="No recent projects matched your query.",
              valid=False))
Пример #49
0
def print_feedback(results):
    updatables = []
    all_configured = []
    for r in results:
        try:
            j = r['json']
            d = r['candidict']
            l = r['local']
        except Exception as e:
            alp.log("{0} threw exception {1}".format(d['name'], e))
            alp.log(r)
        try:
            version = float(j['version'])
            download_uri = j['download_url']
            description = j['description']
        except Exception as e:
            alp.log("{0} failed with error: {1}".format(d['name'], e))
            continue
        try:
            lv = l['version']
        except Exception as e:
            alp.log("{0} failed with malformed json: {1}".format(d['name'], e))
            alp.log(d)
            continue
        if lv < version:
            updatables.append(
                dict(name=d['name'],
                     description=description,
                     icon=d['icon'],
                     download=download_uri,
                     path=d['path'],
                     version=version))
        all_configured.append(
            dict(name=d['name'],
                 description=description,
                 icon=d['icon'],
                 download=download_uri,
                 path=d['path'],
                 version=version,
                 local_d=d['description']))

    items = []
    q = alp.args()
    if not len(q) or (len(q) == 1 and q[0] == "|force|"):
        if not len(updatables):
            alp.feedback(
                I(title="No Updates Available",
                  subtitle="All your workflows are up-to-date.",
                  valid=False))
            return
        update_all = '"update-all"'
        for updict in updatables:
            update_all += " \"{0}>{1}>{2}\"".format(updict['name'],
                                                    updict['path'],
                                                    updict['download'])
        n = len(updatables)
        upd_sib = "s" if n != 1 else ""
        items.append(
            I(title="Update All",
              subtitle="Download {0} update{s}".format(n, s=upd_sib),
              valid=True,
              arg=update_all))
        for up in updatables:
            items.append(
                I(title=up['name'],
                  subtitle=u"v{0}\u2014{1}".format(up['version'],
                                                   up['description']),
                  icon=up['icon'],
                  arg=u"\"update\" \"{0}>{1}>{2}\"".format(
                      up['name'], up['path'], up['download']),
                  valid=True))
    elif len(q) == 1 and q[0] == "|all|":
        if not len(all_configured):
            alp.feedback(
                I(title="No Compatible Workflows",
                  subtitle="No Alleyoop workflows detected",
                  valid=False))
            return
        for c in all_configured:
            items.append(
                I(title=c['name'],
                  subtitle=u"v{0}\u2014{1}".format(c['version'], c['local_d']),
                  icon=c['icon'],
                  valid=False))
    else:
        if q[0] != "|all|" and q[0] != "|force|":
            if not len(results):
                alp.log("'oop' may be broken.")
                alp.log("len(all_configured)=0")
                alp.log("q='{0}'".format(q))
                alp.log("updatables='{0}'".format(updatables))
                alp.log("results='{0}'".format(results))
                alp.feedback(
                    I(title="Error",
                      subtitle=
                      "No compatible workflows were found. See debug.log for info.",
                      valid=False))
                return

            search = q[0]
            results = alp.fuzzy_search(
                search,
                updatables,
                key=lambda x: u"{0} - {1}".format(x['name'], x['local_d']))
            for r in results:
                items.append(
                    I(title=r['name'],
                      subtitle=u"v{0}\u2014{1}".format(r['version'],
                                                       r['description']),
                      icon=r['icon'],
                      arg="\"update\" \"{0}>{1}>{2}".format(
                          r['name'], r['path'], r['download']),
                      valid=True))
        else:
            if not len(all_configured):
                alp.log("'oop!' may be broken.")
                alp.log("len(all_configured)=0")
                alp.log("q='{0}'".format(q))
                alp.log("updatables='{0}'".format(updatables))
                alp.log("results='{0}'".format(results))
                alp.feedback(
                    I(title="Error",
                      subtitle=
                      "No compatible workflows were found. See debug.log for info.",
                      valid=False))
                return

            search = q[1]
            results = alp.fuzzy_search(
                search,
                all_configured,
                key=lambda x: u"{0} - {1}".format(x['name'], x['local_d']))
            for r in results:
                items.append(
                    I(title=r['name'],
                      subtitle=u"v{0}\u2014{1}".format(r['version'],
                                                       r['local_d']),
                      valid=False))

    if not len(items):
        items.append(
            I(title="No Results",
              subtitle="Your query did not return any results.",
              valid=False))

    alp.feedback(items)
Пример #50
0
                  uid="decimal",
                  valid=True,
                  arg=str(decimal),
                  icon="icons/decimal.png")
d = alp.Item(**decimalDic)

# calculate octal number
octal = oct(decimal)[1:]
# create associative array and create xml from it
octalDic = dict(title=str(octal),
                subtitle="Octal",
                uid="octal",
                valid=True,
                arg=str(octal),
                icon="icons/octal.png")
o = alp.Item(**octalDic)

# calculate hex number
hexadec = hex(decimal)[2:]
# create associative array and create xml from it
hexDic = dict(title=str(hexadec),
              subtitle="Hexadecimal",
              uid="hex",
              valid=True,
              arg=str(hexadec),
              icon="icons/hex.png")
h = alp.Item(**hexDic)

itemsList = [d, o, h]
alp.feedback(itemsList)
Пример #51
0
def do_feedback():
    storedNames = alp.jsonLoad("files.json", default=[])
    s = alp.Settings()
    defaultExt = s.get("extension", ".txt")

    args = alp.args()[0]
    args = args.split(" ")
    
    if len(args) == 1 and args[0] == "":
        empty = []
        
        if len(storedNames) > 0:
            for name in storedNames:
                empty.append(I(uid=name, valid=True, autocomplete=name, title=name,
                            subtitle="Create {0} in frontmost Finder window.".format(name),
                            arg="touch \"{0}\"".format(name)))

        empty.append(I(title="Add Filename", subtitle="Store a filename for faster access",
                        autocomplete="|add| ", valid=False))
        empty.append(I(title="Add Path", subtitle="Store a path for use with 'touch filename at'",
                        autocomplete="|path| ", valid=False))

        alp.feedback(empty)

    elif args[0] == "|add|":
        if len(args) >= 2:
            name = " ".join(args[1:])
        else:
            name = ""
        if not "." in name:
            name += defaultExt

        alp.feedback(I(title="Store Filename", subtitle="Store {0} for faster access".format(name),
                        arg="add \"{0}\"".format(name), valid=True))

    elif args[0] == "|path|":
        if len(args) >= 2:
            name = " ".join(args[1:])
        else:
            name = ""

        alp.feedback(I(title=name, subtitle="Store {0} as a location for new files".format(name),
                        arg="path \"{0}\"".format(name), valid=True))

    elif "at" in args:
        i = args.index("at")
        name = args[:i]
        name = " ".join(name)
        if not "." in name:
            name += defaultExt

        feedback = []

        storedPaths = alp.jsonLoad("paths.json", default=[])
        if len(storedPaths) > 0:
            for path in storedPaths:
                (_, tail) = os.path.split(path)
                touch_path = os.path.join(path, name)
                feedback.append(I(title="...{0}/{1}".format(tail, name),
                                    subtitle="{0}{1}".format(path, name),
                                    arg="at \"{0}\"".format(touch_path),
                                    valid=True))
        else:
            feedback.append(I(title="No saved paths!", subtitle="Store a path to use this feature.",
                                valid=False))

        alp.feedback(feedback)

    else:
        name = " ".join(args)
        if not "." in name:
            name += defaultExt

        alp.feedback(I(title=name, subtitle="Create {0} in frontmost finder window.".format(name),
                        valid=True, arg="touch \"{0}\"".format(name), uid=name))
Пример #52
0
def list_projects(kw=None):
    feedback = []
    for project in filter_projects(kw):
        feedback.append(project['feedback'])
    return alp.feedback(feedback)
Пример #53
0
def do_feedback():
    storedNames = alp.jsonLoad("files.json", default=[])
    s = alp.Settings()
    defaultExt = s.get("extension", ".txt")

    args = alp.args()[0]
    args = args.split(" ")

    if len(args) == 1 and args[0] == "":
        empty = []

        if len(storedNames) > 0:
            for name in storedNames:
                empty.append(
                    I(uid=name,
                      valid=True,
                      autocomplete=name,
                      title=name,
                      subtitle="Create {0} in frontmost Finder window.".format(
                          name),
                      arg="touch \"{0}\"".format(name)))

        empty.append(
            I(title="Add Filename",
              subtitle="Store a filename for faster access",
              autocomplete="|add| ",
              valid=False))
        empty.append(
            I(title="Add Path",
              subtitle="Store a path for use with 'touch filename at'",
              autocomplete="|path| ",
              valid=False))

        alp.feedback(empty)

    elif args[0] == "|add|":
        if len(args) >= 2:
            name = " ".join(args[1:])
        else:
            name = ""
        if not "." in name:
            name += defaultExt

        alp.feedback(
            I(title="Store Filename",
              subtitle="Store {0} for faster access".format(name),
              arg="add \"{0}\"".format(name),
              valid=True))

    elif args[0] == "|path|":
        if len(args) >= 2:
            name = " ".join(args[1:])
        else:
            name = ""

        alp.feedback(
            I(title=name,
              subtitle="Store {0} as a location for new files".format(name),
              arg="path \"{0}\"".format(name),
              valid=True))

    elif "at" in args:
        i = args.index("at")
        name = args[:i]
        name = " ".join(name)
        if not "." in name:
            name += defaultExt

        feedback = []

        storedPaths = alp.jsonLoad("paths.json", default=[])
        if len(storedPaths) > 0:
            for path in storedPaths:
                (_, tail) = os.path.split(path)
                touch_path = os.path.join(path, name)
                feedback.append(
                    I(title="...{0}/{1}".format(tail, name),
                      subtitle="{0}{1}".format(path, name),
                      arg="at \"{0}\"".format(touch_path),
                      valid=True))
        else:
            feedback.append(
                I(title="No saved paths!",
                  subtitle="Store a path to use this feature.",
                  valid=False))

        alp.feedback(feedback)

    else:
        name = " ".join(args)
        if not "." in name:
            name += defaultExt

        alp.feedback(
            I(title=name,
              subtitle="Create {0} in frontmost finder window.".format(name),
              valid=True,
              arg="touch \"{0}\"".format(name),
              uid=name))
Пример #54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import alp

pen_dict = {'title': 'Send to PDFPen', 'subtitle': "Send current document to PDFPen's iCloud folder?", 'valid': True, 'arg': 'pdfpen', 'icon': 'pdfpen.png'}
expert_dict = {'title': 'Send to PDF Expert', 'subtitle': "Send current document to PDF Expert's iCloud folder?", 'valid': True, 'arg': 'pdfexpert', 'icon': 'pdfexpert.png'}
both_dict = {'title': 'Send to Both', 'subtitle': "Send current document to both PDFPen and PDF Expert's iCloud folders?", 'valid': True, 'arg': 'both', 'icon': 'icon.png'}

pen_item = alp.Item(**pen_dict)
expert_item = alp.Item(**expert_dict)
both_item = alp.Item(**both_dict)

res_list = [pen_item, expert_item, both_item]
alp.feedback(res_list)
 
Пример #55
0
import alp
from alp import Item

query = "{query}"

item = Item(uid=alp.bundle(),
            arg='',
            valid=True,
            title=query,
            subtitle='set username for delicious',
            icon='logo.png')

alp.feedback([item])

# =========================

import os
from alp import core

query = "{query}"

infoPath = os.path.abspath("./info.plist")

plist = core.readPlist(infoPath)

plist['username'] = query

core.writePlist(plist, infoPath)
Пример #56
0
def do_feedback():
    q = alp.args()

    if len(q) and "+" in q[0][0:2]:
        to_add = q[0].split("+", 1)[1]
        if "\"" in to_add:
            to_add = to_add.replace("\"", "\\\"")
        alp.feedback(
            I(title="Add Task",
              subtitle=to_add,
              arg=u"parse \"{0}\"".format(to_add),
              valid=True))
        return

    things_data = do_things_dump()

    icons = {"list": os.path.join(alp.local(), "images", "area.png"), \
            "project": os.path.join(alp.local(), "images", "project.png"), \
            "task": os.path.join(alp.local(), "images", "check.png")}
    items = []
    if not len(q) or q[0] == "":
        for area in things_data["list"]:
            de_area = area.encode("ascii", "ignore")
            icon = os.path.join(alp.local(), "images",
                                "{0}.png".format(de_area))
            if not os.path.exists(icon):
                icon = icons["list"]
            if "\"" in area:
                clean = area.replace("\"", "\\\"")
            else:
                clean = area
            items.append(
                I(title=area,
                  arg=u"show list \"{0}\"".format(clean),
                  icon=icon,
                  uid=area,
                  valid=True))
        for project in things_data["project"]:
            if "\"" in project:
                clean = project.replace("\"", "\\\"")
            else:
                clean = project
            items.append(
                I(title=project,
                  arg=u"show project \"{0}\"".format(clean),
                  icon=icons["project"],
                  uid=project,
                  valid=True))
        for task in things_data["task"]:
            if task:
                if "\"" in task:
                    clean = task.replace("\"", "\\\"")
                else:
                    clean = task
                split_task = task.encode("ascii", "ignore").split(" ")[0]
                items.append(
                    I(title=task,
                      arg=u"show \"to do\" \"{0}\"".format(clean),
                      icon=icons["task"],
                      uid=u"task-{0}".format(split_task),
                      valid=True))
    else:
        q = q[0]
        items.append(
            I(title="Add Task",
              subtitle=q,
              arg=u"parse \"{0}\"".format(q),
              valid=True))
        for k, v in things_data.iteritems():
            things = alp.fuzzy_search(q, v)
            for thing in things:
                uid = k if k != "task" else u"task-{0}".format(
                    thing.split(" ")[0])
                icon = icons[k] if not thing in ["Inbox", "Logbook", "Next", \
                    "Projects", "Scheduled", "Someday", "Today"] else os.path.join(alp.local(), "images", "{0}.png".format(thing))
                arg = k if k != "task" else "to do"
                if "\"" in thing:
                    clean_thing = thing.replace("\"", "\\\"")
                else:
                    clean_thing = thing
                items.append(
                    I(title=thing,
                      arg=u"show \"{0}\" \"{1}\"".format(arg, clean_thing),
                      icon=icon,
                      uid=uid,
                      valid=True))

    alp.feedback(items)
Пример #57
0
def find_projects():
    q = alp.args()[0] if len(alp.args()) else ""

    session_path = []
    st3_sesh = os.path.expanduser(
        "~/Library/Application Support/Sublime Text 3/Local/Session.sublime_session"
    )
    st2_sesh = os.path.expanduser(
        "~/Library/Application Support/Sublime Text 2/Settings/Session.sublime_session"
    )
    if os.path.exists(st3_sesh):
        session_path.append(st3_sesh)
    if os.path.exists(st2_sesh):
        session_path.append(st2_sesh)
    if not len(session_path):
        alp.feedback(
            I(title="No Sublime Installation",
              subtitle="Sublime Text 2 or 3 is required.",
              valid=False))
        return

    projectNames = []
    for p in session_path:
        with codecs.open(p, "r", "utf-8") as f:
            session_json = f.read()
        session_json = session_json.replace('\t', '')
        projects = json.loads(session_json)["workspaces"]["recent_workspaces"]
        for project in projects:
            # projPath = project
            (projPath, projFile) = os.path.split(project)
            (projTitle, _) = projFile.rsplit(".", 1)
            if "2" in p:
                projTitle += " (ST2)"
                v_arg = project + ":::2"
            elif "3" in p:
                projTitle += " (ST3)"
                v_arg = project + ":::3"

            if os.path.exists(project):
                projectNames.append([project, projTitle, v_arg])

    items = []
    if q == "":
        for path, title, arg in projectNames:
            items.append(
                I(title=title, subtitle=path, arg=arg, valid=True, uid=path))
    elif len(q):
        for match in alp.fuzzy_search(q, projectNames, key=lambda x: x[1]):
            path = match[0]
            title = match[1]
            arg = match[2]
            items.append(
                I(title=title, subtitle=path, arg=arg, valid=True, uid=path))

    if len(items):
        alp.feedback(items)
    else:
        alp.feedback(
            I(title="No Matches",
              subtitle="No recent projects matched your query.",
              valid=False))
Пример #58
0
def executeFunction(args):
    cmd = args[2]
    if cmd == 'start':
        return startTimer(' '.join(args[3:]))
    elif cmd == 'token':
        settings.set(token=args[3])
        return 'Token has been set to %s' % args[3]
    elif cmd == 'stop':
        return stopTimer()
    else:
        return startTimer(' '.join(args[2:]))


alp.log(sys.argv)
if sys.argv[1] not in ACTION_STRINGS:
    print alp.feedback(ACTIONS)
else:
    if sys.argv[1] == 'start':
        item = alp.Item(title='Start Timer \'%s\'' % ' '.join(sys.argv[2:]),
                        subtitle='Start a new Toggl Timer',
                        valid=(len(sys.argv) > 2),
                        arg='start %s' % ' '.join(sys.argv[2:]))
        print alp.feedback([item])
    elif sys.argv[1] == 'stop':
        item = alp.Item(title='Stop Timer',
                        subtitle='Stop the current Toggl Timer',
                        valid=True,
                        autocomplete='stop',
                        arg='stop')
        print alp.feedback([item])
    elif sys.argv[1] == 'token':