Пример #1
0
def generate_launcher_item(item, params):
    script = item.get('script', 'Missing script...') or 'Missing script...'

    if len(params) > 0:
        script += ' ' + ' '.join(params)
    elif len(item.get('default_arguments', [])) > 0:
        script += ' ' + ' '.join(item['default_arguments'])

    description = item[
        'description'] + ' • ' + script if 'description' in item else script

    return ExtensionResultItem(
        icon=get_icon(item.get('icon')),
        name=item.get('name', script) or script,
        description=description,
        on_enter=RunScriptAction(script) if script else DoNothingAction())
Пример #2
0
    def on_event(self, event, extension):
        """ Handles the event """

        query = event.get_argument() or ""

        if not query:
            return extension.show_menu()

        # Get the action based on the search terms
        search = re.findall(r"^search(.*)?$", query, re.IGNORECASE)
        repos = re.findall(r"^projects(.*)?$", query, re.IGNORECASE)
        groups = re.findall(r"^groups(.*)?$", query, re.IGNORECASE)
        starred = re.findall(r"^starred(.*)?$", query, re.IGNORECASE)
        account = re.findall(r"^my(.*)?$", query, re.IGNORECASE)

        try:
            if account:
                return extension.show_my_menu(account[0])

            if search:
                return extension.search_projects(search[0],
                                                 PROJECTS_SEARCH_TYPE_PUBLIC)

            if repos:
                return extension.search_projects(repos[0],
                                                 PROJECTS_SEARCH_TYPE_MEMBER)

            if starred:
                return extension.search_projects(starred[0],
                                                 PROJECTS_SEARCH_TYPE_STARRED)

            if groups:
                return extension.list_groups(groups[0])

            return extension.search_projects(query,
                                             PROJECTS_SEARCH_TYPE_MEMBER)

        except gitlab.GitlabError as exc:
            LOGGER.error(exc)
            return RenderResultListAction([
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='An error ocurred when connecting to GitLab',
                    description=str(exc),
                    highlightable=False,
                    on_enter=HideWindowAction())
            ])
    def on_event(self, event, extension):
        data = event.get_data().replace("%20", " ")
        print('data again')
        print(data)
        if os.path.isdir(data):
            mime_path = icon_path('folder')
        else:
            content_type, val = Gio.content_type_guess('filename=' + data,
                                                       data=None)
            types = Gio.content_type_get_icon(content_type).to_string().split(
                ' ')[2:]
            mime_path = icon_path(*types)
        appchooser_path = appPath + '/appchooser.py'
        options = [['Open with default application', 'xdg-open', mime_path],
                   [
                       'Open with other application', appchooser_path,
                       other_application_icon
                   ],
                   [
                       'Open with file browser',
                       extension.preferences["filebrowser"], file_browser_icon
                   ],
                   [
                       'Open with text editor',
                       extension.preferences["texteditor"], text_editor_icon
                   ],
                   [
                       'Open location in {}'.format(
                           extension.preferences["terminal"]),
                       extension.preferences["terminal"], terminal_icon
                   ]]
        data = event.get_data().replace("%20", " ")
        items = []
        for i in options:
            if not i[1].endswith('='):
                i[1] = i[1] + ' '
            print("%s '%s'" % (i[1], data))
            if i[1] == extension.preferences["terminal"]:
                data = os.path.dirname(os.path.abspath(data))
            items.append(
                ExtensionResultItem(icon=i[2],
                                    name='%s' % i[0],
                                    description="%s" % data,
                                    on_enter=RunScriptAction(
                                        '{}"{}"'.format(i[1], data), None)))

        return RenderResultListAction(items)
Пример #4
0
 def items_copy_note_command(
         self, matches: List[SearchResultItem]) -> List[ResultItem]:
     """
     Search result items for the "copy to clipboard" command
     """
     items = []
     for match in matches[:MAX_RESULTS_VISIBLE]:
         item = ExtensionResultItem(
             icon="images/copy-note.svg",
             name=f"Copy: {match.filename}",
             description=match.match_summary,
             on_enter=callable_action(
                 self.copy_note,
                 os.path.join(self.get_notes_path(), match.filename)),
         )
         items.append(item)
     return items
