Ejemplo n.º 1
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"]),
    ]

    return v0.Item(
        id=__prettyname__,
        icon=icon_path,
        text=googler_item["title"],
        subtext=googler_item["abstract"],
        actions=actions,
    )
Ejemplo n.º 2
0
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,
    )
Ejemplo n.º 3
0
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=__prettyname__,
        icon=icon_path,
        text=f"{text}",
        subtext=f"{subtext}",
        completion=f"{__trigger__}{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),
        ],
    )
Ejemplo n.º 4
0
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=__prettyname__,
                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
Ejemplo n.º 5
0
def setup(query):

    results = []

    if not which("task"):
        results.append(
            v0.Item(
                id=__prettyname__,
                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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
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=__prettyname__,
        icon=prio_to_icon[issue.fields.priority.name],
        text=f"{issue.fields.summary}",
        subtext=subtext,
        actions=actions,
    )
Ejemplo n.º 8
0
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

            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=__prettyname__,
                    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=__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
Ejemplo n.º 9
0
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 []
Ejemplo n.º 10
0
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,
    )
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def handleQuery(query):
    results = []
    if query.isTriggered:
        try:
            # be backwards compatible with v0.2
            if "disableSort" in dir(query):
                query.disableSort()

            fields = query.string.split()
            item = v0.Item(id=__prettyname__,
                           icon=icon_path,
                           completion=query.rawString)

            if len(fields) < 3:
                keys_monitor.reset()

                item.text = __prettyname__
                item.subtext = 'Enter a query in the form of "&lt;srclang&gt; &lt;dstlang&gt; &lt;text&gt;"'
                results.append(item)
                return results

            # determine if we can make the request --------------------------------------------
            keys_monitor.report()
            if keys_monitor.triggered():
                src = fields[0]
                dst = fields[1]
                txt = " ".join(fields[2:])
                url = urltmpl % (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.ClipAction("Copy translation to clipboard", 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}",
                        ))
                    results.append(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