def saveToken(self, text): token = text.replace('#', '') token = token + '×tamp=' + str(int(time.time())) f = open(TOKEN_FILE, 'w') f.write(token) f.close() WoxAPI.show_msg('凭证已保存', 'saved')
def saveConfig(self, jkey, value): WoxAPI.change_query('') self.configfile[jkey] = value with open(os.path.join(os.path.dirname(__file__), "config.json"), "w+") as jsonFile: jsonFile.write(json.dumps(self.configfile)) jsonFile.close()
def wrap(*args, **kwargs): try: return func(*args, **kwargs) except: error = traceback.format_exc() WoxAPI.show_msg("error", error) Log.error(error)
def copy_password(self, password): """ Copies the given password to the clipboard. WARNING:Uses yet-to-be-known Win32 API and ctypes black magic to work. """ clipboard.put(password) WoxAPI.show_msg(password, 'Password has been copied to clipboard.', self.icon)
def setk(self, key, value): with open(self.aliasfile, 'r+') as f: alias = load(f) alias[key] = value f.seek(0) f.truncate() dump(alias, f, indent=4) WoxAPI.show_msg('set alias', '{}={}'.format(key, value))
def delk(self, key): with open(self.aliasfile, 'r+') as f: alias = load(f) alias.pop(key) f.seek(0) f.truncate() dump(alias, f, indent=4) WoxAPI.show_msg('remove alias', '{}'.format(key))
def wrap(*args, **kwargs): try: return func(*args, **kwargs) except: error = traceback.format_exc() WoxAPI.show_msg("error", error) Log.error(error) os.system(r'explorer "{}"'.format(os.getcwd()))
def saveSteamAppsDirectory(self, path): plugin_conf = self.plugin_conf plugin_conf['steamapps_dir'] = re.sub(r'[/\\]+', '/', path.rstrip('/\\')) + '/' self.steam_apps_dir = plugin_conf['steamapps_dir'] with codecs.open('./config.json', 'w', 'utf-8') as f: json.dump(plugin_conf, f, indent=4) WoxAPI.show_msg("Steam apps directory path has been saved", plugin_conf['steamapps_dir'])
def store_tip(self, info): try: times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) tip = {"tip": info, "updated_time": times} with open(self.TIPS_FILE, "a") as f: f.write(json.dumps(tip) + "\n") WoxAPI.change_query("tip") except: logging.error(traceback.format_exc())
def createPalette(self, name): self.initializeLibrary() self.library['palettes'].append({ "name": name, "colors": [] }) self.saveLibrary() WoxAPI.change_query("tint palette " + name)
def open_webpage(self, url, notification=True): """Trivial implementation of bookmarks in Wox Demonstrates how optional parameters in Json RPC are handled. """ if notification: WoxAPI.show_msg('Heads up', 'We opened in new window') webbrowser.open_new(url) else: webbrowser.open(url)
def addColor(self, paletteName, hexColor): self.initializeLibrary() palette = self.findPalette(paletteName) if palette: palette['colors'].append({ 'hex': hexColor }) self.saveLibrary() WoxAPI.change_query("tint palette " + paletteName)
def __init__(self): Wox.__init__(self) watcher = clipmonitor.ClipboardWatcher(self.check_clipboard, self.append_datalist, 5.) watcher.start() while True: try: time.sleep(10) except Exception as e: watcher.stop() WoxAPI.show_msg('Error ' + str(e)) break
def mark_as_done(self, url): try: api = todoist.TodoistAPI(token=self.get_todoist_api_key()) items = api.state['items'] filtered = [i for i in items if i['id'] == int(url)] item_to_complete = filtered[0] item_to_complete.complete() api.commit() api.sync() WoxAPI.show_msg("Marked as done", "GZ!") except Exception as e: WoxAPI.show_msg("Something went wrong :( :(", f"{str(e)}")
def add_new_domain(self,domain): if not domain: WoxAPI.show_msg("Warning","You can't add empty domain") return r = re.compile(r"domains = {([\s\S]*)};") with open(self.get_pac_path(),"r+") as pac: pactxt = pac.read() existing_domains = r.search(pactxt).group(1) domains = json.loads("{" + existing_domains + "}") domains[domain] = 1 newpactxt = r.sub(r"domains = " + json.dumps(domains,indent = 4) +";",pactxt) pac.seek(0) pac.write(newpactxt) pac.truncate() WoxAPI.show_msg("Success","{} is now in PAC file".format(domain))
def update_github(): """从github上clone或pull最新的文件""" try: if not os.path.exists(cmdblog_path): os.chdir(dir) # os.mkdir(cmdblog_path) # git clone 可以生成该文件夹 os.system("git clone https://github.com/basicsp/cmdblog.git") WoxAPI.show_msg('update_github', 'git clone is over.') else: os.chdir(cmdblog_path) os.system("git pull") WoxAPI.show_msg('update_github', 'git pull is over.') except Exception as e: return str(e) else: return True
def delete_tip(self, times): try: tips = [] with open(self.TIPS_FILE, "r") as f: for line in f: tips.append(json.loads(line.strip())) for tip in tips: if times == tip["updated_time"]: tips.remove(tip) break with open(self.TIPS_FILE, "w") as f: for tip in tips: f.write(json.dumps(tip) + "\n") WoxAPI.change_query("tip") except: logging.error(traceback.format_exc())
def add_new_domain(self, domain): if not domain: WoxAPI.show_msg("Warning", "You can't add empty domain") return r = re.compile(r"domains = {([\s\S]*)};") with open(self.get_pac_path(), "r+") as pac: pactxt = pac.read() existing_domains = r.search(pactxt).group(1) domains = json.loads("{" + existing_domains + "}") domains[domain] = 1 newpactxt = r.sub( r"domains = " + json.dumps(domains, indent=4) + ";", pactxt) pac.seek(0) pac.write(newpactxt) pac.truncate() WoxAPI.show_msg("Success", "{} is now in PAC file".format(domain))
def activate(self, service, title, query): action = "toggle" if get_type(service) == "media_player": action = "media_play_pause" if query != title: action = None WoxAPI.change_query("ha " + title + " ",True) try: if action != None: post_data('http://' + ha_ip + ':' + ha_port + '/api/services/' + str(get_type(service)) + '/' + str(action) + '?api_password=' + ha_password,{ "entity_id": str(service) }) #WoxAPI.start_loadingbar(self) #time.sleep(0.8) #WoxAPI.stop_loadingbar(self) #if query.endswith("trigger"): #WoxAPI.change_query("dimming " + fn,True) #else: #WoxAPI.change_query("ha " + fn,True) except: pass
def make_qr_image(self, context): logging.debug("starting make QRImage...") QRImageName = "qrcode_{}.jpg".format(md5(context)) QRImagePath = os.path.join(self.img_path, QRImageName) logging.debug("QRImagePath is %s" % QRImagePath) if not os.path.exists(QRImagePath): logging.debug("QRImage file not exists,so need make") img = qrcode.make(context, border=1) img.save(QRImagePath) logging.debug("make QRImage ok, this file size is %s" % os.path.getsize(QRImagePath)) else: logging.debug("has cache, use cache image") # Wox输入框可能会遮挡二维码 WoxAPI.hide_app() return self.show_image(QRImagePath)
def learn(self, wordId): if False == self.hasToken(): self.authorize() return token = self.getToken() if not token: WoxAPI.show_msg('token失效', 'token expiresed') return payload = {'id': wordId} r = requests.post(LEARNING_API + token, data=payload) if r.json()['status_code'] == 0: WoxAPI.show_msg('已添加', 'already added') else: WoxAPI.show_msg('请检查token', 'pls check token file')
def change_query(self, query): WoxAPI.change_query(query)
def openUrl(self, url): webbrowser.open(url) WoxAPI.change_query(url)
def openUrl(self,url): webbrowser.open(url) #remove input from Wox line WoxAPI.change_query('')
def open_url(self, url): webbrowser.open(url) WoxAPI.change_query(url)
def copy(self, ans): if flag: pyperclip.copy(ans) else: WoxAPI.change_query("ERROR: pyperclip is not installed", True)
def change_query_method(self, query): WoxAPI.change_query(query + '(')
def openFolder(self, path: str): os.startfile(path) WoxAPI.change_query(path)
def clean_cache(self, contest): shutil.rmtree(self.img_path) WoxAPI.show_msg("Success", " clean up cache file done", self.plugin_ico)
def copy_clip(self, query): pyperclip.copy(query) WoxAPI.hide_app()
def selectConfig(self, item): WoxAPI.change_query("{} {}".format(PREFIX_CONFIG, item), True)
def openUrl(self, url): webbrowser.open(url) # todo:doesn't work when move this line up WoxAPI.change_query(url)
def config(self, text): WoxAPI.change_query('yt --config ' + text)
def openConfig(self): WoxAPI.change_query(PREFIX_CONFIG, True)
def openUrl(self, url): # webbrowser.open(url) webbrowser.open_new_tab(url) WoxAPI.change_query(url)
def query(self, query): results = [] argument = "" argument = query.split() #---handle connection errors if len(argument) >= 1: for keywords in key_services: title = keywords subtext = keywords ico = './icons/icons_' + icon_color + "/filter.png" if query.strip().lower() in keywords.lower(): #---add filters to results if argument[0] not in key_services: results.append({ "Title": "Filter by: [" + keywords + "]", "SubTitle": "show " + keywords + " services only", "IcoPath":ico, "JsonRPCAction": { "method": "Wox.ChangeQuery", "parameters": ["ha" + " " + keywords, True], "dontHideAfterAction": True } }) service = get_entity(argument[0]) if service == -1: WoxAPI.change_query("ha connection error",True) for x in range(0, len(service)): entity_id = service[x]["entity_id"] try: title = service[x]["attributes"]["friendly_name"] except: title = entity_id state = service[x]["state"] try: unit_of_measurement = service[x]["attributes"]["unit_of_measurement"] state += unit_of_measurement except: pass ico = get_icon(entity_id,state) subtext = get_attributes(service,x) #----Check if user is refrencing a service keyword and filters it out of query if argument[0].rstrip("s") in key_services: if query.replace(argument[0],"",1).strip().lower() in title.lower(): results.append({ "Title": title + " is " + '\"' + state + '\"', "SubTitle": subtext, "IcoPath":ico, "JsonRPCAction":{ "method": "activate", "parameters":[entity_id,title,query], "dontHideAfterAction":True, } }) else: #----check if query matches any results if query.lower().strip() in title.lower(): results.append({ "Title": title + " is " + '\"' + state + '\"', "SubTitle": subtext, "IcoPath":ico, "JsonRPCAction":{ "method": "activate", "parameters":[entity_id,title,query], "dontHideAfterAction":True } }) #----Check to see if only one match and if exact match of title (No false positives when using filters) if query.lower().strip().startswith(title.lower()): results = [] #----Add entry for every attribute if not query.lower().replace(title.lower(),"",1).strip().startswith("info".lower()): if get_type(entity_id) == "light": ico = get_icon(entity_id, state) percentage = query.lower().replace(title.lower(),"",1).strip() results.append({ "Title": "Adjust Brightness", "SubTitle": "Adjust brightness level to " + query.replace(title.lower(),"",1).lower().strip() + "%", "IcoPath":ico, "JsonRPCAction":{ "method": "adjust_brightness", "parameters":[entity_id,percentage], "dontHideAfterAction":True } }) results.append({ "Title": "Toggle", "SubTitle": "Toggle " + title, "IcoPath":ico, "JsonRPCAction":{ "method": "activate", "parameters":[entity_id,title,query], "dontHideAfterAction":True } }) else: results.append({ "Title": "Action", "SubTitle": "Activate default action for " + get_type(entity_id), "IcoPath":ico, "JsonRPCAction":{ "method": "activate", "parameters":[entity_id,title,query], "dontHideAfterAction":True } }) if subtext != "N/A": ico = './icons/icons_' + icon_color + '/info.png' results.append({ "Title": "Info", "SubTitle": "Show detailed information", "IcoPath":ico, "JsonRPCAction": { "method": "Wox.ChangeQuery", "parameters": ["ha " + query + " info" , True], "dontHideAfterAction": True } }) if query.lower().replace(title.lower(),"",1).strip().startswith("info".lower()): results = [] for g in range(len(service[x]["attributes"].keys())): key = list(service[x]["attributes"].keys())[g].replace("_"," ") value = service[x]["attributes"].values()[g] try: value = removeNonAscii(value) except: value = value ico = './icons/icons_' + icon_color + '/info.png' if key != "friendly name" and key != "unit of measurement": if query.lower().replace(title.lower(),"",1).replace("info","",1).lower().strip().lower() in str(value).lower().strip().lower(): results.append({ "Title": value, "SubTitle": key, "IcoPath": ico, "JsonRPCAction": { "method": "Wox.ChangeQuery", "parameters": [str(key) + ": " + str(value), True], "dontHideAfterAction": True } }) #----No user input except action word else: for keywords in key_services: title = keywords subtext = keywords ico = './icons/icons_' + icon_color + "/filter.png" results.append({ "Title": "Filter by: [" + keywords + "]", "SubTitle": "show " + keywords + " services only", "IcoPath":ico, "JsonRPCAction": { #change query to show only service type "method": "Wox.ChangeQuery", "parameters": ["ha" + " " + keywords, False], # hide the query wox or not "dontHideAfterAction": True } }) return results
def saveConfig(self, jkey, value): WoxAPI.change_query('') self.configfile[jkey] = value with open(os.path.join(os.path.dirname(__file__),"config.json"), "w+") as jsonFile: jsonFile.write(json.dumps(self.configfile)) jsonFile.close()
def pasteContent(self): if _clipboard_exit: key = clipboard.paste() WoxAPI.change_query("wb " + key)
def openUrl(self, url): webbrowser.open(url) #remove input from Wox line WoxAPI.change_query('')
def change_query(self, query): # change query and copy to clipboard after pressing enter WoxAPI.change_query(query) copy_to_clipboard(query)
def openUrl(self, url): # open the browser import webbrowser webbrowser.open(url) # todo:doesn't work when move this line up WoxAPI.change_query(url)
def navigate(self, command): WoxAPI.change_query(command)