Пример #1
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)
Пример #2
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)
Пример #3
0
def do_feedback():
    q = alp.args()
    flowPath = os.path.split(alp.local())[0]
    cache = alp.jsonLoad("cache.json", default={})
    day_secs = 24 * 60 * 60
    force = (len(q) > 0 and q[0] == "|force|")
    t = time.time()
    if (force):
        import shutil
        _c = alp.cache()
        _s = alp.storage()
        shutil.rmtree(_c)
        shutil.rmtree(_s)

    if (cache.get("cache_time", 0) + day_secs > t) and not force:
        candidates = cache.get("cached_workflows", [])
    else:
        candidates = []
        for dirpath, dirnames, filenames in os.walk(flowPath, topdown=False, followlinks=True):
            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")

                        plist = alp.readPlist(fn)
                    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))
        new_cache = dict(cache_time=t, cached_workflows=candidates)
        alp.jsonDump(new_cache, "cache.json")

    threads = []
    for candidict in candidates:
        try:
            with codecs.open(candidict["json"]) as f:
                local = json.load(f, encoding="utf-8")
        except Exception as e:
            alp.log("{0} may no longer exist: {1}".format(candidict["name"], e))
            continue

        ot = OopThread(local['remote_json'], force, candidict, local)
        threads.append(ot)
        ot.start()
    manage_threads(threads)
Пример #4
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)
Пример #5
0
def act():
    args = alp.args()
    if args[0] == "configure":
        url = args[1]
        sig = args[2]

        s = alp.Settings()
        s_dict = {"url": url}
        s.set(**s_dict)

        kc = alp.Keychain("yourls_stats")
        if not kc.retrievePassword("signature"):
            kc.storePassword("signature", sig)
        else:
            kc.modifyPassword("signature", sig)

        info = alp.readPlist(alp.local("info.plist"))
        objs = info['objects']
        kw = None
        for o in objs:
            if o['type'] == "alfred.workflow.input.scriptfilter":
                kw = o['config']['keyword']
                break

        if kw:
            scpt = "tell application \"Alfred 2\" to search \"{0}\"".format(kw)
            call(["osascript", "-e", scpt])

        print "Yourls Configured"

    elif args[0] == "copy":
        print args[1]
Пример #6
0
def act():
    args = alp.args()
    if args[0] == "configure":
        url = args[1]
        sig = args[2]

        s = alp.Settings()
        s_dict = {"url": url}
        s.set(**s_dict)

        kc = alp.Keychain("yourls_stats")
        if not kc.retrievePassword("signature"):
            kc.storePassword("signature", sig)
        else:
            kc.modifyPassword("signature", sig)

        info = alp.readPlist(alp.local("info.plist"))
        objs = info['objects']
        kw = None
        for o in objs:
            if o['type'] == "alfred.workflow.input.scriptfilter":
                kw = o['config']['keyword']
                break

        if kw:
            scpt = "tell application \"Alfred 2\" to search \"{0}\"".format(kw)
            call(["osascript", "-e", scpt])

        print "Yourls Configured"

    elif args[0] == "copy":
        print args[1]
Пример #7
0
def do_feedback():
    args = alp.args()
    path = args[0]
    color = int(args[1])

    set_finder_label(path, color)
    _, name = os.path.split(path)
    name = name.encode("utf-8")
    print "{0} labeled {1}.".format(name, COLORS[color])
Пример #8
0
def do_feedback():
    args = alp.args()
    path = args[0]
    color = int(args[1])

    set_finder_label(path, color)
    _, name = os.path.split(path)
    name = name.encode("utf-8")
    print "{0} labeled {1}.".format(name, COLORS[color])
Пример #9
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)
Пример #10
0
def do_feedback():
    args = alp.args()
    path = args[0]
    tags = args[1:]
    set_tags(tags, path)

    _, name = os.path.split(path)
    tag_string = ", ".join(tags)
    name = name.encode("utf-8")
    print "Tagged {0} \"{1}\".".format(name, tag_string)
