def _load_lights_data_from_api(self, timeout=6): """Downloads lights data and caches it locally.""" # Requests is an expensive import so we only do it when necessary. import requests settings = alp.Settings() r = requests.get( 'http://{0}/api/{1}'.format( settings.get('bridge_ip'), settings.get('username'), ), timeout=timeout, ) data = r.json() lights = data['lights'] if settings.get('group'): lights = {lid: lights[lid] for lid in settings.get('group')} # Filter out anything that doesn't have an "xy" key in its state # e.g. "Dimmable plug-in unit", see: http://goo.gl/a5P7yN lights = {lid: lights[lid] for lid in lights if lights[lid]['state'].get('xy')} alp.jsonDump(lights, alp.cache('lights.json')) # Create icon for light for lid, light_data in lights.iteritems(): self._create_light_icon(lid, light_data)
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)
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)
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
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 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
def save_list(): p = parse_all() alp.jsonDump(p, JSON_LIST) return p
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)
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)
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)
# 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) # Remove duplicates favs = list(set(favs)) # Save new list alp.jsonDump(favs, 'favorites.json') # User feedback if len(adds) is 1: print '\'' + path.basename(adds[0]) + '\' was added to Favorites.'
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: if delete in favs: index = favs.remove(delete) deleted.append(delete) # Save & sync new list alp.jsonDump(favs, 'favorites.json') # User feedback if len(deleted) is 0: print 'No removable items found. Nothing removed.' elif len(deleted) is 1: print '\'' + path.basename(deleted[0]) + '\' was removed from Favorites.' elif len(deleted) > 1: print str(len(deleted)) + ' items were removed from Favorites.'
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)) # Save new list alp.jsonDump(favs, "favorites.json") # User feedback if len(adds) is 1: print "'" + path.basename(adds[0]) + "' was added to Favorites."