Beispiel #1
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)
Beispiel #2
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)
Beispiel #3
0
def get_results(arg):
    """ Returns a list of Bookmark objects after a
    title search based on the given arg """
    bookmarks = tower.get_bookmarks(BOOKMARKS_FILE)

    # alp.fuzzy_search() will break if query is ""
    if arg == "":
        # only use sort_order when no arguments are given
        # otherwise, we'll use alp's ranking system
        results = sorted(bookmarks, key=lambda x: x.sort_order)
    else:
        titles = alp.fuzzy_search(arg, bookmarks, key=lambda x: x.title)
        paths = alp.fuzzy_search(arg, bookmarks, key=lambda x: x.path)
        results = set(titles).union(set(paths))

    return results
Beispiel #4
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 get_results(arg):
    """ Returns a list of Bookmark objects after a
    title search based on the given arg """
    bookmarks = tower.get_bookmarks(BOOKMARKS_FILE)

    # alp.fuzzy_search() will break if query is ""
    if arg == "":
        # only use sort_order when no arguments are given
        # otherwise, we'll use alp's ranking system
        results = sorted(bookmarks, key=lambda x: x.sort_order)
    else:
        titles = alp.fuzzy_search(arg, bookmarks, key=lambda x: x.title)
        paths = alp.fuzzy_search(arg, bookmarks, key=lambda x: x.path)
        results = set(titles).union(set(paths))

    return results
Beispiel #6
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)
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
0
    if cache_valid:
        debug_print("Using cache for categories")
        all = cache["all_categories"]
        get_currency_symbol(
            {"budgetMetaData": {
                "currencyLocale": cache["currencyLocale"]
            }})
        data = None
    else:
        data = load_budget(path)
        get_currency_symbol(data)
        all = all_categories(data)
        cache["all_categories"] = all
        cache["currencyLocale"] = data["budgetMetaData"]["currencyLocale"]
    query = alp.args()[0]
    results = alp.fuzzy_search(query, all, key=lambda x: '%s' % x["name"])

    items = []

    for r in results:
        # Find category ID matching our requirement
        entityId = r["entityId"]

        if entityId == "":
            pass
        else:
            if cache_valid and entityId in cache["entries"]:
                debug_print("Using cached entry")
                ending_balance = cache["entries"][entityId]
            else:
                if data is None:
Beispiel #10
0
favs = list(set(favs))

# Remove non-existent favorites
new_favs = []
for fav in favs:
    if path.exists(fav):
        new_favs.append(fav)
favs = new_favs
alp.jsonDump(favs, 'favorites.json')

if not query:
    # Return all favorites
    results = favs
else:
    # Return matches
    results = alp.fuzzy_search(query, favs, key=lambda x: x)

if not results:
    item = alp.Item(title='No Results',
                    subtitle='No favorites matched your search.',
                    uid=alp.bundle() + ' none',
                    valid=False)

    alp.feedback(item)
# SCRIPT EXITS

# Send to Alfred
items = []
for fav in results:
    item = alp.Item(arg=fav,
                    title=path.basename(fav),
Beispiel #11
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)
    addItem = I(title="Add Todo",
                subtitle=line,
                arg=u"add {0}".format(line),
                valid=True)

    # No words written
    if len(q) == 1:
        if len(todos):
            tmpfeedback = []
            for r in todos:
                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)))
        else:
            tmpfeedback.append(addItem)
        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 q[1] in ['archive', 'deduplicate']:
            # Leave other specific actions unaltered by the program.
            feedback.append(
                I(title="Parse to todo.sh",
                  subtitle="Other Actions",
                  arg=u"-f {0}".format(line),
                  valid=True))
        feedback.append(addItem)
        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:
        if q[1] in ['a', 'add', 'ls', 'list']:  # Ignore these key words.
            line = build_line(q, 2)
            addItem = I(title="Add Todo",
                        subtitle=line,
                        arg=u"add {0}".format(line),
                        valid=True)
        if q[1] in [
                'addm', 'addto', 'append', 'app', 'pri', 'p', 'del', 'rm',
                'depri', 'dp', 'do'
        ]:
            # Leave other specific actions unaltered by the program.
            feedback.append(
                I(title="Parse to todo.sh",
                  subtitle="Other Actions",
                  arg=u"-f {0}".format(line),
                  valid=True))
            feedback.append(addItem)
        else:
            feedback.append(addItem)
            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)