Пример #11
0
def do_feedback():
    args = alp.args()
    path = args[0]
    tags = args[1:]
    set_tags(tags, path)

    _, name = os.path.split(path)
    tag_string = ", ".join(tags)
    name = name.encode("utf-8")
    print "Tagged {0} \"{1}\".".format(name, tag_string)
Пример #12
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))
Пример #13
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))
Пример #14
0
def main():
    query = ' '.join(alp.args()).strip()
    try:
        if query.startswith('pass '):
            _pass = sh.Command('pass')
            output = _pass(query.split(' ')[1:])
            output = output.split('\n')[1].strip()[9:-4]
        else:
            output = query
        sys.stdout.write(output)
    except:
        pass
Пример #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 main():
    alp_args = alp.args()
    alp.log(alp_args)

    try:
        alp.jsonDump(dict(hubid=alp_args[0]), alp.storage('config.json'))
        alp.log('Setting json')
        alp.log(alp.jsonLoad(alp.storage('config.json')))
    except Exception as e:
        alp.log('Unable to save your configuration. Please try again.')
        alp.log(traceback.format_exc())
        raise e

    return
Пример #17
0
def main():
    alp_args = alp.args()
    alp.log(alp_args)

    try:
        alp.jsonDump(dict(hubid=alp_args[0]), alp.storage('config.json'))
        alp.log('Setting json')
        alp.log(alp.jsonLoad(alp.storage('config.json')))
    except Exception as e:
        alp.log('Unable to save your configuration. Please try again.')
        alp.log(traceback.format_exc())
        raise e

    return
Пример #18
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)
Пример #19
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)
Пример #20
0
def process():
    args = alp.args()

    o = subprocess.call(["osascript", "-e", wake_up()])

    if args[0] == "parse":
        inp = args[1]
        if "\"" in inp:
            inp = inp.replace("\"", "\\\"")        
        o = subprocess.call(["osascript", "-e", scpt("parse quicksilver input \"{0}\"".format(inp.encode("utf-8")))])
        # print "Task added."
    elif args[0] == "show":
        thing = args[1]
        inp = args[2]
        if "\"" in inp:
            inp = inp.replace("\"", "\\\"")
        o = subprocess.call(["osascript", "-e", scpt_act("show ({0} named \"{1}\")".format(thing.encode("utf-8"), inp.encode("utf-8")))])
Пример #21
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)
Пример #22
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)
Пример #23
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)
Пример #24
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"
Пример #25
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"
Пример #26
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)
Пример #27
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)
Пример #28
0
def process():
    args = alp.args()

    o = subprocess.call(["osascript", "-e", wake_up()])

    if args[0] == "parse":
        inp = args[1]
        if "\"" in inp:
            inp = inp.replace("\"", "\\\"")
        o = subprocess.call([
            "osascript", "-e",
            scpt("parse quicksilver input \"{0}\"".format(inp.encode("utf-8")))
        ])
        # print "Task added."
    elif args[0] == "show":
        thing = args[1]
        inp = args[2]
        if "\"" in inp:
            inp = inp.replace("\"", "\\\"")
        o = subprocess.call([
            "osascript", "-e",
            scpt_act("show ({0} named \"{1}\")".format(thing.encode("utf-8"),
                                                       inp.encode("utf-8")))
        ])
Пример #29
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)
Пример #30
0
import alp

try:
	path = alp.args()[0]
	if path == "auto":
	    path = ""

	s = alp.Settings()
	s.set(**{"budget_path": path})

	if path == "":
	    print "YNAB budget path set to automatic"
	else:
	    print "YNAB budget path set to %s" % path
except Exception, e:
	alp.log("Oh no, an exception while saving configuration:", e)
Пример #31
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)
Пример #32
0
from os import path
from types import *
import alp

# Check for input
if len(alp.args()) > 0:
	adds = alp.args()[0].split('\t')
else:
	print 'Nothing to add to Favorites.'
	raise SystemExit
# SCRIPT EXITS

# Sync & load favorites
favs = alp.jsonLoad('favorites.json', default=[])

# Correct existing favorites
if type(favs) is DictType:
	favs = favs.items()

# Hide 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')

# Add new entries
deleted = []
for add in adds:
	favs.append(add)
