Example #1
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)
Example #2
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)
Example #3
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)
Example #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)
Example #5
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)
Example #6
0
def parse_others():
    """
    Return a list of manually-added people
    """
    alp.log('parsing others')
    li = alp.jsonLoad(alp.local('others.json'), [])
    for p in li:
        if 'fuzzy' not in p:
            p['fuzzy'] = mk_fuzzy(p)
    alp.log('done others')
    return li
Example #7
0
def parse_others():
    """
    Return a list of manually-added people
    """
    alp.log('parsing others')
    li = alp.jsonLoad(alp.local('others.json'), [])
    for p in li:
        if 'fuzzy' not in p:
            p['fuzzy'] = mk_fuzzy(p)
    alp.log('done others')
    return li
Example #8
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)
    def _load_preset(self, preset_name):
        lights = alp.jsonLoad('presets/%s/lights.json' % preset_name)

        for lid, light_data in lights.iteritems():
            self.hue_request.request(
                'put',
                '/lights/%s/state' % lid,
                json.dumps({
                     'xy': light_data['state']['xy'],
                     'on': light_data['state']['on'],
                    'bri': light_data['state']['bri'],
                }),
            )
Example #10
0
def act():
    q = sys.argv[1:]
    tmp = tempfile.mkdtemp()
    stamp = time.strftime("%Y-%m-%d (%H.%M)")

    cache = alp.jsonLoad("cache.json", default={})

    def do_download(address, name):
        r = alp.Request(address, cache=False)
        r.download()
        r.request.encoding = "utf-8"
        f = tempfile.NamedTemporaryFile(suffix=".alfredworkflow", dir=tmp, delete=False)
        f.write(r.request.content)
        f.close()
        d_path = os.path.join(os.path.expanduser("~/Downloads"), "{0} - {1}.alfredworkflow".format(stamp, name))
        shutil.copy(f.name, d_path)

        remme = None
        for wf in cache["cached_workflows"]:
            cached_name = wf.get("name", None)
            if cached_name == name:
                remme = wf
                break
        if remme:
            cache["cached_workflows"].remove(remme)
        alp.jsonDump(cache, "cache.json")

        return d_path


    if q[0] == "update-all":
        to_download = q[1:]
        i = len(to_download)
        for download in to_download:
            name, target_path, remote = download.split(">")
            ret_path = do_download(remote, name)
            i -= 1
            i_sib = "" if i == 1 else "s"
            n = alp.Notification()
            n.notify("Alleyoop", "Downloaded {0}".format(name),
                    "{0} update{1} remaining.".format(i, i_sib))
        NSDistributedNotificationCenter.defaultCenter().postNotificationName_object_("com.apple.DownloadFileFinished", ret_path)
        print "All updates downloaded."

    elif q[0] == "update":
        name, target_path, remote = q[1].split(">")
        ret_path = do_download(remote, name)
        NSDistributedNotificationCenter.defaultCenter().postNotificationName_object_("com.apple.DownloadFileFinished", ret_path)
        print "Saved {0} to Downloads".format(name)

    shutil.rmtree(tmp, True)
Example #11
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
Example #12
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
Example #13
0
def main():
    verb = sys.argv[1]

    thoughts = alp.jsonLoad("thoughts.json")

    if verb == "copy":
        uuid = sys.argv[2]
        thought = None
        for thought in thoughts:
            if thought["uuid"] == uuid:
                thought = thought["thought"]
                break
        if not thought:
            print "Unknown error."
        else:
            cmd = u"echo \"{0}\" | pbcopy".format(thought)
            subprocess.call(cmd, shell=True)
            print "Recalled \"{0}\"".format(thought)

    elif verb == "save":
        uuid = sys.argv[2]
        thought = sys.argv[3]
        thoughts.append(dict(uuid=uuid, thought=thought))
        alp.jsonDump(thoughts, "thoughts.json")

        print "Remembered %s" % thought

    elif verb == "delete" and sys.argv[2] != "save":
        uuid = sys.argv[3]
        for thought in thoughts:
            if thought["uuid"] == uuid:
                forgotten = thought["thought"]
                thoughts.remove(thought)
                break

        alp.jsonDump(thoughts, "thoughts.json")

        print "Forgot %s" % forgotten

    elif verb == "delete" and sys.argv[2] == "save":
        thought = sys.argv[4]
        print "Never remembered {0}".format(thought)

    else:
        print "Unknown error in act.py"
    def _get_lights(self, from_cache=False):
        """Returns a dictionary of lid => data, or None if no lights data is in the cache.

        Options:
            from_cache - Read data from cached json files instead of querying the API.
        """
        output = dict()

        if not from_cache:
            from requests.exceptions import RequestException
            try:
                self._load_lights_data_from_api()
            except RequestException:
                return None

        lights = alp.jsonLoad(alp.cache('lights.json'))

        return lights
Example #15
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))
Example #16
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)
Example #17
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))
Example #18
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)
Example #19
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))
Example #20
0
def get_list():
    li = alp.jsonLoad(JSON_LIST, default=[])
    if len(li) == 0:
        return save_list()
    return li
Example #21
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)
Example #22
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:
Example #23
0
def get_list():
    li = alp.jsonLoad(JSON_LIST, default=[])
    if len(li) == 0:
        return save_list()
    return li
Example #24
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)