def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string if len(query_str) < 2: keys_monitor.reset() return results keys_monitor.report() if keys_monitor.triggered(): bing_images = list( bing_search_save_to_cache(query=query_str, limit=10)) if not bing_images: results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text="No images found", subtext=f"Query: {query_str}", ), ) return results results.extend(get_bing_results_as_items(bing_images)) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def handleQuery(query) -> list: results = [] if not query.isTriggered: if not query.string: results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f'Search {"_".join("search_stackoverflow".split("_")[1:])}', completion=__trigger__, ) ) else: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() # setup stage --------------------------------------------------------------------- results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() # too small request - don't even send it. if len(query_str) < 2: keys_monitor.reset() return results # determine if we can make the request -------------------------------------------- keys_monitor.report() if keys_monitor.triggered(): json_results = query_googler(query_str) googler_results = [ get_googler_result_as_item(googler_result) for googler_result in json_results ] results.extend(googler_results) except Exception: # user to report error raise results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text="Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def handleQuery(query): results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string src, dst = extract_src_dst(query_str) if src and dst: actions = [] for m in available_means: actions.append( v0.FuncAction( m.capitalize(), lambda src=src, dst=dst, m=m: spawn_and_launch_route(src, dst, means=m))) results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f"Open route (takes ~5s)", subtext=f"{src} -> {dst}", actions=actions, )) except Exception: # user to report error results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{sys.exc_info()}", ) ], ), ) return results
def get_as_item(item: Union[Countdown, Stopwatch]): """Return an item - ready to be appended to the items list and be rendered by Albert.""" actions = [v0.FuncAction( "Remove", lambda: delete_item(item), )] if item.started(): actions.append(v0.FuncAction( "Pause", lambda: item.pause(), )) else: actions.append(v0.FuncAction( "Resume", lambda: item.start(), )) return v0.Item( id=__prettyname__, icon=countdown_path if isinstance(item, Countdown) else stopwatch_path, text=str(item), subtext="", completion=__trigger__, actions=actions, )
def get_as_item(p: Process, *extra_actions): """Return an item - ready to be appended to the items list and be rendered by Albert. if Process is not a valid object (.name or .cmdline raise an exception) then return None """ name_field = cmdline(p) if not name_field: return None try: actions = [ v0.FuncAction("Terminate", lambda: p.terminate()), v0.FuncAction("Kill", lambda: p.kill()), v0.ClipAction("Get PID", f"{p.pid}"), v0.FuncAction( "Terminate matching names", lambda name=p.name(): kill_by_name(name, signal=signal.SIGTERM ), ), v0.FuncAction("Kill matching names", lambda name=p.name(): kill_by_name(name)), ] actions = [*extra_actions, *actions] return v0.Item( id=__prettyname__, icon=icon_path, text=name_field, subtext="", completion=p.name(), actions=actions, ) except psutil.NoSuchProcess: return None
def get_as_item(s): actions = [] if s.details_url: actions.append(v0.UrlAction("Open on Zoopla", s.details_url)) if s.floor_plan: actions.append(v0.UrlAction("Floorplan", s.floor_plan[0])) if s.price: actions.append(v0.ClipAction("Copy price", str(s.price))) if s.price: if s.listing_status == "rent": price_str = f"Weekly: £{s.price} | " else: price_str = f"Total: £{s.price} | " else: price_str = "" return v0.Item( id=__prettyname__, icon=iconPath, text=f"{s.description}", subtext="{}{}{}".format( f"Type: {s.property_type} | " if s.property_type else "", f"Code: {s.outcode} | " if s.outcode else "", price_str, f"# Bedrooms: {s.num_bedrooms} | " if s.num_bedrooms else "", )[:-2], actions=actions, )
def handleQuery(query): results = [] if query.isTriggered: try: if len(query.string) >= 3: query_dict = format_query(query) search = zoopla.property_listings(query_dict) for s in search["listing"]: results.append(get_as_item(s)) except Exception: # user to report error results.insert( 0, v0.Item( id=__prettyname__, icon=iconPath, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{sys.exc_info()}", ) ], ), ) return results
def handleQuery(query) -> list: results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup # modify this... results.append(get_as_item()) except Exception: # user to report error results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_cmd_as_item(pair: Tuple[str, Path]): with open(pair[-1], "r") as f: all_lines = f.readlines() description_lines = [ li.lstrip("> ").rstrip().rstrip(".") for li in all_lines if li.startswith("> ") ] # see if there's a line with more information and a URL more_info_url = None try: more_info = [li for li in all_lines if "More information" in li][0] more_info_url = re.search("<(.*)>", more_info) if more_info_url.groups(): more_info_url = more_info_url.groups()[0] except IndexError: pass actions = [ v0.ClipAction("Copy command", pair[0]), v0.UrlAction("Do a google search", f'https://www.google.com/search?q="{pair[0]}" command'), ] if more_info_url: actions.append(v0.UrlAction("More information", more_info_url)) return v0.Item( id=__prettyname__, icon=icon_path, text=pair[0], completion=" ".join([__trigger__, pair[0]]), subtext=" ".join(description_lines), actions=actions, )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() query_str = query.string.strip() results.append(get_as_item(query_str if query_str else randstr())) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(color): """Return an item - ready to be appended to the items list and be rendered by Albert.""" img_path = str(get_color_thumbnail(color)) rgb = [int(i * 255) for i in color.get_rgb()] hl = color.get_hex_l() if hl in h_to_color_name: name = f"| {h_to_color_name[hl]}" else: name = "" actions = [ v0.ClipAction("Copy Hex (Long)", hl), v0.ClipAction("Copy RGB", f"{rgb}"), v0.ClipAction("Copy RGB [0, 1]", f"{color.get_rgb()}"), ] h = color.get_hex() if h != hl: actions.insert(0, v0.ClipAction("Copy Hex (Short)", h)) return v0.Item( id=__prettyname__, icon=img_path, text=f'<p style="color:{hl}";>{hl}{name}</p>', subtext=f"{rgb}", completion=" ".join([__trigger__, h]), actions=actions, )
def get_as_item(city: str): """Return an item - ready to be appended to the items list and be rendered by Albert.""" code = city_to_code[city] icon = str(get_logo_path_for_code(code)) utc_dt = pytz.utc.localize(datetime.utcnow()) dst_tz = pytz.timezone(city) dst_dt = utc_dt.astimezone(dst_tz) text = f"{str(dst_dt)}" subtext = f"[{code}] | {city}" return v0.Item( id=__prettyname__, icon=icon, text=text, subtext=subtext, completion=city, actions=[ v0.UrlAction( "Open in zeitverschiebung.net", f'https://www.zeitverschiebung.net/en/timezone/{city.replace("/", "--").lower()}', ), ], )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() matched = [ elem[0] for elem in process.extract(query_str, [*cities, *countries], limit=8) ] matched2 = [] # replace country names with its cities for m in matched: if m in countries: matched2.extend(*country_to_cities[m]) else: matched2.append(m) matched2 = get_uniq_elements(matched2) # add own timezone: if local_tz_str in matched2: matched2.remove(local_tz_str) matched2.insert(0, local_tz_str) results.extend([get_as_item(m) for m in matched2]) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def get_as_item(result: BingImage): """Return an item. Will return None if the link to the image is not reachable (e.g., on 404) """ try: img = str(result.image.absolute()) except RequestException: return None actions = [ v0.ClipAction("Copy url", result.url), v0.ClipAction("Copy local path to image", img), v0.UrlAction("Open in browser", result.url), ] if result.type != "gif": actions.insert( 0, v0.FuncAction("Copy image", lambda result=result: copy_image(result))) item = v0.Item( id=__prettyname__, icon=str(result.image), text=result.url[-20:], subtext=result.type, completion=f"{__trigger__}", actions=actions, ) return item
def get_as_item(issue: resources.Issue, jira): field = get_as_subtext_field # first action is default action actions = [ v0.UrlAction("Open in jira", f"{issue.permalink()}"), v0.ClipAction("Copy jira URL", f"{issue.permalink()}"), ] # add an action for each one of the available transitions curr_status = issue.fields.status.name for a_transition in jira.transitions(issue): if a_transition["name"] != curr_status: actions.append( v0.FuncAction( f'Mark as "{a_transition["name"]}"', lambda a_transition_id=a_transition["id"]: make_transition( jira, issue, a_transition_id), )) subtext = "{}{}{}{}".format( field(issue.fields.assignee), field(issue.fields.status.name), field(issue.fields.issuetype.name), field(issue.fields.project.key, "proj"), ) subtext += prio_to_text[issue.fields.priority.name] return v0.Item( id=__prettyname__, icon=prio_to_icon[issue.fields.priority.name], text=f"{issue.fields.summary}", subtext=subtext, actions=actions, )
def get_cmd_items(pair: Tuple[str, Path]): """Return a list of Albert items - one per example.""" with open(pair[-1], "r") as f: lines = [li.strip() for li in f.readlines()] items = [] for i, li in enumerate(lines): if not li.startswith("- "): continue desc = li.lstrip("- ")[:-1] example_cmd = sanitize_string(lines[i + 2].strip("`").replace( "{{", "").replace("}}", "")) items.append( v0.Item( id=__prettyname__, icon=icon_path, text=example_cmd, subtext=desc, actions=[ v0.ClipAction("Copy command", example_cmd), v0.UrlAction( "Do a google search", f'https://www.google.com/search?q="{pair[0]}" command', ), ], )) return items
def get_googler_result_as_item(googler_item: dict): actions = [ v0.UrlAction("Open in browser", googler_item["url"]), v0.ClipAction("Copy URL", googler_item["url"]), ] # incognito search if inco_cmd: actions.insert( 1, v0.FuncAction( "Open in browser [incognito mode]", lambda url=googler_item["url"]: inco_cmd(url), ), ) # special url handler if url_handler: # check that the handler is actually there actions.insert( 0, v0.FuncAction( url_handler_desc, lambda url_handler=url_handler: subprocess.Popen( f'{url_handler} {googler_item["url"]}', shell=True), ), ) return v0.Item( id=__prettyname__, icon=icon_path, text=googler_item["title"], subtext=googler_item["abstract"], actions=actions, )
def get_as_item(text, subtext, completion="", actions=[]): return v0.Item( id=__prettyname__, icon=icon_path, text=text, subtext=subtext, completion=completion, actions=actions, )
def get_as_item(t: Tuple[str, Tuple[str, str]]): return v0.Item( id=__prettyname__, icon=icon_path, text=f"{t[0]} - {t[1][0]}", subtext=f"{t[1][1]}", completion="", actions=[], )
def handleQuery(query): results = [] # check whether I have downlaoded the latest metadata with open(last_update_path, "r") as f: date_str = float(f.readline().strip()) last_date = datetime.fromtimestamp(date_str) if datetime.now() - last_date > timedelta(days=1): # run an update daily update_date_file() update_xkcd_db() if query.isTriggered: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() try: with open(xkcd_dict, "r", encoding="utf-8") as f: d = json.load(f) if len(query.string) in [0, 1]: # Display all items for k, v in d.items(): results.append(get_as_item(k, v)) else: # fuzzy search desc_to_item = { item[1]["description"]: item for item in d.items() } matched = process.extract(query.string.strip(), list(desc_to_item.keys()), limit=20) for m in [elem[0] for elem in matched]: # bypass a unicode issue - use .get item = desc_to_item.get(m) if item: results.append(get_as_item(*item)) except Exception as e: # user to report error results.insert( 0, v0.Item( id=__prettyname__, icon=iconPath, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{sys.exc_info()}", ) ], ), ) return results
def handleQuery(query): results = [] if query.isTriggered: try: if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup tasks = tw_side.get_all_items(include_completed=False) # TODO Handle a potential subcommand - add? query_text = query.string if len(query.string) < 2: tw_side.reload_items = True results.extend( [ get_as_item(text=val, completion=f"{__trigger__} {key} ") for key, val in zip( get_prop_for_subcommands("name"), get_prop_for_subcommands("desc") ) ] ) tasks.sort(key=lambda t: t["urgency"], reverse=True) results.extend([get_tw_item(task) for task in tasks]) else: # find relevant results desc_to_task = {task["description"]: task for task in tasks} matched = process.extract(query_text, list(desc_to_task.keys()), limit=30) for m in [elem[0] for elem in matched]: task = desc_to_task[m] results.append(get_tw_item(task)) except Exception: # user to report error results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text="Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{sys.exc_info()}", ) ], ), ) return results
def get_as_item(t: Tuple[str, tuple]): return v0.Item( id=__prettyname__, icon=icon_path, text=f"{t[0]} - {t[1][0]}", subtext="", completion="", actions=[ v0.UrlAction("More info", f"https://httpstatuses.com/{t[0]}"), ], )
def get_as_item(): return v0.Item( id=__prettyname__, icon=icon_path, text=f"{sys.version}", subtext="Python version", completion="", actions=[ v0.UrlAction("Open in xkcd.com", "https://www.xkcd.com/"), v0.ClipAction("Copy URL", f"https://www.xkcd.com/"), ], )
def get_as_item(k: str, v: dict): return v0.Item( id=__prettyname__, icon=iconPath, text=v["description"], subtext=v["date-published"], completion="", actions=[ v0.UrlAction("Open in xkcd.com", f"https://www.xkcd.com/{k}"), v0.ClipAction("Copy URL", f"https://www.xkcd.com/{k}"), ], )
def setup(query) -> list: """Setup is successful if an empty list is returned. Use this function if you need the user to provide you data """ results = [] query_str = query.string # abbreviations file if not abbr_store_fname.is_file(): results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f"Specify file to read/write abbreviations to/from", subtext="Paste the path to the file, then press <ENTER>", actions=[ v0.FuncAction("Submit path", lambda p=query_str: submit_fname(Path(p))), ], )) return results if not abbr_store_sep.is_file(): results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f"Specify separator *character* for abbreviations", subtext=f"Separator: {query_str}", actions=[ v0.FuncAction("Submit separator", lambda c=query_str: submit_sep(c)), ], )) return results return results
def get_as_item(): """Return an item - ready to be appended to the items list and be rendered by Albert.""" return v0.Item( id=__prettyname__, icon=icon_path, text=f"{sys.version}", subtext="Python version", completion="", actions=[ v0.UrlAction("Open in xkcd.com", "https://www.xkcd.com/"), v0.ClipAction("Copy URL", f"https://www.xkcd.com/"), ], )
def get_googler_result_as_item(googler_item: dict): actions = [ v0.UrlAction("Open in browser", googler_item["url"]), v0.ClipAction("Copy URL", googler_item["url"]), ] return v0.Item( id=__prettyname__, icon=icon_path, text=googler_item["title"], subtext=googler_item["abstract"], actions=actions, )
def get_as_item(email): """Return an item - ready to be appended to the items list and be rendered by Albert.""" return v0.Item( id=__prettyname__, icon=icon_path, text=f"Temporary email: <u>{email}</u>", subtext="", completion=f"{__trigger__} {email}", actions=[ v0.FuncAction("Open in browser (and copy email address)", lambda email=email: copy_and_go(email)), ], )
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: # be backwards compatible with v0.2 if "disableSort" in dir(query): query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string.strip() if not query_str: return results # see if the name matches a color exactly color = get_as_color(query_str) if color: results.append(get_as_item(color)) return results # no exact match matched = process.extract(query_str, list(color_names_and_hex), limit=10) for m in [elem[0] for elem in matched]: results.append(get_as_item(Color(m))) except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text="Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def setup(query): results = [] try: if not server_path.is_file(): results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f"Please specify the JIRA server to connect to", subtext="Fill and press [ENTER]", actions=[ v0.FuncAction( "Save JIRA server", lambda: save_data(query.string, "server")) ], )) except Exception: remove_server() results.insert( 0, v0.Item( id=__prettyname__, icon=icon_path, text="Something went wrong! Please try again!", actions=[ v0.ClipAction( f"Copy error - report this problem", f"{traceback.format_exc()}", ), v0.UrlAction( f"Report error!", "https://github.com/gabrielczar/albert-jira-extension/issues/new" ) ], ), ) return results