Пример #33
0
def do_action():
    args = alp.args()
    storedFiles = alp.jsonLoad("files.json", default=[])
    storedPaths = alp.jsonLoad("paths.json", default=[])

    if args[0] == "undo":
        action = args[1]
        arg = args[2]

        if action == "add":
            storedFiles.remove(arg)
            alp.jsonDump(storedFiles, "files.json")
            print "Forgot {0}".format(arg)

        elif action == "touch":
            the_dir = subprocess.check_output(["osascript", "getFinder.applescript"])
            the_dir = the_dir[:-1]
            the_file = os.path.join(the_dir, arg)
            try:
                os.remove(the_file)
            except Exception as e:
                alp.log("Failed to delete: {0}".format(e))
                print "Failed to delete: {0}".format(e)

        elif action == "path":
            storedPaths.remove(arg)
            alp.jsonDump(storedPaths, "paths.json")
            print "Forgot {0}".format(arg)

        elif action == "at":
            try:
                os.remove(arg)
            except Exception as e:
                alp.log("Failed to delete: {0}".format(e))
                print "Failed to delete: {0}".format(e)
            else:
                print "Deleted {0}".format(arg)

    else:
        action = args[0]
        arg = args[1]

        if action == "add":
            storedFiles.append(arg)
            alp.jsonDump(storedFiles, "files.json")
        
        elif action == "path":
            storedPaths.append(arg)
            alp.jsonDump(storedPaths, "paths.json")
        
        elif action == "touch":
            the_dir = subprocess.check_output(["osascript", "getFinder.applescript"])
            the_dir = the_dir[:-1]
            target = os.path.join(the_dir, arg)
            cmd = ["touch", target]
            subprocess.call(cmd)

            if len(args) == 3 and args[2] == "open":
                cmd = ["open", target]
                subprocess.call(cmd)

        elif action == "at":
            cmd = ["touch", arg]
            subprocess.call(cmd)

            if len(args) == 3 and args[2] == "open":
                cmd = ["open", arg]
                subprocess.call(cmd)
            else:
                print "Created {0}".format(arg)
Пример #34
0
        path = check_for_budget(os.path.expanduser("~/Dropbox/YNAB"))

    # 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
Пример #35
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:
Пример #36
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)
Пример #37
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)
Пример #38
0
# -*- coding: utf-8 -*-
import os
import shutil

import alp


def save_preset(preset_name):
    preset_dir = alp.storage(join='presets/%s/' % preset_name)
    os.makedirs(preset_dir)
    shutil.copy2(alp.cache('lights.json'), preset_dir)
    print 'Preset saved: %s' % preset_name


if __name__ == '__main__':
    settings = alp.Settings()
    if settings.get('username'):
        save_preset(alp.args()[0])
    else:
        print 'To save presets please use "-hue set-bridge" to enable this workflow.'
Пример #39
0
from os import path
from types import *
# from sync import rsync
import alp

if len(alp.args()) > 0:
    query = alp.args()[0].strip()
else:
    query = ''

# Sync & load favorites
# rsync(alp.storage('favorites.json'), 'favorites.json')
favs = alp.jsonLoad('favorites.json', default=[])
if type(favs) is DictType:
    favs = favs.values()

if not favs:
    item = alp.Item(
        title='No Favorites',
        subtitle=
        'No favorites were found. Add favorites via the File Actions panel.',
        uid=alp.bundle() + ' none',
        valid=False)

    alp.feedback(item)
# SCRIPT EXITS

# Remove duplicate favorites (sets can't have duplicates)
favs = list(set(favs))

# Remove non-existent favorites
Пример #40
0
from os import path
from types import *
# from sync import rsync
import alp

if len(alp.args()) > 0:
	deletes = alp.args()[0].split('\t')
else:
	print 'Nothing to remove.'
	raise SystemExit
# SCRIPT EXITS

# Sync & load favorites
# rsync(alp.storage('favorites.json'), 'favorites.json')
favs = alp.jsonLoad('favorites.json', default=[])
if type(favs) is DictType:
	favs = favs.values()

if not favs:
	print 'Favorites couldn\'t be located. Nothing removed.'
	raise SystemExit
# SCRIPT EXITS

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