Пример #5
0
 def on_event(self, event, extension):
     items = []
     argumentToEval = event.get_argument()
     argumentToEval = argumentToEval.replace('\'', '')
     argumentToEval = argumentToEval.replace('"', '')
     resultEval = eval(argumentToEval)
     resultParsed = ""
     if isinstance(resultEval, int):
         resultParsed = str(resultEval)
     elif isinstance(resultEval, float):
         resultParsed = "{:.8}".format(resultEval)
     items.append(
         ExtensionResultItem(icon='images/icon.png',
                             name=resultParsed,
                             description='Enter to copy to clipboard',
                             on_enter=CopyToClipboardAction(resultParsed)))
     return RenderResultListAction(items)
Пример #6
0
    def on_event(self, event, extension):
        items = list()

        if event.get_argument():
            LOGGER.info('Showing Startpage search for "{}"'.format(
                event.get_argument()))
            items.append(
                ExtensionResultItem(
                    icon='images/icon.svg',
                    name='Search on Startpage',
                    description='Search for "{}".'.format(
                        event.get_argument()),
                    on_enter=OpenUrlAction(
                        'https://www.startpage.com/do/dsearch?{}'.format(
                            urlencode({'query': event.get_argument()})))))

        return RenderResultListAction(items)
Пример #7
0
    def get_list(self):
        api_token = self.extension.preferences['todoist_api_token']
        api = todoist.TodoistAPI(api_token)
        api.sync()

        projects = []

        for project in api.projects.all(filt=self.filter_projects):
            logger.debug(project)
            projects.append(
                ExtensionResultItem(icon="images/projects.png",
                                    name=self.deEmojify(str(project["name"])),
                                    on_enter=OpenUrlAction(
                                        "https://todoist.com/app?#project/%s" %
                                        project["id"])))

        return projects
Пример #8
0
    def on_event(self, event, extension):
        """ Handles event """
        items = []

        if event.get_argument():
            pw_length = int(event.get_argument())
        else:
            pw_length = int(extension.preferences['pw_length'])

        pw_count = int(extension.preferences['pw_count'])

        if pwgen_module:
            passwords = pwgen.pwgen(
                pw_length,
                pw_count,
                False,
                False,
                True,
                True,
                False,
                True,
                '!$.#*+-_~()][?%&@,;',
                True
            )
        elif not pwgen_module and is_exist(program='pwgen'):
            command = 'pwgen -1 -c -n -y {} {}'.format(
                str(pw_length),
                str(pw_count)
            )
            output = check_output(command.split(' '))
            passwords = output.splitlines()
        else:
            passwords = ['Could not find neither pwgen module nor the command!']

        for password in passwords:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=str(password),
                    description='Press Enter to copy this password to clipboard',
                    highlightable=False,
                    on_enter=CopyToClipboardAction(str(password))
                )
            )

        return RenderResultListAction(items)
Пример #9
0
def show_suggestion_items(suggestions: List[Snippet], limit=8):

    if len(suggestions) == 0:
        return no_input_item()

    return [
        ExtensionResultItem(
            icon=suggestion.icon,
            name=suggestion.name,
            description=suggestion.description,
            on_enter=ExtensionCustomAction(
                {
                    "type": "select",
                    "snippet": suggestion
                }, keep_app_open=True),
        ) for suggestion in suggestions[:limit]
    ]
Пример #10
0
    def build_results_list(self, sites):
        """ Builds the result list from a list of sites """
        items = []

        for site in sites:
            name = site["name"]
            if site["custom_domain"] is not None:
                name = site["custom_domain"]

            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=name,
                                    on_enter=OpenUrlAction(site["url"]),
                                    on_alt_enter=OpenUrlAction(
                                        site['admin_url'])))

        return items
