def on_catalog(self):
        self.dbg('on_catalog')

        catalog = []
        for server_name, server in self.servers.items():
            self.set_default_icon(self._icons[ICON_KEY_DEFAULT])
            self.info(
                "Creating catalog entry for server name={name}, issues_label={issues_label}, filter_label={filter_label}, server_name={server_name}, issues_icon={issues_icon}, filter_icon={filter_icon},filter={filter}"
                .format(filter_icon=server.filter_icon,
                        issues_icon=server.issues_icon,
                        issues_label=server.issues_label,
                        filter_label=server.filter_label,
                        server_name=server_name,
                        name=server.name,
                        filter=server.filter_prefix))
            catalog.append(
                self.create_item(category=self.ITEMCAT_FILTER,
                                 label=server.filter_label,
                                 short_desc=server.name,
                                 target=kpu.kwargs_encode(server=server_name),
                                 args_hint=kp.ItemArgsHint.REQUIRED,
                                 hit_hint=kp.ItemHitHint.NOARGS,
                                 icon_handle=self._icons[server.filter_icon]))
            catalog.append(
                self.create_item(category=self.ITEMCAT_ISSUES,
                                 label=server.issues_label,
                                 short_desc=server.name,
                                 target=kpu.kwargs_encode(server=server_name),
                                 args_hint=kp.ItemArgsHint.REQUIRED,
                                 hit_hint=kp.ItemHitHint.NOARGS,
                                 icon_handle=self._icons[server.issues_icon]))
        self.set_catalog(catalog)
