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_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(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(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_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_albert_items_full(self, query_str): item = self.get_as_albert_item() item.subtext = query_str item.addAction( v0.FuncAction( "Add task", lambda args_list=["add", *query_str.split()]: run_tw_action(args_list), ) ) return [item]
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(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): 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(path: Path): return v0.Item( id=__prettyname__, icon=icon_path, text=path.stem, completion="", actions=[ v0.FuncAction( "Copy 2FA code", lambda name=path.stem: subprocess.check_output( ["totp", "show", name]).strip(), ) ], )
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=__prettyname__, icon=icon, text=stream.name, subtext=stream.description if stream.description else "", completion="", actions=actions, )
def get_tw_item(task: taskw.task.Task) -> v0.Item: """Get a single TW task as an Albert Item.""" field = get_as_subtext_field actions = [ v0.FuncAction( "Complete task", lambda args_list=["done", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Delete task", lambda args_list=["delete", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Start task", lambda args_list=["start", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Stop task", lambda args_list=["stop", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Edit task interactively", lambda args_list=["edit", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.ClipAction("Copy task UUID", f"{tw_side.get_task_id(task)}"), ] 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", tw_side.get_task_id(task), f"+{reminders_tag}", ]: run_tw_action(args_list), ) ) urgency_str, icon = urgency_to_visuals(task.get("urgency")) return get_as_item( text=f'{task["description"]}', subtext="{}{}{}{}{}".format( field(urgency_str), "ID: {}... | ".format(tw_side.get_task_id(task)[:8]), field(task["status"]), field(task.get("tags"), "tags"), field(task.get("due"), "due"), )[:-2], icon=icon, completion="", actions=actions, )
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
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 # new behavior tokens = query_str.split() if len(tokens) >= 1 and tokens[0] == "new": if len(tokens) > 1: name = tokens[1] else: name = "" if len(tokens) > 2: desc = " ".join(tokens[2:]) else: desc = "" results.append( v0.Item( id=__prettyname__, icon=icon_path, text=f"New abbreviation: {name}", subtext=f"Description: {desc}", actions=[ v0.FuncAction( f"Save abbreviation to file", lambda name=name, desc=desc: save_abbr( name, desc), ) ], )) return results curr_hash = hash_file(abbreviations_path) global abbr_latest_hash, abbr_latest_d, abbr_latest_d_bi if abbr_latest_hash != curr_hash: abbr_latest_hash = curr_hash with open(abbreviations_path) as f: conts = f.readlines() abbr_latest_d = make_latest_dict(conts) abbr_latest_d_bi = abbr_latest_d.copy() abbr_latest_d_bi.update( {v: k for k, v in abbr_latest_d.items()}) if not abbr_latest_d: results.append( v0.Item( id=__prettyname__, icon=icon_path, text= f'No lines split by "{split_at}" in the file provided', actions=[ v0.ClipAction( f"Copy provided filename", str(abbreviations_path), ) ], )) return results # do fuzzy search on both the abbreviations and their description matched = process.extract(query_str, abbr_latest_d_bi.keys(), limit=10) for m in [elem[0] for elem in matched]: if m in abbr_latest_d.keys(): results.append(get_abbr_as_item((m, abbr_latest_d[m]))) else: results.append(get_abbr_as_item((abbr_latest_d_bi[m], 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 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() cmdline_to_procs = get_cmdline_to_procs() matched = [ elem[0] for elem in process.extract( query_str, cmdline_to_procs.keys(), limit=15) ] extra_actions = [] if any([symbol in query_str for symbol in "*?[]"]): extra_actions = [ v0.FuncAction( "Terminate by glob", lambda: list( map(lambda p: p.terminate(), globsearch_procs(query_str))), ), v0.FuncAction( "Kill by glob", lambda: list( map(lambda p: p.kill(), globsearch_procs(query_str) )), ), ] for m in matched: for p in cmdline_to_procs[m]: results.append(get_as_item(p, *extra_actions)) # filtering step results = [r for r in results if r is not None] 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: """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_parts = query.string.strip().split() name = None if query_parts: name = query_parts.pop(0) subtext = f'Name: {name if name else "Not given"}' results.extend([ v0.Item( id=__prettyname__, icon=countdown_path, text="Create countdown", subtext= f'{subtext}{" - <u>Please provide a duration</u>" if not query_parts else ""}', completion=__trigger__, actions=[ v0.FuncAction( "Create countdown", lambda name=name, query_parts=query_parts: create_countdown( name, *query_parts, ), ) ], ), v0.Item( id=__prettyname__, icon=stopwatch_path, text="Create stopwatch", subtext=subtext, completion=__trigger__, actions=[ v0.FuncAction( "Create stopwatch", lambda name=name, query_parts=query_parts: create_stopwatch( name, *query_parts, ), ) ], ), ]) # cleanup watches that are done for li in [ countdowns, stopwatches, ]: for watch in li: if watch.to_remove(): li.remove(watch) results.extend([get_as_item(item) for item in all_watches()]) 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=countdown_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 = [] if not shutil.which("pass"): results.append( v0.Item( id=__prettyname__, 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=__prettyname__, 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=__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")) ], )) return results # api_key if not api_key_path.is_file(): results.append( v0.Item( id=__prettyname__, 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) -> 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 query_text = query.string.strip() if not len(query_text): results = [ v0.Item( id=__prettyname__, icon=icon_path, text="Update tldr database", actions=[ v0.FuncAction("Update", lambda: update_tldr_db()) ], ), v0.Item( id=__prettyname__, icon=icon_path, text="Reindex tldr pages", actions=[ v0.FuncAction("Reindex", lambda: reindex_tldr_pages()) ], ), v0.Item( id=__prettyname__, icon=icon_path, text="Need at least 1 letter to offer suggestions", actions=[], ), ] + results return results if query_text in page_paths.keys(): # exact match - show examples results.extend( get_cmd_items((query_text, page_paths[query_text]))) else: # fuzzy search based on word matched = process.extract(query_text, page_paths.keys(), limit=20) for m in [elem[0] for elem in matched]: results.append(get_cmd_as_item((m, page_paths[m]))) except Exception: # user to report error if in_development: 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): tokens = query.string.split() if tokens and "pomodoro".startswith(tokens[0].lower()): global pomodoro pattern = re.compile(query.string, re.IGNORECASE) item = v0.Item( id=__prettyname__, icon=icon_path_kill if pomodoro.is_active() else icon_path, text=pattern.sub(lambda m: "<u>%s</u>" % m.group(0), "Pomodoro Timer"), completion=query.rawString, ) if len(tokens) == 1 and pomodoro.is_active(): item.addAction(v0.FuncAction("Stop", lambda p=pomodoro: p.stop())) if pomodoro.isBreak: whatsNext = "Pomodoro" else: whatsNext = ("Long break" if pomodoro.remainingTillLongBreak == 1 else "Short break") item.subtext = "Stop pomodoro (Next: %s at %s)" % ( whatsNext, time.strftime("%X", time.localtime(pomodoro.endTime)), ) return item p_duration = 25 b_duration = 5 lb_duration = 15 count = 4 item.subtext = "Invalid parameters. Use <i> pomodoro [duration [break duration [long break duration [count]]]]</i>" if len(tokens) > 1: if not tokens[1].isdigit(): return item p_duration = int(tokens[1]) if len(tokens) > 2: if not tokens[2].isdigit(): return item b_duration = int(tokens[2]) if len(tokens) > 3: if not tokens[3].isdigit(): return item lb_duration = int(tokens[3]) if len(tokens) > 4: if not tokens[4].isdigit(): return item count = int(tokens[4]) if len(tokens) > 5: return item item.subtext = ( "Start new pomodoro timer (%s min/Break %s min/Long break %s min/Count %s)" % (p_duration, b_duration, lb_duration, count)) item.addAction( v0.FuncAction( "Start", lambda p=p_duration, b=b_duration, lb=lb_duration, c=count: pomodoro.start(p, b, lb, c), )) return item
def handleQuery(query) -> list: # noqa results = [] if len(query.rawString.strip()) <= 1 and is_radio_on(): results.insert( 0, v0.Item( id=__prettyname__, icon=stop_icon_path, text="Stop Radio", actions=[v0.FuncAction("Stop Radio", lambda: stop_radio())], ), ) if query.isTriggered: results.insert( 0, v0.Item( id=__prettyname__, icon=repeat_icon_path, text="Reindex stations", actions=[v0.FuncAction("Reindex", lambda: init_streams())], ), ) 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().lower() if not query_str: for stream in streams: results.append(get_as_item(stream)) else: for stream in streams: if query_str in stream.name.lower() or ( stream.description and stream.description.lower()): results.append(get_as_item(stream)) 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): results = [] if query.isTriggered: try: results_setup = setup(query) if results_setup: return results_setup query_string = query.string if "remove server" in query_string: results.append( v0.Item(id=__prettyname__, icon=icon_path, text="Remove server", subtext="press [ENTER]", actions=[ v0.FuncAction(f"Removing stored server", remove_server()) ])) else: results.append( v0.Item( id=__prettyname__, icon=icon_path, text="Open issue...", actions=[ v0.UrlAction(f"Open issue in Jira", get_issue_path(query_string)) ], )) results.append( v0.Item( id=__prettyname__, icon=icon_path, text="Search for issue...", actions=[ v0.UrlAction(f"Search for issue in Jira", get_search_path(query_string)) ], )) except Exception: 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"Copied error - report this problem", f"{traceback.format_exc()}", ), v0.UrlAction( f"Report error!", "https://github.com/gabrielczar/albert-jira-extension/issues/new" ) ], ), ) return results
def get_tw_item(task: taskw.task.Task) -> v0.Item: """Get a single TW task as an Albert Item.""" field = get_as_subtext_field actions = [ v0.FuncAction( "Complete task", lambda args_list=["done", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Delete task", lambda args_list=["delete", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Start task", lambda args_list=["start", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Stop task", lambda args_list=["stop", tw_side.get_task_id(task)]: run_tw_action(args_list), ), v0.FuncAction( "Edit task interactively", lambda args_list=["edit", tw_side.get_task_id(task)]: run_tw_action(args_list, need_pty=True), ), v0.ClipAction("Copy task UUID", f"{tw_side.get_task_id(task)}"), ] 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", tw_side.get_task_id(task), f"+{reminders_tag}", ]: run_tw_action(args_list), ) ) urgency_str, icon = urgency_to_visuals(task.get("urgency")) return get_as_item( text=f'{task["description"]}', subtext="{}{}{}{}{}".format( field(urgency_str), "ID: {}... | ".format(tw_side.get_task_id(task)[:8]), field(task["status"]), field(task.get("tags"), "tags"), field(task.get("due"), "due"), )[:-2], icon=icon, completion="", actions=actions, )