Пример #11
0
    def on_event(self, event, extension):
        query = event.get_argument() or str()

        if len(query.strip()) == 0:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name='Open Elixir docs',
                                    on_enter=OpenUrlAction('https://hexdocs.pm/elixir'))
            ])
        else:
            search_url = 'https://hex.pm/api/packages?search=%s&sort=recent_downloads'

            api_results = requests.get(search_url % query).json()

            result_items = list(map(self.build_result_item, api_results))

            return RenderResultListAction(result_items)
Пример #12
0
    def on_event(self, event, extension):
        items = list()

        if event.get_argument():
            LOGGER.info('Word Linguee search for "{}"'.format(event.get_argument()))
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Define words on Linguee',
                    description='Define words "{}".'.format(event.get_argument()),
                    on_enter=OpenUrlAction(
                        'https://www.linguee.com/english-french/search?{}'.format(urlencode({ 'source': 'auto', 'query': event.get_argument() }))
                    )
                )
            )

        return RenderResultListAction(items)
Пример #13
0
    def on_event(self, event, extension):
        """React to user input"""
        items = []

        AWESOME_PROVIDER.load()

        lists = AWESOME_PROVIDER.search(event.get_argument())

        for item in lists[:8]:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=item["name"].strip().replace(
                                        '\n', '-'),
                                    description=item.get("description", ""),
                                    on_enter=OpenUrlAction(item["url"])))

        return RenderResultListAction(items)
Пример #14
0
def notlinked(ws, linkObject):
    entries = []
    for action in sessionActions:
        entries.append(
            ExtensionResultItem(
                icon=action["icon"],
                name=linkObject['filename'] + " " + action["display_name"],
                description=ws,
                on_enter=ExtensionCustomAction(
                    {
                        "open_cmd": action["command"],
                        "opt": [ws, action],
                    },
                    keep_app_open=False,
                ),
            ))
    return entries
Пример #15
0
    def on_event(self, event, extension):
        keyword = event.get_keyword()
        search = str(event.get_argument() or '').lower().strip()

        items = []

        # Get list of all windows, and process into a dictionary that looks like this:
        # {<window_id>: {ws: <workspace_id>, name: <window_name>}}
        result = subprocess.run(
            ['wmctrl -l | awk \'{ if( $2 != "-1") { $3="";  print $0} }\''],
            capture_output=True,
            shell=True,
            text=True).stdout
        w_list = [y for y in (x.strip() for x in result.splitlines()) if y]
        w_dict = {
            x[1].split(maxsplit=2)[0]: {
                'ws': int(x[1].split(maxsplit=2)[1]),
                'name': x[1].split(maxsplit=2)[2]
            }
            for x in enumerate(w_list)
        }

        # Get list of all workspaces and process into a dictionary that looks like this:
        # {<workspace_id>: <workspace_name>}
        result = subprocess.run(
            ['wmctrl -d | awk \'{$1=$2=$3=$4=$5=$6=$7=$8=$9=""; print $0}\''],
            capture_output=True,
            shell=True,
            text=True).stdout
        ws_list = [y for y in (x.strip() for x in result.splitlines()) if y]
        ws_dict = {i: x for i, x in enumerate(ws_list)}

        for w_idx, window in w_dict.items():
            if search == '' or search in window['name'].lower():
                items.append(
                    ExtensionResultItem(
                        icon='images/window.svg',
                        # Workaround for https://github.com/Ulauncher/Ulauncher/issues/587
                        name=window['name'].replace('&', '&amp;')
                        if search else window['name'],
                        description=
                        f'Workspace: {window["ws"]}: {ws_dict[window["ws"]]}, Window Id: {w_idx}',
                        on_enter=RunScriptAction(f'wmctrl -ia {w_idx}')))

        return RenderResultListAction(items)