# Remove specified entries
Пример #41
0
from os import path
from types import *
import alp

if len(alp.args()) > 0:
    adds = alp.args()[0].split("\t")
else:
    print "Nothing to add to Favorites."
    raise SystemExit
# SCRIPT EXITS

# Sync & load favorites
favs = alp.jsonLoad("favorites.json", default=[])
if type(favs) is DictType:
    favs = favs.items()

# 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")

# Remove specified entries
deleted = []
for add in adds:
    favs.append(add)

# Remove duplicates
favs = list(set(favs))
Пример #42
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))
Пример #43
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))
Пример #44
0
import sys
import alp
import alfred_random

def main(args):
    args = args[0].split(' ')
    r = alfred_random.main(args)
    sys.stdout.write(r)

if __name__ == '__main__':
    main(alp.args())
Пример #45
0
from os import path
from types import *
import alp

if len(alp.args()) > 0:
	deletes = alp.args()[0].split('\t')
else:
	print 'Nothing to remove.'
	raise SystemExit
# SCRIPT EXITS

# Sync & load favorites
favs = alp.jsonLoad('favorites.json', default=[])
if type(favs) is DictType:
	favs = favs.values()

if not favs:
	print 'Favorites couldn\'t be located. Nothing removed.'
	raise SystemExit
# SCRIPT EXITS

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

# Remove specified entries
deleted = []
for delete in deletes:
Пример #46
0
from os import path
from types import *
import alp

# Check for input
if len(alp.args()) > 0:
    adds = alp.args()[0].split('\t')
else:
    print 'Nothing to add to Favorites.'
    raise SystemExit
# SCRIPT EXITS

# Sync & load favorites
favs = alp.jsonLoad('favorites.json', default=[])

# Correct existing favorites
if type(favs) is DictType:
    favs = favs.items()

# Hide 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')

# Add new entries
deleted = []
for add in adds:
    favs.append(add)
Пример #47
0
import math
import alp

if len(alp.args()) > 0:
	query = alp.args()[0]
else:
	query = ''
#query = ""

Phi = 1.6180339887
phi = 0.6180339887

if not query:
	Phi_item = alp.Item(title=str(Phi), subtitle=u"\u03D5", valid=True, arg=str(Phi), uid="tylereich.goldenratio Phi")
	phi_item = alp.Item(title=str(phi), subtitle=u"1 \u00F7 \u03D5", valid=True, arg=str(phi), uid="tylereich.goldenratio phi")
	
	alp.feedback([Phi_item, phi_item])

try:
	query = int(query)
except ValueError:
	try:
		query = float(query)
	except ValueError:
		query = None

if query is not None:
	long_side = query * Phi
	short_side = query * phi

	if type(query) is int:
Пример #48
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)
Пример #49
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))
Пример #50
0
def do_action():
    args = alp.args()
    storedFiles = alp.jsonLoad("files.json", default=[])
    storedPaths = alp.jsonLoad("paths.json", default=[])

    if args[0] == "undo":
        action = args[1]
        arg = args[2]

        if action == "add":
            storedFiles.remove(arg)
            alp.jsonDump(storedFiles, "files.json")
            print "Forgot {0}".format(arg)

        elif action == "touch":
            the_dir = subprocess.check_output(
                ["osascript", "getFinder.applescript"])
            the_dir = the_dir[:-1]
            the_file = os.path.join(the_dir, arg)
            try:
                os.remove(the_file)
            except Exception as e:
                alp.log("Failed to delete: {0}".format(e))
                print "Failed to delete: {0}".format(e)

        elif action == "path":
            storedPaths.remove(arg)
            alp.jsonDump(storedPaths, "paths.json")
            print "Forgot {0}".format(arg)

        elif action == "at":
            try:
                os.remove(arg)
            except Exception as e:
                alp.log("Failed to delete: {0}".format(e))
                print "Failed to delete: {0}".format(e)
            else:
                print "Deleted {0}".format(arg)

    else:
        action = args[0]
        arg = args[1]

        if action == "add":
            storedFiles.append(arg)
            alp.jsonDump(storedFiles, "files.json")

        elif action == "path":
            storedPaths.append(arg)
            alp.jsonDump(storedPaths, "paths.json")

        elif action == "touch":
            the_dir = subprocess.check_output(
                ["osascript", "getFinder.applescript"])
            the_dir = the_dir[:-1]
            target = os.path.join(the_dir, arg)
            cmd = ["touch", target]
            subprocess.call(cmd)

            if len(args) == 3 and args[2] == "open":
                cmd = ["open", target]
                subprocess.call(cmd)

        elif action == "at":
            cmd = ["touch", arg]
            subprocess.call(cmd)

            if len(args) == 3 and args[2] == "open":
                cmd = ["open", arg]
                subprocess.call(cmd)
            else:
                print "Created {0}".format(arg)
