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.lower()][0] more_info_url = re.search("<(.*)>", more_info) if more_info_url is not None and 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=__title__, icon=icon_path, text=pair[0], completion=" ".join([__triggers__, pair[0]]), subtext=" ".join(description_lines), actions=actions, )
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=__title__, 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): if not query.isTriggered: return None stripped = query.string.strip() if not stripped: return albert.Item( id=__title__, icon=icon_path, text=__title__, subtext="Search NASA ADS", completion=query.rawString, ) query_string = parse_query_string(stripped) return [ albert.Item( id=__title__, icon=icon_path, text="Sorted by date", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string, ) ], ), albert.Item( id=__title__, icon=icon_path, text="Sorted by popularity", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string + "&sort=classic_factor desc", ) ], ), albert.Item( id=__title__, icon=icon_path, text="Sorted by citation count", subtext=query_string, completion=query.rawString, actions=[ albert.UrlAction( "Search on the web", "https://ui.adsabs.harvard.edu/search/q=" + query_string + "&sort=citation_count desc", ) ], ), ]
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=__title__, icon=str(result.image), text=result.url[-20:], subtext=result.type, completion=f"{__triggers__}", 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=__title__, icon=prio_to_icon[issue.fields.priority.name], text=f"{issue.fields.summary}", subtext=subtext, 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=__title__, 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 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=__title__, icon=icon_path, text=googler_item["title"], subtext=googler_item["abstract"], 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=__title__, 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_as_item(t: Tuple[str, tuple]): return v0.Item( id=__title__, 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 an item - ready to be appended to the items list and be rendered by Albert.""" return v0.Item( id=__title__, 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(stream: Stream): icon = stream.icon() or icon_path actions = [ v0.FuncAction("Play", lambda stream=stream: start_stream(stream)) ] if stream.homepage: actions.append(v0.UrlAction("Go to radio homepage", stream.homepage)) return v0.Item( id=__title__, icon=icon, text=stream.name, subtext=stream.description if stream.description else "", completion="", actions=actions, )
def get_abbr_as_item(abbr: Tuple[str, str]): """Return the abbreviation pair as an item - ready to be appended to the items list and be rendered by Albert.""" text = abbr[0].strip() subtext = abbr[1].strip() return v0.Item( id=__title__, icon=icon_path, text=f"{text}", subtext=f"{subtext}", completion=f"{__triggers__}{text.strip()}", actions=[ v0.UrlAction("Open in Google", f"https://www.google.com/search?&q={text}"), v0.ClipAction("Copy abbreviation", text), v0.ClipAction("Copy description", subtext), ], )
def setup(query): # type: ignore results = [] if not which("task"): results.append( v0.Item( id=__title__, icon=icon_path, text=f'"taskwarrior" is not installed.', subtext= 'Please install and configure "taskwarrior" accordingly.', actions=[ v0.UrlAction('Open "taskwarrior" website', "https://taskwarrior.org/download/") ], )) return results return results
def setup(query): """setup is successful if an empty list is returned. Use this function if you need the user to provide you data """ results = [] if not shutil.which("googler"): results.append( v0.Item( id=__title__, icon=icon_path, text=f'"googler" is not installed.', subtext='Please install and configure "googler" accordingly.', actions=[ v0.UrlAction('Open "googler" website', "https://github.com/jarun/googler") ], )) return results
def get_tw_item(task: taskw.task.Task) -> v0.Item: # type: ignore """Get a single TW task as an Albert Item.""" field = get_as_subtext_field task_id = tw_side.get_task_id(task) actions = [ v0.FuncAction( "Complete task", lambda args_list=["done", task_id]: run_tw_action(args_list), ), v0.FuncAction( "Delete task", lambda args_list=["delete", task_id]: run_tw_action(args_list), ), v0.FuncAction( "Start task", lambda args_list=["start", task_id]: run_tw_action(args_list), ), v0.FuncAction( "Stop task", lambda args_list=["stop", task_id]: run_tw_action(args_list), ), v0.FuncAction( "Edit task interactively", lambda args_list=["edit", task_id]: run_tw_action(args_list, need_pty=True), ), v0.FuncAction( "Fail task", lambda args_list=[task_id, "done", failure_annotation]: run_tw_action(args_list), ), v0.ClipAction("Copy task UUID", f"{task_id}"), ] found_urls = url_re.findall(task["description"]) if "annotations" in task.keys(): found_urls.extend(url_re.findall(" ".join(task["annotations"]))) for url in found_urls[-1::-1]: actions.insert(0, v0.UrlAction(f"Open {url}", url)) if reminders_tag_path.is_file(): reminders_tag = load_data(reminders_tag_path) actions.append( v0.FuncAction( f"Add to Reminders (+{reminders_tag})", lambda args_list=[ "modify", task_id, f"+{reminders_tag}", ]: run_tw_action(args_list), )) urgency_str, icon = urgency_to_visuals(task.get("urgency")) text = f'{task["description"]}' if "start" in task: text = f'<p style="color:orange;">{text}</p>' due = None if "due" in task: due = task["due"].astimezone(dateutil.tz.tzlocal()).strftime( "%Y-%m-%d %H:%M:%S") # type: ignore return get_as_item( text=text, subtext="{}{}{}{}{}".format( field(urgency_str), "ID: {}... | ".format(tw_side.get_task_id(task)[:8]), field(task["status"]), field(task.get("tags"), "tags"), field(due, "due"), )[:-2], icon=str(icon), completion=f'{__triggers__}{task["description"]}', actions=actions, )
def setup(query): results = [] if not shutil.which("pass"): results.append( v0.Item( id=__title__, icon=icon_path, text=f'"pass" is not installed.', subtext='Please install and configure "pass" accordingly.', actions=[ v0.UrlAction('Open "pass" website', "https://www.passwordstore.org/") ], )) return results # user if not user_path.is_file(): results.append( v0.Item( id=__title__, icon=icon_path, text=f"Please specify your email address for JIRA", subtext="Fill and press [ENTER]", actions=[ v0.FuncAction("Save user", lambda: save_data(query.string, "user")) ], )) return results # jira server if not server_path.is_file(): results.append( v0.Item( id=__title__, 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")) ], )) return results # api_key if not api_key_path.is_file(): results.append( v0.Item( id=__title__, icon=icon_path, text=f"Please add api_key", subtext="Press to copy the command to run", actions=[ v0.ClipAction( "Copy command", f"pass insert {api_key_path.relative_to(pass_path).parent / api_key_path.stem}", ) ], )) return results return []
def handleQuery(query): results = [] if query.isTriggered: try: query.disableSort() fields = query.string.split() item = v0.Item( id=__title__, text=__title__, subtext='Enter a query in the form of "<srclang> <dstlang> <text>"', icon=icon_path, completion=query.rawString, ) results.append(item) if len(fields) < 3: keys_monitor.reset() return results def completion(): return f"{__triggers__}{dst} {src} {txt}" src = fields[0] dst = fields[1] txt = " ".join(fields[2:]) results[-1].completion = completion() # determine if we can make the request -------------------------------------------- keys_monitor.report() if keys_monitor.triggered(): url = url_template % (src, dst, urllib.parse.quote_plus(txt)) req = urllib.request.Request(url, headers={"User-Agent": ua}) with urllib.request.urlopen(req) as response: data = json.loads(response.read().decode("utf-8")) result = data[0][0][0] item.text = result item.subtext = "%s -> %s: %s" % ( src.upper(), dst.upper(), txt, ) item.addAction( v0.FuncAction( "Copy translation to clipboard", lambda lang_config={ "src": src, "dst": dst, "src_txt": txt, }, result=result: select_item( lang_config=lang_config, result=result ), ) ) item.addAction( v0.UrlAction( "Open in browser", f"https://translate.google.com/#view=home&op=translate&sl={src.lower()}&tl={dst.lower()}&text={txt}", ) ) # Show previous results iterator = reversed(history_deque) try: next(iterator) for di in iterator: # last is the most recent results.append( get_history_item( src=di["src"], dst=di["dst"], src_txt=di["src_txt"], dst_txt=di["dst_txt"], ) ) except StopIteration: pass except Exception: # user to report error if dev_mode: # let exceptions fly! print(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, 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: query.disableSort() results_setup = setup(query) if results_setup: return results_setup user = load_data("user") server = load_data("server") api_key = load_api_key() # connect to JIRA jira = JIRA(server=server, basic_auth=(user, api_key)) issues = jira.search_issues( "assignee = currentUser() AND status != 'Done'", maxResults=max_results_to_request, fields=",".join(fields_to_include), ) issues.sort(key=lambda issue: issue.fields.priority.id, reverse=False) results.append( v0.Item( id=__title__, icon=icon_path, text="Create new issue", actions=[ v0.UrlAction(f"Create new issue", get_create_issue_page(server)) ], )) if len(query.string.strip()) <= 2: for issue in issues[:max_results_to_show]: results.append(get_as_item(issue, jira)) else: desc_to_issue = { issue.fields.summary: issue for issue in issues } # do fuzzy search - show relevant issues matched = process.extract(query.string.strip(), list(desc_to_issue.keys()), limit=5) for m in [elem[0] for elem in matched]: results.append(get_as_item(desc_to_issue[m], jira)) except Exception: # user to report error results.insert( 0, v0.Item( id=__title__, 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