Пример #16
0
def render_episode(media_id, episode_designator, language):
    from languages import LANGUAGES
    from preferences import PREF_MAIN_LANGUAGE
    import re
    import api

    info = re.findall(r'\d+', episode_designator)
    season = str(int(info[0]))
    episode = info[1]
    
    language_valid = False
    if language:
        for name, code in list(LANGUAGES.items()):
            if code == language.lower() or name.lower() == language.lower():
                language = code
                language_valid = True
                break

    if not language_valid:
        language = PREF_MAIN_LANGUAGE

    try:
        episode_results = api.get_episode(media_id, season, episode, language)
    except:
        # TODO Render error message
        return

    items = []
    for result in episode_results:
        uploader = result.uploader or 'UNKOWN'
        uploader_badge = ''
        if result.uploader_badge:
            uploader_badge = '[%s]' % result.uploader_badge

        items.append( ExtensionResultItem(icon = 'images/languages/%s.svg' % LANGUAGES[result.language],
                                name = 'Uploaded by %s %s' % (uploader, uploader_badge),
                                description = '%s | (%s)' % (result.video_source_name, result.language),
                                highlightable = True,
                                on_enter = ExtensionCustomAction(data = {'download': {'url': result.url, 'download_id': result.download_id}}, keep_app_open=False)))

    # If it's empty
    if not items:
        items.append( not_found_item(episode_designator) )   

    return items[:5]
Пример #17
0
    def handle_online_exact_results(self, soup: BeautifulSoup,
                                    word: str) -> List[ExtensionResultItem]:
        """All elements to be displayed by the extension when an exact definition is found.

        Args:
            soup (BeautifulSoup): Whole page soup.
            word (str): Word to which the definitions belong.

        Returns:
            List[ExtensionResultItem]: All elements to be shown by the extension.
        """
        items = []
        max_shown_definitions = int(self.preferences["max_shown_definitions"])
        logger.info(f"max_shown_definitions={max_shown_definitions}")

        definitions = soup.find_all("p", {"class": "j"})

        for definition in definitions[:max_shown_definitions]:
            abbrs = " ".join(abbr.text for abbr in definition.find_all("abbr"))

            # This is done this weird way cause they put words inside <mark> tags but whitespaces and puntcuations outside of them.
            words = "".join(child if isinstance(child, NavigableString
                                                ) else child.get_text()
                            for child in definition.children
                            if child.name not in {"span", "abbr"})

            words = words.strip()
            chunks = chunkize_sentence(words, CHARACTERS_PER_LINE)
            definition_in_lines = "\n".join(chunks)

            code = definition["id"]

            items.append(
                ExtensionResultItem(
                    icon="images/icon.png",
                    name=f"{word} [{abbrs}]",
                    description=definition_in_lines,
                    on_enter=CopyToClipboardAction(
                        words
                    ),  # https://github.com/Ulauncher/Ulauncher/blob/dev/ulauncher/api/shared/action/CopyToClipboardAction.py
                    on_alt_enter=OpenUrlAction(
                        f"{BASE_URL}/{word}#{code}"
                    ),  # https://github.com/Ulauncher/Ulauncher/blob/dev/ulauncher/api/shared/action/OpenUrlAction.py
                ))
        return items
Пример #18
0
def get_open_windows():
    """Get open windows

    Returns:
        List[ExtensionResultItem] -- list of Ulauncher result items
    """
    windows=list_windows()
    # Filter out stickies (desktop is -1)
    non_stickies=filter(lambda x: x['desktop'] != '-1', windows)

    results = []
    for window in non_stickies:
        results.append(ExtensionResultItem(icon='images/icon.png',
                                           name=get_process_name(window['pid']),
                                           description=window['title'],
                                           on_enter=RunScriptAction(ACTIVATE_COMMAND.format(window['id']), None)
                       ))
    return results
Пример #19
0
    def on_event(self, event, extension):
        datetime_format = {
            'DD.MM.YYYY HH:MM': '%d.%m.%Y %H:%M',  # '17.05.2020 14:46'
            'DD-MM-YYYY HH:MM': '%d-%m-%Y %H:%M',  # '17-05-2020 14:46'
            'MM-DD-YYYY HH:MM': '%m-%d-%Y %H:%M',  # '05-17-2020 14:46'
            'MM/DD/YYYY HH:MM': '%m/%d/%Y %H:%M',  # '05/17/2020 14:46'
        }[extension.preferences['journal_datetime_format']]

        data = {
            'header': datetime.now().strftime(datetime_format),
            'content': event.get_argument() or ''
        }
        item = ExtensionResultItem(icon='images/icon.png',
                                   name=data['header'],
                                   description=data['content'],
                                   on_enter=ExtensionCustomAction(data))

        return RenderResultListAction([item])