Beispiel #12
0
    # Then we look locally
    if path == "":
        path = check_for_budget(os.path.expanduser("~/Documents/YNAB"))

    # Then we give up
    if path == "":
        handle_error("Unable to guess budget location", "Use Alfred's File Action on your budget file to configure", "icon-no.png")

    # Load data
    data = load_budget(path)
    get_currency_symbol(data)

    all = all_categories(data)
    query = alp.args()[0]
    results = alp.fuzzy_search(query, all, key = lambda x: '%s' % x["name"])

    items = []

    for r in results:
        # Find category ID matching our requirement
        entityId = r["entityId"]

        if entityId == "":
            pass
        else:
            # Find the starting balance of our category
            starting_balance = find_budgeted(data, entityId)

            # Replay the transactions
            ending_balance = walk_transactions(data, entityId, starting_balance)
Beispiel #13
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)
Beispiel #14
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)
Beispiel #15
0
def do_feedback():
    args = alp.args()
    settings = alp.Settings()
    url = settings.get("url", None)
    if url:
        k = alp.Keychain("yourls_stats")
        sig = k.retrievePassword("signature")
        links = fetch_stats(url, sig)
        if isinstance(links, I):
            alp.feedback(links)
            return
        feedback = []

    def build_feedback(good_links):
        for l in good_links:
            s = "" if int(l["clicks"]) == 1 else "s"
            subtitle = u"{0} \u2022 {1} click{2}".format(
                l["shorturl"], l["clicks"], s)
            feedback.append(
                I(title=l["title"],
                  subtitle=subtitle,
                  valid=True,
                  arg="copy \"{0}\"".format(l["shorturl"])))

    if len(args) == 0 and url:
        build_feedback(links)
    elif len(args):
        q = args[0]
        if "!" in q:
            links = fetch_stats(url, sig, force=True)
            if isinstance(links, I):
                alp.feedback(links)
                return
            q = q.replace("!", "")

        if not url or "=" in q:
            new_settings = q.split(" ")
            url = "foo"
            sig = "bar"
            for ns in new_settings:
                if "=" in ns:
                    k = ns.split("=")[0]
                    v = ns.split("=")[1]
                    if k == "url":
                        if not v.startswith("http://"):
                            v = "http://" + v
                        if v.endswith("php"):
                            pass
                        elif v.endswith("/"):
                            v += "yourls-api.php"
                        else:
                            v += "/yourls-api.php"
                        url = v
                    if k == "signature":
                        sig = v

            valid = True if "=" in q and (url != "foo") and (
                sig != "bar") else False
            feedback = I(title="Configure Yourls",
                         subtitle="url={0} signature={1}".format(url, sig),
                         valid=valid,
                         arg="configure \"{0}\" \"{1}\"".format(url, sig))
        elif url:
            gl = alp.fuzzy_search(
                q,
                links,
                key=lambda x: u"{0} - {1}".format(x["title"], x["shorturl"]))
            build_feedback(gl)
            if len(feedback) == 0:
                feedback = I(title="No Results",
                             subtitle="No Yourls matched your query.",
                             valid=False)
    else:
        feedback = I(title="Configure Yourls",
                     subtitle="url=foo signature=bar",
                     valid=False)

    alp.feedback(feedback)
Beispiel #16
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)
Beispiel #17
0
favs = list(set(favs))

# Remove non-existent favorites
new_favs = []
for fav in favs:
	if path.exists(fav):
		new_favs.append(fav)
favs = new_favs
alp.jsonDump(favs, 'favorites.json')

if not query:
	# Return all favorites
	results = favs
else:
	# Return matches
	results = alp.fuzzy_search(query, favs, key=lambda x: x)

if not results:
	item = alp.Item(title='No Results', subtitle='No favorites matched your search.', uid=alp.bundle() + ' none', valid=False)
	
	alp.feedback(item)
# SCRIPT EXITS

