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
예제 #2
0
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=__title__,
        icon=img_path,
        text=f'<p style="color:{hl}";>{hl}{name}</p>',
        subtext=f"{rgb}",
        completion=" ".join([__triggers__, h]),
        actions=actions,
    )
def handleQuery(query) -> list:
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            for path in pass_2fa_dir.iterdir():
                results.append(get_as_item(path))

        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
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=__title__,
            icon=icon_path,
            text=name_field,
            subtext="",
            completion=p.name(),
            actions=actions,
        )
    except psutil.NoSuchProcess:
        return None
예제 #5
0
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,
    )
예제 #6
0
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=__title__,
                    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"{traceback.format_exc()}",
                        )
                    ],
                ),
            )

    return results
예제 #7
0
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
예제 #8
0
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,
    )
예제 #9
0
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,
    )
예제 #10
0
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 handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            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=__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) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            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=3))
                if not bing_images:
                    results.insert(
                        0,
                        v0.Item(
                            id=__title__,
                            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=__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
예제 #13
0
def handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            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=__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 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),
        ],
    )
예제 #15
0
def get_as_item(password_path: Path):
    full_path_no_suffix = Path(f"{password_path.parent}/{password_path.stem}")
    full_path_rel_root = full_path_no_suffix.relative_to(pass_dir)

    full_path_no_suffix_str = str(full_path_no_suffix)
    full_path_rel_root_str = str(full_path_rel_root)

    actions = [
        v0.ProcAction("Remove",
                      ["pass", "rm", "--force", full_path_rel_root_str]),
        v0.ClipAction("Copy Full Path", str(password_path)),
        v0.ClipAction(
            "Copy pass-compatible path",
            str(
                password_path.relative_to(pass_dir).parent /
                password_path.stem),
        ),
    ]

    if len(password_path.suffixes
           ) >= 2 and password_path.suffixes[-2] in pass_open_doc_exts:
        pass
        # actions.insert(
        #     0,
        #     v0.FuncAction(
        #         "Open with pass-open-doc", lambda p=str(password_path): subprocess.check_call(["pass-open-doc", p]),
        #     ),
        # )
    else:
        actions.insert(
            0, v0.ProcAction("Edit", ["pass", "edit", full_path_rel_root_str]))
        actions.insert(
            0,
            v0.ProcAction("Copy", ["pass", "--clip", full_path_rel_root_str]),
        )

    return v0.Item(
        id=__title__,
        icon=icon_path,
        text=f"{password_path.stem}",
        subtext=full_path_no_suffix_str,
        completion=f"{__triggers__} {full_path_no_suffix_str}",
        actions=actions,
    )
예제 #16
0
def handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            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=__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
예제 #17
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/"),
        ],
    )
예제 #18
0
def handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string.strip()

            # avoid racing conditions when multiple queries are running simultaneously (i.e,
            # current and previous query due to successive keystrokes)
            pulse_lock.acquire()
            sources_sinks: List[Union[pulsectl.PulseSourceInfo, pulsectl.PulseSinkInfo]] = [
                *pulse.sink_list(),
                *pulse.source_list(),
            ]
            cards: List[pulsectl.PulseCardInfo] = pulse.card_list()
            pulse_lock.release()

            if not query_str:
                results.extend(render_noargs(sources_sinks, cards))
            else:
                results.extend(render_search(sources_sinks, cards, query_str))

        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=None,
                    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
예제 #19
0
def handleQuery(query):
    results = []

    if query.isTriggered:
        try:
            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=__title__,
                        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=__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"{sys.exc_info()}",
                        )
                    ],
                ),
            )

    return results
예제 #20
0
 def get_as_item(self):
     """Return it as item - ready to be appended to the items list and be rendered by
     Albert.
     """
     return v0.Item(
         id=__title__,
         icon=str(self.img),
         text=self.title(),
         subtext="",
         completion=f"{__triggers__} {self.id} ",
         actions=[
             v0.FuncAction("Copy vanilla image",
                           lambda: self.copy_vanilla_img()),
             v0.ClipAction("Copy vanilla image path", str(self.img)),
         ],
     )
def handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string
            if len(query_str) < 2:
                results.extend([s.get_as_albert_item() for s in subcommands])

            else:
                subcommand_query = get_subcommand_query(query_str)

                if subcommand_query:
                    results.extend(
                        subcommand_query.command.get_as_albert_items_full(
                            subcommand_query.query))

        except Exception:  # user to report error
            if dev_mode:  # let exceptions fly!
                v0.critical(traceback.format_exc())
                raise

            results.insert(
                0,
                v0.Item(
                    id=__title_short__,
                    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
예제 #22
0
def handleQuery(query):
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string.strip()
            if len(query_str) == 0:
                # refresh the passwords cache
                passwords_cache.signal_refresh()

            # build a list of all the paths under pass_dir
            gpg_files = passwords_cache.get_all_gpg_files(pass_dir)

            # fuzzy search on the paths list
            matched = process.extract(query_str, gpg_files, limit=10)
            for m in [elem[0] for elem in matched]:
                results.append(get_as_item(m))

        except Exception:  # user to report error
            if dev_mode:
                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"{sys.exc_info()}",
                        )
                    ],
                ),
            )

    return results
예제 #23
0
def handleQuery(query) -> list:
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str: str = query.string
            for item in codes_d.items():
                if query_str in item[0]:
                    results.append(get_as_item(item))
                else:
                    for v in item[1]:
                        if query_str.lower() in v.lower():
                            results.append(get_as_item(item))
                            break

        except Exception:  # user to report error
            if dev_mode:
                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