Пример #20
0
    def on_event(self, event, extension):
        keyword = event.get_keyword()
        clientsString = "[]"
        for id, kw in extension.preferences.items():
            if kw == keyword:
                clientsString = self.get_client_string(id, extension)
        search = str(event.get_argument() or '').lower().strip()
        items = []
        clients = json.loads(clientsString)
        for clt in clients:
            if search == '' or search in clt["class"].lower() or search in clt["name"].lower():
                data = (clt["wid"])
                items.append(ExtensionResultItem(icon='images/icon.png',
                                                 name=clt["class"],
                                                 description=f'{clt["screen"]} - {clt["tags"][0]["name"]}: {clt["name"]}',
                                                 on_enter=ExtensionCustomAction(data)))

        return RenderResultListAction(items)
Пример #21
0
 def make_favourite(self, stop: Stop, departures: Iterable[Departure],
                    back: str) -> ExtensionResultItem:
     if len(list(departures)) == 0:
         return self.make_stop(stop)
     else:
         departure = list(departures)[0]
         desc = f"Next: {departure.route_id} {departure.destination} | {departure.time}"
         if not departure.is_real_time:
             desc += "*"
         if departure.time_late:
             desc += f" - {departure.time_late}"
         return ExtensionResultItem(
             icon="images/icon.png",
             name=f"#{stop.id} {stop.name}",
             description=desc,
             highlightable=False,
             on_enter=SetUserQueryAction(f"{self.kw} departures {stop.id}"),
             on_alt_enter=self.make_stop_menu(stop, back))
Пример #22
0
    def on_event(self, event, extension):
        items = []
        query = event.get_argument() or ""

        source = extension.preferences['source']
        to = extension.preferences['to']
        repairTo = extension.preferences['repairTo']

        results = inletMain(query, source, to, repairTo)
        for item in results:
            items.append(
                ExtensionResultItem(icon=item['icon'],
                                    name=item['title'],
                                    description=item['subtitle'],
                                    on_enter=CopyToClipboardAction(
                                        item['subtitle'])))

        return RenderResultListAction(items)
Пример #23
0
    def on_event(self, event, extension):
        items = []
        
        for i in range(7):
            x = extension.preferences["dov"+str(i)].split(";")
            if len(x) < 2:
                continue
            # Adres
            metin = doviz(x[1].strip())

            items.append(ExtensionResultItem(
                icon='images/icon.png',
                name="{:10}{:20}{}".format(x[0].strip(), metin[0], metin[1]),
                description=metin[2],
                on_enter=OpenUrlAction(x[1] and x[1].strip()))
            )

        return RenderResultListAction(items)
Пример #24
0
    def show_active_entry(self, entry):
        items = []
        details = self.keepassxc_db.get_entry_details(entry)
        attrs = [
            ("Password", "password"),
            ("UserName", "username"),
            ("URL", "URL"),
            ("Notes", "notes"),
        ]
        for attr, attr_nice in attrs:
            val = details.get(attr, "")
            if val:
                action = ActionList(
                    [
                        ExtensionCustomAction(
                            {
                                "action": "show_notification",
                                "summary": "{} copied to the clipboard.".format(
                                    attr_nice.capitalize()
                                ),
                            }
                        ),
                        CopyToClipboardAction(val),
                    ]
                )

                if attr == "Password":
                    items.append(
                        ExtensionSmallResultItem(
                            icon=COPY_ICON,
                            name="Copy password to the clipboard",
                            on_enter=action,
                        )
                    )
                else:
                    items.append(
                        ExtensionResultItem(
                            icon=COPY_ICON,
                            name="{}: {}".format(attr_nice.capitalize(), val),
                            description="Copy {} to the clipboard".format(attr_nice),
                            on_enter=action,
                        )
                    )
        return RenderResultListAction(items)