# Send to Alfred
items = []
for fav in results:
	item = alp.Item(arg=fav, title=path.basename(fav), subtitle=fav, icon=fav, fileIcon=True, type='file', uid=alp.bundle() + ' ' + fav, valid=True)
	
	items.append(item)

alp.feedback(items)
Beispiel #18
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))
Beispiel #19
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)
    addItem = I(title="Add Todo", subtitle=line, arg=u"add {0}".format(line), valid=True)

    # 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)))
        else:
            tmpfeedback.append(addItem)
        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 q[1] in ['archive','deduplicate']:
            # Leave other specific actions unaltered by the program.
            feedback.append(I(title="Parse to todo.sh", subtitle="Other Actions", arg=u"-f {0}".format(line), valid=True))
        feedback.append(addItem)
        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:
        if q[1] in ['add','ls','list']: # Ignore these key words.
            line = build_line(q,2)
            addItem = I(title="Add Todo", subtitle=line, arg=u"add {0}".format(line), valid=True)
        if len(q[2])==1 and q[2].isalpha():
            pri = '(' + q[2].upper() + ') '
            line = pri + build_line(q,3)
            addItem = I(title="Add Todo", subtitle=line, arg=u"add {0}".format(line), valid=True)
        if q[1] in ['addm','addto','append','app','pri','p','del','rm','depri','dp','do']:
            # Leave other specific actions unaltered by the program.
            feedback.append(I(title="Parse to todo.sh", subtitle="Other Actions", arg=u"-f {0}".format(line), valid=True))
            feedback.append(addItem)
        elif q[1].isalpha():
            feedback.append(addItem)
        else:
            feedback.append(addItem)
            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)
Beispiel #20
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))
Beispiel #21
0
def do_feedback():
    args = alp.args()
    settings = alp.Settings()
    url = settings.get("url", None)
    if url:
        k = alp.Keychain("yourls_stats")
        sig = k.retrievePassword("signature")
        links = fetch_stats(url, sig)
        if isinstance(links, I):
            alp.feedback(links)
            return
        feedback = []

    def build_feedback(good_links):
        for l in good_links:
            s = "" if int(l["clicks"]) == 1 else "s"
            subtitle = u"{0} \u2022 {1} click{2}".format(l["shorturl"], l["clicks"], s)
            feedback.append(I(title=l["title"], subtitle=subtitle,
                            valid=True, arg="copy \"{0}\"".format(l["shorturl"])))

    if len(args) == 0 and url:
        build_feedback(links)
    elif len(args):
        q = args[0]
        if "!" in q:
            links = fetch_stats(url, sig, force=True)
            if isinstance(links, I):
                alp.feedback(links)
                return
            q = q.replace("!", "")

        if not url or "=" in q:
            new_settings = q.split(" ")
            url = "foo"
            sig = "bar"
            for ns in new_settings:
                if "=" in ns:
                    k = ns.split("=")[0]
                    v = ns.split("=")[1]
                    if k == "url":
                        if not v.startswith("http://"):
                            v = "http://" + v
                        if v.endswith("php"):
                            pass
                        elif v.endswith("/"):
                            v += "yourls-api.php"
                        else:
                            v += "/yourls-api.php"
                        url = v
                    if k == "signature":
                        sig = v

            valid = True if "=" in q and (url != "foo") and (sig != "bar") else False
            feedback = I(title="Configure Yourls", subtitle="url={0} signature={1}".format(url, sig),
                            valid=valid, arg="configure \"{0}\" \"{1}\"".format(url, sig))
        elif url:
            gl = alp.fuzzy_search(q, links, key=lambda x: u"{0} - {1}".format(x["title"], x["shorturl"]))
            build_feedback(gl)
            if len(feedback) == 0:
                feedback = I(title="No Results", subtitle="No Yourls matched your query.", valid=False)
    else:
        feedback = I(title="Configure Yourls", subtitle="url=foo signature=bar", valid=False)

    alp.feedback(feedback)