Пример #51
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)
Пример #52
0
        self.partial_query = query

        for _, dirnames, __ in os.walk(alp.storage(join='presets')):
            for subdirname in dirnames:
                self._add_item(
                    title=subdirname,
                    icon=self.ICON,
                    autocomplete=subdirname,
                    arg=json.dumps({
                        'action': 'load_preset',
                        'preset_name': subdirname,
                    }),
                )

        if not self.results:
            self._add_item(
                title='You have no saved presets!',
                subtitle='Use "-hue save-preset" to save the current lights state as a preset.',
                icon=self.ICON,
                valid=False,
            )

        self._filter_results()
        return self.results


if __name__ == '__main__':
    hue_filter = HueFilter()
    results = hue_filter.get_results(alp.args())
    alp.feedback(results)
Пример #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
                self._add_item(
                    title=reminder_title('hours'),
                    subtitle='',
                    icon=icon,
                    valid=True if int_value else False,
                    arg=json.dumps({
                        'lid': lid,
                        'action': 'reminder',
                        'time_delta': (int_value * 60 * 60) if int_value else 0,
                    }))

            elif function == 'rename':
                self._add_item('light_rename',
                    icon=icon,
                    valid=True,
                    arg=json.dumps({
                        'action': 'rename',
                        'lid': lid,
                        'data': {'name': value},
                    }))

        self._filter_results()
        return self.results


if __name__ == '__main__':
    light_filter = HueLightFilter()
    results = light_filter.get_results(alp.args()[0])
    alp.feedback(results)
Пример #55
0
def do_feedback():
    q = alp.args()
    flowPath = os.path.split(alp.local())[0]
    cache = alp.jsonLoad("cache.json", default={})
    day_secs = 24 * 60 * 60
    force = (len(q) > 0 and q[0] == "|force|")
    t = time.time()
    if (force):
        import shutil
        _c = alp.cache()
        _s = alp.storage()
        shutil.rmtree(_c)
        shutil.rmtree(_s)

    if (cache.get("cache_time", 0) + day_secs > t) and not force:
        candidates = cache.get("cached_workflows", [])
    else:
        candidates = []
        for dirpath, dirnames, filenames in os.walk(flowPath,
                                                    topdown=False,
                                                    followlinks=True):
            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")

                        plist = alp.readPlist(fn)
                    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))
        new_cache = dict(cache_time=t, cached_workflows=candidates)
        alp.jsonDump(new_cache, "cache.json")

    threads = []
    for candidict in candidates:
        try:
            with codecs.open(candidict["json"]) as f:
                local = json.load(f, encoding="utf-8")
        except Exception as e:
            alp.log("{0} may no longer exist: {1}".format(
                candidict["name"], e))
            continue

        ot = OopThread(local['remote_json'], force, candidict, local)
        threads.append(ot)
        ot.start()
    manage_threads(threads)
Пример #56
0
import json
import random

import alp

import helpers
from hue_request import HueRequest
from action import HueAlfredAction


q = alp.args()[0]
lights = helpers.get_lights()

if not lights:
    print 'No Hue lights found. Try -hue set-bridge.'
else:
    hue_request = HueRequest()
    settings = alp.Settings()

    if settings.get('group'):
        group_id = settings.get('group_id')
    else:
        group_id = '/groups/0'

    if q == 'All Off':
        hue_request.request(
            'put',
            '%s/action' % group_id,
            json.dumps({'on': False})
        )
        print 'All lights toggled off.'