예제 #24
0
def handleQuery(query) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    # trigger if the user has either explicitly called the plugin or when we have detected many
    # words in the query. The latter is just a heuristic; I haven't decided whether it's worth
    # keeping
    if query.isTriggered or len(query.rawString.split()) >= 4:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string
            # modify this...
            results.append(get_as_item(query_str))

        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
예제 #25
0
def handleQuery(query) -> list:
    results = []

    if not query.isTriggered:
        if False:
            if not query.string:
                results.append(
                    v0.Item(
                        id=__title__,
                        icon=icon_path,
                        text=
                        f'Search {"_".join("search_github".split("_")[1:])}',
                        completion=__triggers__,
                    ))
    else:
        try:
            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)

                if not results:
                    results.insert(
                        0,
                        v0.Item(
                            id=__title__,
                            icon=icon_path,
                            text="No results.",
                            actions=[],
                        ),
                    )

        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
예제 #26
0
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,
    )
예제 #27
0
def handleQuery(query):
    results = []

    # we're into the new day, create and assign a fresh instance
    last_used = last_used_date.get()
    current_date = datetime.datetime.today().date()

    global tw_side, subcommands
    if last_used < current_date:
        tw_side = TaskWarriorSideWLock()
        subcommands = create_subcommands()
        last_used_date.set(current_date)
    elif last_used > current_date:
        # maybe due to NTP?
        v0.critical(
            f"Current date {current_date} < last_used date {last_used} ?! Overriding current date, please report this if it persists"
        )
        tw_side = TaskWarriorSideWLock()
        subcommands = create_subcommands()
        last_used_date.set(current_date)

    if not query.isTriggered:
        if show_items_wo_trigger and len(query.string) < 2:
            results = [
                ActiveTasks().get_as_albert_item(),
                TodayTasks().get_as_albert_item(),
                *results,
            ]
    else:
        # join any previously launched threads
        for i in range(len(workers)):
            workers.pop(i).join(2)

        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup
            tasks = tw_side.get_all_items(include_completed=False)

            query_str = query.string

            if len(query_str) < 2:
                results.extend([s.get_as_albert_item() for s in subcommands])
                results.append(
                    get_as_item(
                        text="Reload list of tasks",
                        actions=[v0.FuncAction("Reload", async_reload_items)],
                    ))

                tasks.sort(key=lambda t: t["urgency"], reverse=True)
                results.extend([get_tw_item(task) for task in tasks])

            else:
                subcommand_query = get_subcommand_query(query_str)

                if subcommand_query:
                    results.extend(
                        subcommand_query.command.get_as_albert_items_full(
                            subcommand_query.query))

                    if not results:
                        results.append(get_as_item(text="No results"))

                else:
                    # find relevant results
                    desc_to_task = {
                        task["description"]: task
                        for task in tasks
                    }
                    matched = process.extract(query_str,
                                              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
            if dev_mode:
                v0.critical(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) -> list:
    """Hook that is called by albert with *every new keypress*."""  # noqa
    results = []

    if query.isTriggered:
        try:
            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=__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
예제 #29
0
def handleQuery(query) -> list:
    results = []

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            # External IP address -------------------------------------------------------------
            with request.urlopen("https://ipecho.net/plain") as response:
                external_ip = response.read().decode()

            results.append(
                get_as_item(
                    text=external_ip,
                    subtext="External IP Address",
                    actions=[
                        v0.ClipAction("Copy address", external_ip),
                    ],
                ))
            # IP address in all interfaces - by default IPv4 ----------------------------------
            ifaces = netifaces.interfaces()

            for iface in ifaces:  # Each interface
                addrs = netifaces.ifaddresses(iface)
                for family_to_addrs in addrs.items():
                    family = families[family_to_addrs[0]]

                    # discard all but IPv4?
                    if show_ipv4_only and family != "AF_INET":
                        continue

                    for i, addr_dict in enumerate(family_to_addrs[1]):
                        own_addr = addr_dict["addr"]
                        broadcast = addr_dict.get("broadcast")
                        netmask = addr_dict.get("netmask")
                        results.append(
                            get_as_item(
                                text=own_addr,
                                subtext=iface.ljust(15) +
                                f" | {family} | Broadcast: {broadcast} | Netmask: {netmask}",
                                actions=[
                                    v0.ClipAction("Copy address", own_addr),
                                    v0.ClipAction("Copy interface", iface),
                                ],
                            ))

            # Gateways ------------------------------------------------------------------------
            # Default gateway
            def_gws: Dict[int, tuple] = netifaces.gateways()["default"]

            for def_gw in def_gws.items():
                family_int = def_gw[0]
                addr = def_gw[1][0]
                iface = def_gw[1][1]
                results.append(
                    get_as_item(
                        text=f"[GW - {iface}] {addr}",
                        subtext=families[family_int],
                        actions=[
                            v0.ClipAction("Copy address", addr),
                            v0.ClipAction("Copy interface", iface),
                        ],
                    ))

        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) -> list:  # noqa
    results = []

    if len(query.rawString.strip()) <= 1 and is_radio_on():
        results.insert(
            0,
            v0.Item(
                id=__title__,
                icon=stop_icon_path,
                text="Stop Radio",
                actions=[v0.FuncAction("Stop Radio", lambda: stop_radio())],
            ),
        )

    reindex_item = v0.Item(
        id=__title__,
        icon=repeat_icon_path,
        text="Reindex stations",
        actions=[v0.FuncAction("Reindex", lambda: init_streams())],
    )

    if query.isTriggered:
        try:
            query.disableSort()

            results_setup = setup(query)
            if results_setup:
                return results_setup

            query_str = query.string.strip().lower()

            if not query_str:
                results.append(reindex_item)
                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 query_str.lower()
                            in stream.description.lower()):
                        results.append(get_as_item(stream))

                # reindex goes at the end of the list if we are searching for a stream
                results.append(reindex_item)

        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