Beispiel #22
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)
Beispiel #23
0
def do_feedback():
    flowPath = os.path.split(alp.local())[0]
    candidates = []
    for dirpath, dirnames, filenames in os.walk(flowPath, topdown=False):
        for aFile in filenames:
            if aFile == "update.json":
                try:
                    fn = os.path.join(dirpath, "Info.plist")
                    if not os.path.exists(fn):
                        fn = os.path.join(dirpath, "info.plist")

                    with open(fn) as f:
                        plist = plistlib.readPlist(f)
                except IOError as e:
                    alp.log("Exception: Info.plist not found ({0}).".format(e))
                    continue
                else:
                    name = plist["name"]
                    local_description = plist["description"]
                    the_json = os.path.join(dirpath, aFile)
                    the_icon = os.path.join(dirpath, "icon.png")
                    if name != "Alleyoop":
                        candidates.append(
                            dict(name=name,
                                 json=the_json,
                                 icon=the_icon,
                                 path=dirpath,
                                 description=local_description))
                    else:
                        downloads_path = os.path.expanduser("~/Downloads/")
                        candidates.append(
                            dict(name=name,
                                 json=the_json,
                                 icon=the_icon,
                                 path=downloads_path,
                                 description=local_description))

    updatables = []
    all_configured = []
    for candidict in candidates:
        with open(candidict["json"]) as f:
            local = json.load(f, encoding="utf-8")
        try:
            remote_uri = local["remote_json"]
            local_version = float(local["version"])
            local_description = candidict["description"]
        except Exception as e:
            alp.log("{0} failed on key: {1}.".format(candidict["name"], e))
            continue

        r = alp.Request(remote_uri)
        remote = r.request.json
        if not remote:
            alp.log("{0} failed to load remote JSON.".format(
                candidict["name"]))
            continue

        should_add = True
        try:
            version = float(remote["version"])
            download_uri = remote["download_url"]
            description = remote["description"]
        except Exception as e:
            alp.log("{0} failed with error: {1}".format(candidict["name"], e))
            should_add = False
            continue

        if should_add and local_version < version:
            updatables.append(
                dict(name=candidict["name"],
                     description=description,
                     icon=candidict["icon"],
                     download=download_uri,
                     path=candidict["path"],
                     version=version))
        all_configured.append(
            dict(name=candidict["name"],
                 description=description,
                 icon=candidict["icon"],
                 download=download_uri,
                 path=candidict["path"],
                 version=version,
                 local_d=local_description))

    q = alp.args()
    items = []
    if not len(q):
        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 len(updatables) != 1 else ""
        items.append(
            I(title="Update All",
              subtitle="Download and install {0} update{1}".format(n, upd_sib),
              valid=True,
              arg=update_all))

        for updict in updatables:
            items.append(
                I(title=updict["name"],
                  subtitle=u"v{0}\u2014{1}".format(updict["version"],
                                                   updict["description"]),
                  icon=updict["icon"],
                  arg="\"update\" \"{0}>{1}>{2}\"".format(
                      updict["name"], updict["path"], updict["download"]),
                  valid=True))

    elif len(q) == 1 and q[0] == "all":
        for configured in all_configured:
            items.append(
                I(title=configured["name"],
                  subtitle=u"v{0}\u2014{1}".format(configured["version"],
                                                   configured["local_d"]),
                  icon=configured["icon"],
                  valid=False))

    else:
        if q[0] != "all":
            search = q[0]
            results = alp.fuzzy_search(
                search,
                updatables,
                key=lambda x: "{0} - {1}".format(x["name"], x["description"]))
            for result in results:
                items.append(
                    I(title=result["name"],
                      subtitle=u"v{0}\u2014{1}".format(result["version"],
                                                       result["description"]),
                      icon=result["icon"],
                      arg="\"update\" \"{0}>{1}>{2}\"".format(
                          result["name"], result["path"], result["download"]),
                      valid=True))
        else:
            search = q[1]
            results = alp.fuzzy_search(
                search,
                all_configured,
                key=lambda x: "{0} - {1}".format(x["name"], x["local_d"]))
            for result in results:
                items.append(
                    I(title=result["name"],
                      subtitle=u"v{0}\u2014{1}".format(result["version"],
                                                       result["local_d"]),
                      icon=result["icon"],
                      arg="{0} up-to-date.".format(result["name"]),
                      valid=False))

    alp.feedback(items)