Пример #25
0
    def on_event(self, event, extension):  # pylint: disable=unused-argument
        """ Handles the event """

        items = []

        try:
            items = extension.get_zones(event)

        except CloudFlare.exceptions.CloudFlareError as e:
            LOGGER.error(e)
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name="CloudFlare API error",
                                    description="Error %s : %s" %
                                    (e.evalue.code, e.evalue.message),
                                    on_enter=HideWindowAction(),
                                    highlightable=False))

        return RenderResultListAction(items[:8])
Пример #26
0
    def download_data(self, data):
        """
        Function to manually update data in case more coins get added to Coingecko
        """
        coinlist = requests.get(
            "https://api.coingecko.com/api/v3/coins/list?include_platform=false"
        ).json()
        with open(data, "w") as a:
            json.dump(coinlist, a)

        items = [
            ExtensionResultItem(
                icon="images/icon.png",
                name="Data update complete!",
                description="You can now search your favorite coins!",
            )
        ]

        return RenderResultListAction(items)
Пример #27
0
    def on_event(self, event, extension):
        items = list()

        if event.get_argument():
            LOGGER.info('Showing DuckDuckGo search for "{}"'.format(
                event.get_argument()))
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name='Search on Duckduckgo',
                                    description='Search for "{}".'.format(
                                        event.get_argument()),
                                    on_enter=OpenUrlAction(
                                        'https://duckduckgo.com/?{}'.format(
                                            urlencode({
                                                'q': event.get_argument(),
                                                's': 'all'
                                            })))))

        return RenderResultListAction(items)
Пример #28
0
    def on_event(self, event, extension):
        """ Handles the event """
        query = event.get_argument() or ""

        if not extension.lp.is_cli_installed():
            return extension.show_lpass_not_installed_message()

        if not extension.lp.is_authenticated():
            return extension.show_not_authenticated_message()

        if len(query) < 3:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Keep typing for searching in your Vault ...',
                    on_enter=HideWindowAction())
            ])

        return extension.list_passwords(query)
Пример #29
0
    def on_event(self, event, extension):
        query = event.get_argument()
        logger.info("preferences %s" % json.dumps(extension.preferences))
        result = subprocess.run(["gnome-calculator", "-s", query],
                                stdout=subprocess.PIPE,
                                text=True).stdout
        items = [
            ExtensionResultItem(
                icon="images/icon.svg",
                name=result,
                description=
                "Enter to copy to the clipboard\nAlt-enter to open in calculator",
                on_enter=CopyToClipboardAction(result.rstrip("\n")),
                on_alt_enter=RunScriptAction("gnome-calculator -e '%s'" %
                                             query),
            )
        ]

        return RenderResultListAction(items)
Пример #30
0
    def on_event(self, event, extension):
        query = event.get_argument()
        if query:
            url = 'http://dict-co.iciba.com/api/dictionary.php?type=json&key=F1D7870B690CBC2442A527DCB771E852&w=' + query
            s = quote(url, safe=string.printable)
            response = request.urlopen(s)
            rsp_data = response.read()
            obj = json.loads(rsp_data)

            parts = []
            if "parts" in obj["symbols"][0].keys():
                parts = obj["symbols"][0]["parts"]
                print(parts)

            items = []
            for part in parts:
                means = ''
                desc = ''
                if isinstance(part["means"][0], str):
                    means = '; '.join(part["means"])
                    desc = part["part"] + ' ' + means
                else:
                    for word in part["means"]:
                        means = means + word["word_mean"] + '; '
                    desc = means

                # 替换'<'、'>'字符,否则字符串无法正常显示
                desc = desc.replace('<', '[')
                desc = desc.replace('>', ']')

                items.append(
                    ExtensionResultItem(icon='images/icon.png',
                                        name=desc,
                                        on_enter=CopyToClipboardAction(desc)))

            if items:
                return RenderResultListAction(items)
            else:
                return self.get_action_to_render(name="Type in your query",
                                                 description="Example: word ")
        else:
            return self.get_action_to_render(name="Type in your query",
                                             description="Example: word ")