Beispiel #2
0
    def on_suggest(self, user_input, items_chain):
        if not items_chain or items_chain[0].category() != kp.ItemCategory.FILE:
            return

        suggestions = []

        data_bag = kpu.kwargs_decode(items_chain[0].data_bag())
        current_distro = self._distros[data_bag['distro_name']]
        current_distro_path = os.path.dirname(os.path.abspath(current_distro['exe_file']))
        sessions = current_distro['sessions']

        for session_name in sessions:
            displayed_session_name = session_name.replace(os.path.join(current_distro_path, 'Sessions') + os.sep, '')
            if not user_input or kpu.fuzzy_score(user_input, displayed_session_name) > 0:
                suggestions.append(self.create_item(
                    category=kp.ItemCategory.REFERENCE,
                    label="{}".format(displayed_session_name),
                    short_desc='Launch "{}" session'.format(displayed_session_name),
                    target=kpu.kwargs_encode(
                        dist=data_bag['distro_name'], session=session_name),
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE))

        if user_input:
            suggestions.append(self.create_item(
                category=kp.ItemCategory.REFERENCE,
                label="{}".format(user_input),
                short_desc='Launch "{}" directly'.format(user_input),
                target=kpu.kwargs_encode(
                    dist=data_bag['distro_name'], host_name=user_input),
                args_hint=kp.ItemArgsHint.FORBIDDEN,
                hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #3
0
    def suggest_copy(self, current_item, params):
        contact_no = int(params['contact_no'])
        contact = self.contacts[contact_no]
        verb = self.COPY_VERB

        if self._debug:
            self.dbg(
                f"Suggest copy action(s) for contact {contact['name']} - {repr(contact)} \nparams={repr(params)}"
            )

        suggestions = []

        target = current_item.target()
        suggestions.append(
            self.create_item(category=self.ITEMCAT_COPY,
                             label=f'Copy to clipboard - {target}',
                             short_desc="",
                             target=target,
                             args_hint=kp.ItemArgsHint.FORBIDDEN,
                             hit_hint=kp.ItemHitHint.IGNORE,
                             loop_on_suggest=False,
                             data_bag=kpu.kwargs_encode(
                                 verb_name=verb.name,
                                 contact_no=contact_no,
                                 action=self.ACTION_COPY)))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #4
0
    def on_suggest(self, user_input, items_chain):
        if not items_chain or items_chain[0].category(
        ) != kp.ItemCategory.KEYWORD:
            return

        suggestions = []

        data_bag = kpu.kwargs_decode(items_chain[0].data_bag())
        sessions = self._distros[data_bag['distro_name']]['sessions']
        for session in sessions:
            session_name = str(session).replace('\\', '/')
            if not user_input or kpu.fuzzy_score(user_input, session_name) > 0:
                suggestions.append(
                    self.create_item(
                        category=kp.ItemCategory.REFERENCE,
                        label=session_name,
                        short_desc='Open "{}" with HeidiSQL'.format(
                            session_name),
                        target=kpu.kwargs_encode(
                            distro_name=data_bag['distro_name'],
                            session=session),
                        args_hint=kp.ItemArgsHint.FORBIDDEN,
                        hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #5
0
 def _get_seasons_suggestion(self) -> TextSuggestion:
     """Returns the suggestion representing the seasons detail."""
     label = '{} {}'.format(self._number_of_seasons, 'season' if self._number_of_seasons == 1 else 'seasons')
     description = 'Number of seasons'
     url = '{}/tv/{}/seasons'.format(constants.URL_MOVIEDB_BASE, self._id)
     target = kpu.kwargs_encode(url=url)
     return TextSuggestion(label, description, target, 'Seasons')
Beispiel #6
0
    def on_catalog(self):
        self._read_config()

        catalog = []
        for distro_name, distro in self.distros.items():
            if not distro['enabled']:
                continue
            # catalog the executable
            catalog.append(self.create_item(
                category=kp.ItemCategory.FILE,
                label=distro['label'],
                short_desc="",
                target=distro['exe_file'],
                args_hint=kp.ItemArgsHint.ACCEPTED,
                hit_hint=kp.ItemHitHint.KEEPALL))
            # catalog the configured sessions, if any
            for session_name in distro['sessions']:
                catalog.append(self.create_item(
                    category=kp.ItemCategory.REFERENCE,
                    label="{}: {}".format(distro['label'], session_name),
                    short_desc='Launch {} "{}" session'.format(
                        distro['label'], session_name),
                    target=kpu.kwargs_encode(
                        dist=distro_name, session=session_name),
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.NOARGS))
        self.set_catalog(catalog)
Beispiel #7
0
 def target(self) -> str:
     #url = '{}/{}/{}'.format(constants.URL_MOVIEDB_BASE, self._media_type, self._id)
     url = constants.URL_VIDEOSPIDER.format(self._id)
     target = kpu.kwargs_encode(media_type=self._media_type,
                                id=self._id,
                                url=url)
     return target
    def add_filter_suggestions(self, actual_user_input, suggestions) -> None:
        api_result_suggestions = self.api.get_intellisense_suggestions(
            actual_user_input)
        # the first displays the current filter so far
        first = True
        for api_result_suggestion in api_result_suggestions:
            start = api_result_suggestion.start
            end = api_result_suggestion.end

            user_input_start_ = actual_user_input[:start]
            user_input_end_ = actual_user_input[end:]
            effective_value = user_input_start_ + api_result_suggestion.full_option + user_input_end_

            data_bag_encoded = kpu.kwargs_encode(
                url=self.api.create_issues_url(effective_value),
                effective_value=effective_value)
            desc = api_result_suggestion.description + " | " + effective_value if first else api_result_suggestion.description
            first = False
            suggestions.append(
                self.plugin.create_item(
                    category=self.plugin.ITEMCAT_FILTER,
                    label=api_result_suggestion.full_option,
                    short_desc=desc,
                    target=kpu.kwargs_encode(
                        server=self.name, label=api_result_suggestion.option),
                    args_hint=kp.ItemArgsHint.ACCEPTED,
                    hit_hint=kp.ItemHitHint.NOARGS,
                    icon_handle=self.plugin._icons[self.filter_icon],
                    loop_on_suggest=True,
                    data_bag=data_bag_encoded))
        suggestions.insert(
            0,
            self.plugin.create_item(
                category=self.plugin.ITEMCAT_FILTER,
                label=self.filter_label + "▶" + actual_user_input,
                short_desc="Open",
                target=actual_user_input,
                args_hint=kp.ItemArgsHint.FORBIDDEN,
                hit_hint=kp.ItemHitHint.KEEPALL,
                icon_handle=self.plugin._icons[self.filter_icon],
                loop_on_suggest=False,
                data_bag=(kpu.kwargs_encode(
                    url=self.api.create_issues_url(actual_user_input),
                    effective_value=actual_user_input))))
Beispiel #9
0
 def _get_year_suggestion(self):
     """Returns the suggestion representing the release year detail."""
     from .searchsuggestion import SearchSuggestion
     url = '{}/discover/{}?primary_release_year={}'.format(
         constants.URL_MOVIEDB_BASE, self._media_type, self._year)
     target = kpu.kwargs_encode(url=url,
                                media_type=self._media_type,
                                search_args=json.dumps(
                                    {'primary_release_year': self._year}))
     return SearchSuggestion(self._year, 'Year', target, 'Calendar')
Beispiel #10
0
    def on_suggest(self, user_input, items_chain):
        if not user_input:
            return
        if not items_chain:
            return

        initial_item = items_chain[0]

        if self.should_terminate(0.25):
            return
        if initial_item.category() != kp.ItemCategory.KEYWORD:
            return

        suggestions = []
        origin_word = user_input.strip()
        word = urllib.parse.quote_plus(origin_word)
        try:
            # get translated version of terms
            opener = kpnet.build_urllib_opener()
            opener.addheaders = [("User-agent", self.API_USER_AGENT)]
            rnum = str(random.randint(0, 10000))
            sign = self.get_md5(self._key + origin_word + rnum + self._keyfrom)
            url = self.URL_YOUDAO.format(word, rnum, sign)
            print(url)
            with opener.open(url) as conn:
                response = conn.read()
            if self.should_terminate():
                return
            results = self._parse_api_response(response)
        except urllib.error.HTTPError as exc:
            suggestions.append(
                self.create_error_item(label=user_input, short_desc=str(exc)))
            return
        except Exception as exc:
            suggestions.append(
                self.create_error_item(label=user_input,
                                       short_desc="Error: " + str(exc)))
            traceback.print_exc()
            return
        idx = 0
        for res in results:
            suggestions.append(
                self.create_item(category=self.ITEMCAT_RESULT,
                                 label=str(res['translation']),
                                 short_desc=str(res['description']),
                                 target=str(idx) + str(res['translation']),
                                 args_hint=kp.ItemArgsHint.REQUIRED,
                                 hit_hint=kp.ItemHitHint.IGNORE,
                                 icon_handle=self._icon,
                                 data_bag=kpu.kwargs_encode(
                                     word=word,
                                     translation=res['translation'])))
            idx += 1
        if suggestions:
            self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #11
0
    def suggest_contacts(self, current_item, params, user_input):
        verb = self.VERBS[current_item.target()]
        if self._debug:
            self.dbg(
                f"Suggest contacts matching '{user_input}' for {verb.name}")

        # Creating list of "{verb} {name} - {associated-item}"
        suggestions = []
        for idx, contact in enumerate(self.contacts):
            if len(suggestions) > 10:
                break

            if (not (self.ID_NAME in contact) or not contact[self.ID_NAME]):
                continue

            if not user_input.lower() in contact[self.ID_NAME].lower():
                continue

            item_target = None
            if (verb.contact_field.startswith("TEL;")
                    and verb.contact_field in contact):
                item_target = contact[verb.contact_field]
                item_label = f'Call {contact[self.ID_NAME]} ({verb.name}) - {item_target}'
            elif (verb.contact_field == self.AD_ATTR_PHONE):
                for v in self.VERB_LIST:
                    if v.contact_field.startswith(
                            "TEL;") and v.contact_field in contact:
                        item_target = contact[v.contact_field]
                        item_label = f'Call {contact[self.ID_NAME]} ({verb.name}) - {item_target}'
                        break
                if not item_target:
                    continue
            elif verb.contact_field in contact:
                item_target = contact[verb.contact_field]
                item_label = f'{verb.name} {contact[self.ID_NAME]} - {item_target}'
            else:
                continue

            title = contact[
                self.AD_ATTR_TITLE] if self.AD_ATTR_TITLE in contact else ""
            suggestions.append(
                self.create_item(category=self.ITEMCAT_CONTACT,
                                 label=item_label,
                                 short_desc=title,
                                 target=item_target,
                                 args_hint=kp.ItemArgsHint.ACCEPTED,
                                 hit_hint=kp.ItemHitHint.IGNORE,
                                 loop_on_suggest=True,
                                 data_bag=kpu.kwargs_encode(
                                     verb_name=verb.name,
                                     contact_no=idx,
                                     action=verb.action)))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
    def on_suggest(self, user_input, items_chain):
        if not items_chain or items_chain[0].category(
        ) != kp.ItemCategory.FILE:
            return

        suggestions = []

        data_bag = kpu.kwargs_decode(items_chain[0].data_bag())
        current_distro = self._distros[data_bag['distro_name']]
        current_distro_path = os.path.dirname(
            os.path.abspath(current_distro['exe_file']))
        sessions = current_distro['sessions']

        for session_name in sessions:
            displayed_session_name = session_name.replace(
                os.path.join(current_distro_path, 'Sessions') + os.sep, '')
            if not user_input or kpu.fuzzy_score(user_input,
                                                 displayed_session_name) > 0:
                suggestions.append(
                    self.create_item(category=kp.ItemCategory.REFERENCE,
                                     label="{}".format(displayed_session_name),
                                     short_desc='Launch "{}" session'.format(
                                         displayed_session_name),
                                     target=kpu.kwargs_encode(
                                         dist=data_bag['distro_name'],
                                         session=session_name),
                                     args_hint=kp.ItemArgsHint.FORBIDDEN,
                                     hit_hint=kp.ItemHitHint.IGNORE))

        if user_input:
            suggestions.append(
                self.create_item(
                    category=kp.ItemCategory.REFERENCE,
                    label="{}".format(user_input),
                    short_desc='Launch "{}" directly'.format(user_input),
                    target=kpu.kwargs_encode(dist=data_bag['distro_name'],
                                             host_name=user_input),
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
    def _load_search_presets(self) -> dict:
        """
        Parse the search presets defined in the settings.
        Each search preset can be customized by the user.
        """
        supported_media_types = ['movie', 'tv']
        settings = self.settings

        search_presets = {}
        for section in settings.sections():
            if section.lower().startswith(self.CONFIG_SECTION_SEARCH_PRESET +
                                          '/'):
                enabled = settings.get_bool('enabled',
                                            section=section,
                                            fallback=True)
                if enabled is False:
                    continue

                section_label = section[len(self.CONFIG_SECTION_SEARCH_PRESET
                                            ) + 1:].strip()
                label = settings.get_stripped('label', section=section)
                description = settings.get_stripped('description',
                                                    section=section)
                media_type = settings.get_enum('media_type',
                                               section=section,
                                               enum=supported_media_types)

                search_args = {}
                search_args_config = settings.get_multiline(
                    'search_args', section)
                if search_args_config:
                    for arg in search_args_config:
                        if ' ' not in arg:
                            raise ValueError(
                                'malformed {} search_args value from config section [{}]'
                                .format(section))
                        name, value = arg.split(' ', maxsplit=1)
                        search_args[name.strip()] = value.strip()

                try:
                    target = kpu.kwargs_encode(
                        media_type=media_type,
                        search_args=json.dumps(search_args))
                except Exception as exc:
                    continue

                if media_type not in search_presets:
                    search_presets[media_type] = {}

                search_presets[media_type][section_label] = SearchSuggestion(
                    label, description, target)

        return search_presets
Beispiel #14
0
 def on_catalog(self):
     catalog = []
     for profile_name, profile in self.profiles.items():
         catalog.append(self.create_item(
             category=self.ITEMCAT_PROFILE,
             label=profile['label'],
             short_desc="Suggest via {} (default action: {})".format(
                       profile['provider'].label, profile['default_action']),
             target=kpu.kwargs_encode(profile=profile_name),
             args_hint=kp.ItemArgsHint.REQUIRED,
             hit_hint=kp.ItemHitHint.NOARGS,
             icon_handle=self._find_icon(profile['provider'].browse_base)))
     self.set_catalog(catalog)
Beispiel #15
0
 def on_catalog(self):
     self._setup_default_icon()
     self._read_config()
     catalog = []
     for site_name, site in self.sites.items():
         catalog.append(
             self.create_item(category=kp.ItemCategory.REFERENCE,
                              label=site['item_label'],
                              short_desc="Search {}".format(site['label']),
                              target=kpu.kwargs_encode(site=site_name),
                              args_hint=kp.ItemArgsHint.ACCEPTED,
                              hit_hint=site['history_keep']))
     self.set_catalog(catalog)
    def _get_ratings_suggestions(self) -> list:
        """
        Get the suggestion containing all the media's ratings.
        Currently the only place where this data come from is through OMDB api.
        """
        rv = []
        if self._ratings:
            for rating in self._ratings:
                rating_type = self.RATINGS_TYPE[rating['source']]
                info = getattr(self, rating_type['info'])
                search_url = rating_type['url'].format(info)
                target = kpu.kwargs_encode(url=search_url)
                rv.append(TextSuggestion(rating['value'], rating['source'], target, rating['source']))

        return rv
    def on_suggest(self, user_input: str, items_chain: Sequence):
        self.dbg('on_suggest')

        if not items_chain:
            return []

        initial_item = items_chain[0]
        current_items = items_chain[1:len(items_chain)]
        current_suggestion_type: SuggestionMode = self.get_current_suggestionmode(
            items_chain)
        suggestions = []
        actual_user_input = self.filter_prefix if len(items_chain) == 1 else ""
        previous_effective_value = ""
        if (len(current_items) > 0):
            current_item = current_items[-1]
            previous_effective_value = kpu.kwargs_decode(
                current_item.data_bag())['effective_value']
            actual_user_input += previous_effective_value
        actual_user_input += user_input
        self.print(actual_user_input=actual_user_input, user_input=user_input)
        self.print(is_filter=str(current_suggestion_type))
        if current_suggestion_type == SuggestionMode.Filter:
            self.add_filter_suggestions(actual_user_input, suggestions)
        else:
            self.add_issues_matching_filter(actual_user_input, suggestions)

        suggestions.append(
            self.plugin.create_item(
                category=self.plugin.ITEMCAT_SWITCH,
                label="Switch ⇆",
                short_desc="Switch between filter suggestions and issue list",
                target="switch",
                args_hint=kp.ItemArgsHint.ACCEPTED,
                hit_hint=kp.ItemHitHint.IGNORE,
                icon_handle=self.plugin._icons[self.filter_icon],
                loop_on_suggest=True,
                data_bag=kpu.kwargs_encode(
                    url=self.api.create_issues_url(previous_effective_value),
                    effective_value=previous_effective_value)))

        # avoid flooding YouTrack with too many unnecessary queries in
        # case user is still typing her search
        if self.plugin.should_terminate(self.plugin.idle_time):
            return []
        if initial_item.category() == self.plugin.ITEMCAT_SWITCH:
            return []
        return suggestions
 def get_issues_matching_filter(self, actual_user_input):
     issues = self.api.get_issues_matching_filter(actual_user_input)
     suggestions = []
     for issue in issues:
         suggestions.append(
             self.plugin.create_item(
                 category=self.plugin.ITEMCAT_ISSUES,
                 label=issue.summary + " [" + issue.id + "]",
                 short_desc=issue.id +
                 (" ▶ " + issue.description
                  if issue.description is not None else ""),
                 target=issue.id,
                 args_hint=kp.ItemArgsHint.FORBIDDEN,
                 hit_hint=kp.ItemHitHint.NOARGS,
                 icon_handle=self.plugin._icons[self.issues_icon],
                 loop_on_suggest=False,
                 data_bag=(kpu.kwargs_encode(url=issue.url))))
     return suggestions
    def on_catalog(self):
        self._read_config()

        catalog = []
        for distro_name, distro in self._distros.items():
            if not distro['enabled']:
                continue
            # catalog the executable
            catalog.append(
                self.create_item(
                    category=kp.ItemCategory.FILE,
                    label=distro['label'],
                    short_desc="",
                    target=distro['exe_file'],
                    args_hint=kp.ItemArgsHint.ACCEPTED,
                    hit_hint=kp.ItemHitHint.KEEPALL,
                    data_bag=kpu.kwargs_encode(distro_name=distro_name)))
        self.set_catalog(catalog)
    def on_catalog(self):
        self._read_config()

        catalog = []
        for distro_name, distro in self._distros.items():
            if not distro['enabled']:
                continue
            # catalog the executable
            catalog.append(self.create_item(
                category=kp.ItemCategory.FILE,
                label=distro['label'],
                short_desc="",
                target=distro['exe_file'],
                args_hint=kp.ItemArgsHint.ACCEPTED,
                hit_hint=kp.ItemHitHint.KEEPALL,
                data_bag= kpu.kwargs_encode(
                    distro_name=distro_name
                ))
            )
        self.set_catalog(catalog)
 def add_issues_matching_filter(self, actual_user_input: str,
                                suggestions: Sequence) -> None:
     self.dbg("add_issues_matching_filter for " + actual_user_input)
     api_result_suggestions = self.get_issues_matching_filter(
         actual_user_input)
     for res in api_result_suggestions:
         suggestions.append(res)
     suggestions.insert(
         0,
         self.plugin.create_item(
             category=self.plugin.ITEMCAT_ISSUES,
             label=actual_user_input,
             short_desc=actual_user_input,
             target=actual_user_input,
             args_hint=kp.ItemArgsHint.ACCEPTED,
             hit_hint=kp.ItemHitHint.IGNORE,
             icon_handle=self.plugin._icons[self.issues_icon],
             loop_on_suggest=True,
             data_bag=(kpu.kwargs_encode(
                 url=self.api.create_issues_url(actual_user_input),
                 effective_value=actual_user_input))))
    def on_catalog(self):
        self._read_config()
        catalog = []

        for distro_name, distro in self._distros.items():
            if not distro['enabled']:
                continue
            self.dbg('Creating catalogItem for action: ', distro['label'], distro['exe_file'])
            catalog.append(self.create_item(
                category=kp.ItemCategory.KEYWORD,
                label=distro['label'],
                short_desc='Open HeidiSQL or open sessions via auto-complete',
                target=distro['exe_file'],
                args_hint=kp.ItemArgsHint.ACCEPTED,
                hit_hint=kp.ItemHitHint.NOARGS,
                data_bag=kpu.kwargs_encode(
                    distro_name=distro_name
                )
            ))

        self.set_catalog(catalog)
    def on_suggest(self, user_input, items_chain):
        if not items_chain or items_chain[0].category() != kp.ItemCategory.FILE:
            return

        suggestions = []

        data_bag = kpu.kwargs_decode(items_chain[0].data_bag())
        sessions = self._distros[data_bag['distro_name']]['sessions']

        for session_name in sessions:
            if not user_input or kpu.fuzzy_score(user_input, session_name) > 0:
                suggestions.append(self.create_item(
                    category=kp.ItemCategory.REFERENCE,
                    label="{}".format(session_name),
                    short_desc='Launch "{}" session'.format(session_name),
                    target=kpu.kwargs_encode(
                        dist=data_bag['distro_name'], session=session_name),
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #24
0
    def on_catalog(self):
        self._read_config()
        catalog = []

        for distro_name, distro in self._distros.items():
            if not distro['enabled']:
                continue
            self.dbg('Creating catalogItem for action: ', distro['label'],
                     distro['exe_file'])
            catalog.append(
                self.create_item(
                    category=kp.ItemCategory.KEYWORD,
                    label=distro['label'],
                    short_desc=
                    'Open HeidiSQL or open sessions via auto-complete',
                    target=distro['exe_file'],
                    args_hint=kp.ItemArgsHint.ACCEPTED,
                    hit_hint=kp.ItemHitHint.NOARGS,
                    data_bag=kpu.kwargs_encode(distro_name=distro_name)))

        self.set_catalog(catalog)
    def on_suggest(self, user_input, items_chain):
        if len(user_input) == 0:
            return
        if not items_chain:
            return

        initial_item = items_chain[0]

        # avoid flooding Leo with too much unnecessary queries in
        # case user is still typing her search
        if self.should_terminate(0.250):
            return
        if initial_item.category() != kp.ItemCategory.KEYWORD:
            return

        suggestions = []

        current_language = self._languages[initial_item.target()]

        for leo_translation in self._parser.translate(current_language.language_code, user_input):
            item_icon = self._icons[leo_translation.language]

            suggestions.append(self.create_item(
                category=kp.ItemCategory.EXPRESSION,
                label=leo_translation.caption,
                short_desc=leo_translation.description,
                target=leo_translation.caption,
                args_hint=kp.ItemArgsHint.FORBIDDEN,
                hit_hint=kp.ItemHitHint.IGNORE,
                icon_handle=item_icon,
                data_bag=kpu.kwargs_encode(
                    language_code=current_language.language_code,
                    item_language=leo_translation.language,
                    user_query=user_input,
                    translation_result=leo_translation.caption
                )
            ))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #26
0
    def details_suggestions(self) -> list:
        """Returns all the suggestions used in this media details."""
        from .peoplesuggestion import PeopleSuggestion
        from .textsuggestion import TextSuggestion

        suggestions = [
            TextSuggestion(self.label, self._genres_text, self._id, self.icon),
            self._get_year_suggestion(),
            TextSuggestion(self._runtime, 'Runtime', 'movieruntime', 'Clock')
        ]

        if self._director:
            director = PeopleSuggestion(self._director)
            director.description = 'Director'
            director.icon = 'Director'
            suggestions.append(director)

        if self._tagline:
            suggestions.append(
                TextSuggestion(self._tagline, 'Tagline', 'movietagline',
                               'Tagline'))

        if self._omdb:
            suggestions.extend(self._get_ratings_suggestions())

        if self._trailer:
            suggestions.append(
                TextSuggestion(
                    'Trailer',
                    "Watch trailer on {}".format(self._trailer['site']),
                    kpu.kwargs_encode(url=constants.URL_YOUTUBE_WATCH.format(
                        self._trailer['key'])), 'Trailer'))

        if self._main_cast:
            suggestions.extend(self._get_main_cast_suggestion())

        return suggestions
    def on_suggest(self, user_input, items_chain):
        if not items_chain or items_chain[0].category() != kp.ItemCategory.KEYWORD:
            return

        suggestions = []

        data_bag = kpu.kwargs_decode(items_chain[0].data_bag())
        sessions = self._distros[data_bag['distro_name']]['sessions']
        for session in sessions:
            session_name = str(session).rpartition('\\')[2]
            if not user_input or kpu.fuzzy_score(user_input, session_name) > 0:
                suggestions.append(self.create_item(
                    category=kp.ItemCategory.REFERENCE,
                    label=session_name,
                    short_desc='Open "{}" with HeidiSQL'.format(session_name),
                    target=kpu.kwargs_encode(
                        distro_name=data_bag['distro_name'],
                        session=session
                    ),
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE
                ))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)
Beispiel #28
0
    def suggest_actions(self, current_item, params):
        contact_no = int(params['contact_no'])
        contact = self.contacts[contact_no]

        if self._debug:
            self.dbg(
                f"Suggest actions for contact {contact['name']} - {repr(contact)}"
            )

        suggestions = []
        # suggestions.insert(0, item)
        for key in contact.keys():
            if not key.startswith(
                    "TEL;") or not key in self.VERB_CONTACT_FIELDS:
                continue

            verb = self.VERB_CONTACT_FIELDS[key]
            if not verb.contact_field in contact:
                continue

            target = contact[verb.contact_field]
            title = contact[
                self.AD_ATTR_TITLE] if self.AD_ATTR_TITLE in contact else ""
            suggestions.append(
                self.create_item(
                    category=self.ITEMCAT_ACTION,
                    label=
                    f'Call {contact[self.ID_NAME]} - {target} ({verb.name})',
                    short_desc=title,
                    target=contact[verb.contact_field],
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE,
                    loop_on_suggest=True,
                    data_bag=kpu.kwargs_encode(verb_name=verb.name,
                                               contact_no=contact_no,
                                               action=verb.action)))

        if self.AD_ATTR_MAIL in contact:
            verb = self.VERB_CONTACT_FIELDS[self.AD_ATTR_MAIL]
            target = contact[verb.contact_field]
            title = contact[
                self.AD_ATTR_TITLE] if self.AD_ATTR_TITLE in contact else ""
            suggestions.append(
                self.create_item(
                    category=self.ITEMCAT_ACTION,
                    label=f'{verb.name} {contact[self.ID_NAME]} - {target}',
                    short_desc=title,
                    target=target,
                    args_hint=kp.ItemArgsHint.FORBIDDEN,
                    hit_hint=kp.ItemHitHint.IGNORE,
                    loop_on_suggest=True,
                    data_bag=kpu.kwargs_encode(verb_name=verb.name,
                                               contact_no=contact_no,
                                               action=verb.action)))

        verb = self.VERB_CONTACT_FIELDS[self.AD_ATTR_NAME]
        target = contact[verb.contact_field]
        title = contact[
            self.AD_ATTR_TITLE] if self.AD_ATTR_TITLE in contact else ""
        suggestions.append(
            self.create_item(
                category=self.ITEMCAT_ACTION,
                label=f'{verb.name} {contact[self.ID_NAME]} - {target}',
                short_desc=title,
                target=target,
                args_hint=kp.ItemArgsHint.FORBIDDEN,
                hit_hint=kp.ItemHitHint.IGNORE,
                loop_on_suggest=True,
                data_bag=kpu.kwargs_encode(verb_name=verb.name,
                                           contact_no=contact_no,
                                           action=verb.action)))

        suggestions.append(
            self.create_item(
                category=self.ITEMCAT_ACTION,
                label=f'{verb.name} {contact[self.ID_NAME]} - {target}',
                short_desc=title,
                target=target,
                args_hint=kp.ItemArgsHint.FORBIDDEN,
                hit_hint=kp.ItemHitHint.IGNORE,
                loop_on_suggest=False,
                data_bag=kpu.kwargs_encode(verb_name=verb.name,
                                           contact_no=contact_no,
                                           action=verb.action)))

        self.set_suggestions(suggestions, kp.Match.ANY, kp.Sort.NONE)