예제 #1
0
 def show_plugin_info(self, source: CommandSource, plugin_id: str):
     plugin = self.mcdr_server.plugin_manager.get_plugin_from_id(plugin_id)
     if plugin is None:
         source.reply(self.tr('mcdr_command.invalid_plugin_id', plugin_id))
     else:
         meta = plugin.get_metadata()
         source.reply(
             RTextList(
                 RText(meta.name).set_color(RColor.yellow).set_styles(
                     RStyle.bold).h(plugin), ' ',
                 RText('v{}'.format(meta.version), color=RColor.gray)))
         source.reply('ID: {}'.format(meta.id))
         if meta.author is not None:
             source.reply('Authors: {}'.format(', '.join(meta.author)))
         if meta.link is not None:
             source.reply(
                 RTextList(
                     'Link: ',
                     RText(meta.link,
                           color=RColor.blue,
                           styles=RStyle.underlined).c(
                               RAction.open_url, meta.link)))
         if meta.description is not None:
             source.reply(
                 meta.get_description(
                     self.__mcdr_server.translation_manager.language))
예제 #2
0
 def to_rtext(self) -> RTextBase:
     return RTextBase.format(
         '{}: {}{}{}',
         RTextBase.from_any(self.__message).copy().set_color(RColor.red),
         RText(self._parsed_command, RColor.dark_red),
         RText(self._error_command, RColor.red),
         RText('<--', RColor.dark_red))
예제 #3
0
    def test_1_translation_formatting(self):
        self.translation_manager.language = 'test_lang'
        self.translation_manager.translations['key1'] = {
            'test_lang': 'A {0} bb {c} {1}zzz'
        }
        tr = functools.partial(self.translation_manager.translate,
                               allow_failure=False)

        self.assertEqual('A X bb Z Yzzz', tr('key1', ('X', 'Y'), {'c': 'Z'}))
        self.assertEqual('A X bb Z Yzzz',
                         tr('key1', ('X', 'Y', 'dummy'), {'c': 'Z'}))
        self.assertEqual('A X bb Z Yzzz',
                         tr('key1', ('X', 'Y'), {
                             'c': 'Z',
                             'dummy': 'dummy'
                         }))

        rtext = tr('key1', ('X', RText('Y')), {'c': 'Z'})
        self.assertIsInstance(rtext, RTextBase)
        self.assertEqual('A X bb Z Yzzz', rtext.to_plain_text())
        self.assertEqual(4, len(rtext.to_json_object()))

        rtext = tr('key1', ('X', RText('Y')), {'c': RText('Z')})
        self.assertIsInstance(rtext, RTextBase)
        self.assertEqual('A X bb Z Yzzz', rtext.to_plain_text())
예제 #4
0
 def get_file_name(fp) -> Tuple[str, RText]:
     name = os.path.basename(fp)
     name_text = RText(name)
     if source.has_permission(
             PermissionLevel.PHYSICAL_SERVER_CONTROL_LEVEL):
         name_text.h(fp)
     return name, name_text
 def get_suggestion_text(value: str):
     text = RText(value, VALUE_COLOR).c(
         RAction.suggest_command,
         '{} preference {} set {}'.format(self.control_command_prefix,
                                          pref_name, value))
     hover_text = RTextList(
         self.tr('mcdr_command.preference.item.set_suggestion_hint',
                 RText(pref_name, PREF_COLOR),
                 RText(value, VALUE_COLOR)))
     styles: List[RStyle] = []
     extra_descriptions: List[RTextBase] = []
     if value == current_value:
         styles.append(RStyle.underlined)
         extra_descriptions.append(
             self.tr('mcdr_command.preference.item.current').set_color(
                 RColor.gray))
     if value == default_value:
         styles.append(RStyle.bold)
         extra_descriptions.append(
             self.tr('mcdr_command.preference.item.default').set_color(
                 RColor.gray))
     if len(extra_descriptions) > 0:
         hover_text.append(
             RTextList(
                 '\n',
                 RText.join(RText(', ', RColor.dark_gray),
                            extra_descriptions)))
     text.set_styles(styles)
     return text.h(hover_text)
 def show_preference_list(self, source: CommandSource):
     pref = self.pref_mgr.get_preference(source, auto_add=True)
     source.reply(self.tr('mcdr_command.preference.list.title'))
     for pref_name in pref.get_annotations_fields().keys():
         value = getattr(pref, pref_name, RText('N/A', RColor.gray))
         source.reply(
             self.__detail_hint(
                 RTextList(RText('- ', RColor.gray),
                           RText(pref_name, PREF_COLOR),
                           RText(': ', RColor.gray),
                           RText(value, VALUE_COLOR)), pref_name))
    def show_preference_item(self, source: CommandSource, pref_name: str):
        entry: PrefCommandEntry = self.preferences.get(pref_name)
        pref: PreferenceItem = self.pref_mgr.get_preference(source,
                                                            auto_add=True)
        current_value = getattr(pref, pref_name, None)
        default_value = getattr(self.pref_mgr.get_default_preference(),
                                pref_name, None)
        if entry is None or current_value is None:  # should never come here
            raise KeyError('Unknown preference {}'.format(pref_name))

        def get_suggestion_text(value: str):
            text = RText(value, VALUE_COLOR).c(
                RAction.suggest_command,
                '{} preference {} set {}'.format(self.control_command_prefix,
                                                 pref_name, value))
            hover_text = RTextList(
                self.tr('mcdr_command.preference.item.set_suggestion_hint',
                        RText(pref_name, PREF_COLOR),
                        RText(value, VALUE_COLOR)))
            styles: List[RStyle] = []
            extra_descriptions: List[RTextBase] = []
            if value == current_value:
                styles.append(RStyle.underlined)
                extra_descriptions.append(
                    self.tr('mcdr_command.preference.item.current').set_color(
                        RColor.gray))
            if value == default_value:
                styles.append(RStyle.bold)
                extra_descriptions.append(
                    self.tr('mcdr_command.preference.item.default').set_color(
                        RColor.gray))
            if len(extra_descriptions) > 0:
                hover_text.append(
                    RTextList(
                        '\n',
                        RText.join(RText(', ', RColor.dark_gray),
                                   extra_descriptions)))
            text.set_styles(styles)
            return text.h(hover_text)

        source.reply(
            self.tr(
                'mcdr_command.preference.item.name',
                self.__detail_hint(RText(pref_name, PREF_COLOR), pref_name)))
        source.reply(
            self.tr('mcdr_command.preference.item.value',
                    RText(current_value, VALUE_COLOR)))
        source.reply(
            self.tr(
                'mcdr_command.preference.item.suggestions',
                RText.join(', ', map(get_suggestion_text, entry.suggester()))))
 def set_language(self, source: CommandSource, new_lang: Optional[str]):
     if new_lang is None:  # reset
         new_lang = self.pref_mgr.get_default_preference().language
     if new_lang not in self.available_languages:
         source.reply(
             self.tr('mcdr_command.preference.unknown_language', new_lang))
         return
     pref = self.pref_mgr.get_preference(source, auto_add=True)
     pref.language = new_lang
     self.pref_mgr.save_preferences()
     source.reply(
         self.tr('mcdr_command.preference.set.done',
                 RText('language', RColor.yellow),
                 RText(new_lang, RColor.gold)))
예제 #9
0
 def list_permission(self, source: CommandSource,
                     target_value: Optional[str]):
     specified_level = PermissionLevel.get_level(target_value)
     if specified_level is None:
         # show default level information if target permission not specified
         source.reply(
             RText(
                 self.tr(
                     'mcdr_command.list_permission.show_default',
                     self.mcdr_server.permission_manager.
                     get_default_permission_level())).c(
                         RAction.suggest_command,
                         '{} permission setdefault '.format(
                             self.control_command_prefix)).
             h(self.tr('mcdr_command.list_permission.suggest_setdefault')))
     for permission_level in PermissionLevel.INSTANCES:
         if specified_level is None or permission_level == specified_level:
             source.reply(
                 RText('§7[§e{}§7]§r'.format(permission_level.name)).c(
                     RAction.run_command, '{} permission list {}'.format(
                         self.control_command_prefix, permission_level.name)
                 ).h(
                     self.tr('mcdr_command.list_permission.suggest_list',
                             permission_level.name)))
             for player in self.mcdr_server.permission_manager.get_permission_group_list(
                     permission_level.name):
                 texts = RText('§7-§r {}'.format(player))
                 if self.can_see_rtext(source):
                     texts += RTextList(
                         RText(' [✎]', color=RColor.gray).c(
                             RAction.suggest_command,
                             '{} permission set {} '.format(
                                 self.control_command_prefix,
                                 string_util.auto_quotes(player))).
                         h(
                             self.tr(
                                 'mcdr_command.list_permission.suggest_set',
                                 player)),
                         RText(' [×]', color=RColor.gray).c(
                             RAction.suggest_command,
                             '{} permission remove {}'.format(
                                 self.control_command_prefix,
                                 string_util.auto_quotes(player))).
                         h(
                             self.tr(
                                 'mcdr_command.list_permission.suggest_disable',
                                 player)),
                     )
                 source.reply(texts)
 def __detail_hint(self, text: RTextBase, pref_name: str) -> RTextBase:
     return (text.h(
         self.tr('mcdr_command.preference.list.detail_hint',
                 RText(pref_name, PREF_COLOR))).c(
                     RAction.run_command,
                     '{} preference {}'.format(self.control_command_prefix,
                                               pref_name)))
예제 #11
0
 def on_mcdr_command_unknown_argument(self, source: CommandSource,
                                      error: CommandError):
     command = error.get_parsed_command().rstrip(' ')
     source.reply(
         RText(self.tr('mcdr_command.command_not_found', command)).h(
             self.tr('mcdr_command.command_not_found_suggest',
                     command)).c(RAction.run_command, command))
예제 #12
0
 def add_if_not_empty(msg: RTextList, lst: List['AbstractPlugin'
                                                or str], key: str):
     if len(lst) > 0:
         add_element(
             msg,
             RText(self.__mcdr_server.tr(key, len(lst))).h('\n'.join(
                 map(str, lst))))
예제 #13
0
 def __check_update(self, condition_check: Callable[[], bool],
                    reply_func: Callable[[Union[str or RTextBase]], Any]):
     if not condition_check():
         return
     acquired = self.update_lock.acquire(blocking=False)
     if not acquired:
         reply_func(
             self.mcdr_server.tr(
                 'update_helper.check_update.already_checking'))
         return
     try:
         response = None
         try:
             response = requests.get(constant.GITHUB_API_LATEST,
                                     timeout=5).json()
             latest_version = response['tag_name']  # type: str
             update_log = response['body']
         except Exception as e:
             reply_func(
                 self.mcdr_server.tr(
                     'update_helper.check_update.check_fail', repr(e)))
             if isinstance(e, KeyError) and type(
                     response) is dict and 'message' in response:
                 reply_func(response['message'])
                 if 'documentation_url' in response:
                     reply_func(
                         RText(response['documentation_url'],
                               color=RColor.blue,
                               styles=RStyle.underlined).h(
                                   response['documentation_url']).c(
                                       RAction.open_url,
                                       response['documentation_url']))
         else:
             try:
                 cmp_result = misc_util.version_compare(
                     constant.VERSION, latest_version.lstrip('v'))
             except:
                 self.mcdr_server.logger.exception(
                     'Fail to compare between versions "{}" and "{}"'.
                     format(constant.VERSION, latest_version))
                 return
             if cmp_result == 0:
                 reply_func(
                     self.mcdr_server.tr(
                         'update_helper.check_update.is_already_latest'))
             elif cmp_result == 1:
                 reply_func(
                     self.mcdr_server.tr(
                         'update_helper.check_update.newer_than_latest',
                         constant.VERSION, latest_version))
             else:
                 reply_func(
                     self.mcdr_server.tr(
                         'update_helper.check_update.new_version_detected',
                         latest_version))
                 for line in update_log.splitlines():
                     reply_func('    {}'.format(line))
     finally:
         self.update_lock.release()
예제 #14
0
    def process_help_command(self, source: CommandSource,
                             context: CommandContext):
        page = context.get('page')
        source.reply(self.tr('mcdr_command.help_message.title'))
        matched = []  # type: List[HelpMessage]
        for msg in self.mcdr_server.plugin_manager.registry_storage.help_messages:  # type: HelpMessage
            if source.has_permission(msg.permission):
                matched.append(msg)
        matched_count = len(matched)

        if page is not None:
            left, right = (
                page - 1) * HELP_MESSAGE_PER_PAGE, page * HELP_MESSAGE_PER_PAGE
        else:
            left, right = 0, matched_count
        for i in range(left, right):
            if 0 <= i < matched_count:
                msg = matched[i]
                source.reply(
                    RTextList(
                        RText(msg.prefix,
                              color=RColor.gray).c(RAction.suggest_command,
                                                   msg.prefix), ': ',
                        translation_util.translate_from_dict(
                            msg.message,
                            self.server_interface.get_mcdr_language(),
                            default='')))

        if page is not None:
            has_prev = 0 < left < matched_count
            has_next = 0 < right < matched_count
            color = {False: RColor.dark_gray, True: RColor.gray}
            prev_page = RText('<-', color=color[has_prev])
            if has_prev:
                prev_page.c(RAction.run_command, '{} {}'.format(
                    self.help_command_prefix, page - 1)).h(
                        self.tr(
                            'mcdr_command.help_message.previous_page_hover'))
            next_page = RText('->', color=color[has_next])
            if has_next:
                next_page.c(RAction.run_command, '{} {}'.format(
                    self.help_command_prefix, page + 1)).h(
                        self.tr('mcdr_command.help_message.next_page_hover'))

            source.reply(
                RTextList(
                    prev_page, ' {} '.format(
                        self.tr('mcdr_command.help_message.page_number',
                                page)), next_page))
예제 #15
0
 def __check_update(self, condition_check: Callable[[], bool],
                    reply_func: Callable[[Union[str or RTextBase]], Any]):
     if not condition_check():
         return
     acquired = self.__update_lock.acquire(blocking=False)
     if not acquired:
         reply_func(self.tr('update_helper.check_update.already_checking'))
         return
     try:
         response = None
         try:
             response = self.__api_fetcher.fetch()
             latest_version: str = response['tag_name']
             update_log: str = response['body']
         except Exception as e:
             reply_func(
                 self.tr('update_helper.check_update.check_fail', repr(e)))
             if isinstance(e, KeyError) and isinstance(
                     response, dict) and 'message' in response:
                 reply_func(response['message'])
                 if 'documentation_url' in response:
                     reply_func(
                         RText(response['documentation_url'],
                               color=RColor.blue,
                               styles=RStyle.underlined).h(
                                   response['documentation_url']).c(
                                       RAction.open_url,
                                       response['documentation_url']))
         else:
             try:
                 version_current = Version(core_constant.VERSION,
                                           allow_wildcard=False)
                 version_fetched = Version(latest_version.lstrip('vV'),
                                           allow_wildcard=False)
             except:
                 self.mcdr_server.logger.exception(
                     'Fail to compare between versions "{}" and "{}"'.
                     format(core_constant.VERSION, latest_version))
                 return
             if version_current == version_fetched:
                 reply_func(
                     self.tr(
                         'update_helper.check_update.is_already_latest'))
             elif version_current > version_fetched:
                 reply_func(
                     self.tr('update_helper.check_update.newer_than_latest',
                             core_constant.VERSION, latest_version))
             else:
                 reply_func(
                     self.tr(
                         'update_helper.check_update.new_version_detected',
                         latest_version))
                 for line in update_log.splitlines():
                     reply_func('    {}'.format(line))
     finally:
         self.__update_lock.release()
예제 #16
0
    def to_rtext(self, *, show_path: bool) -> RTextBase:
        if not self.__has_record:
            raise IllegalCallError('No record yet')

        def add_element(msg: RTextList, element):
            msg.append(element)
            msg.append('; ')

        def add_if_not_empty(msg: RTextList, lst: List['AbstractPlugin'
                                                       or str], key: str):
            if len(lst) > 0:
                text_list = []
                for ele in lst:
                    if isinstance(ele, str):
                        text_list.append(
                            ele if show_path else os.path.basename(ele))
                    else:
                        text_list.append(str(ele))
                add_element(
                    msg,
                    RText(self.__mcdr_server.tr(key, len(lst))).h(
                        '\n'.join(text_list)))

        message = RTextList()
        add_if_not_empty(
            message,
            list(
                filter(
                    lambda plg: plg in self.dependency_check_result.
                    success_list, self.load_result.success_list)),
            'plugin_operation_result.info_loaded_succeeded')
        add_if_not_empty(message, self.unload_result.success_list,
                         'plugin_operation_result.info_unloaded_succeeded')
        add_if_not_empty(message, self.reload_result.success_list,
                         'plugin_operation_result.info_reloaded_succeeded')
        add_if_not_empty(message, self.load_result.failed_list,
                         'plugin_operation_result.info_loaded_failed')
        add_if_not_empty(message, self.unload_result.failed_list,
                         'plugin_operation_result.info_unloaded_failed')
        add_if_not_empty(message, self.reload_result.failed_list,
                         'plugin_operation_result.info_reloaded_failed')
        add_if_not_empty(
            message, self.dependency_check_result.failed_list,
            'plugin_operation_result.info_dependency_check_failed')
        if message.is_empty():
            add_element(
                message,
                self.__mcdr_server.tr('plugin_operation_result.info_none'))
        message.append(
            RText(
                self.__mcdr_server.tr(
                    'plugin_operation_result.info_plugin_amount',
                    len(self.__plugin_manager.plugins))).h('\n'.join(
                        map(str, self.__plugin_manager.plugins.values()))).c(
                            RAction.suggest_command, '!!MCDR plugin list'))
        return message
예제 #17
0
 def on_mcdr_command_unknown_argument(self, source: CommandSource,
                                      error: CommandError):
     if source.has_permission(PermissionLevel.MCDR_CONTROL_LEVEL):
         command = error.get_parsed_command().rstrip(' ')
         source.reply(
             RText(self.tr('mcdr_command.command_not_found', command)).h(
                 self.tr('mcdr_command.command_not_found_suggest',
                         command)).c(RAction.run_command, command))
     else:
         self.on_mcdr_command_permission_denied(source, error)
예제 #18
0
 def list_permission(self, source: CommandSource, target_value):
     specified_level = PermissionLevel.get_level(target_value)
     if specified_level is None:
         # show default level information if target permission not specified
         source.reply(
             RText(
                 self.tr(
                     'mcdr_command.list_permission.show_default',
                     self.mcdr_server.permission_manager.
                     get_default_permission_level())).c(
                         RAction.suggest_command,
                         '!!MCDR permission setdefault ').
             h(self.tr('mcdr_command.list_permission.suggest_setdefault')))
     for permission_level in PermissionLevel.INSTANCES:
         if specified_level is None or permission_level == specified_level:
             source.reply(
                 RText('§7[§e{}§7]§r'.format(permission_level.name)).c(
                     RAction.run_command, '!!MCDR permission list {}'.
                     format(permission_level.name)).h(
                         self.tr(
                             'mcdr_command.list_permission.suggest_list',
                             permission_level.name)))
             for player in self.mcdr_server.permission_manager.get_permission_group_list(
                     permission_level.name):
                 texts = RText('§7-§r {}'.format(player))
                 if self.should_display_buttons(source):
                     texts += RTextList(
                         RText(' [✎]', color=RColor.gray).c(
                             RAction.suggest_command,
                             '!!MCDR permission set {} '.format(player)).
                         h(
                             self.tr(
                                 'mcdr_command.list_permission.suggest_set',
                                 player)),
                         RText(' [×]', color=RColor.gray).c(
                             RAction.suggest_command,
                             '!!MCDR permission remove {}'.format(player)).
                         h(
                             self.tr(
                                 'mcdr_command.list_permission.suggest_disable',
                                 player)),
                     )
                 source.reply(texts)
예제 #19
0
 def get_help_message(self, translation_key):
     lst = RTextList()
     for line in self.tr(translation_key).splitlines(keepends=True):
         prefix = re.search(r'(?<=§7)!!MCDR[\w ]*(?=§)', line)
         if prefix is not None:
             lst.append(
                 RText(line).c(RAction.suggest_command, prefix.group()))
         else:
             lst.append(line)
     return lst
예제 #20
0
 def set_language(self, source: CommandSource, language: str):
     available_languages = self.mcdr_server.translation_manager.available_languages
     if language not in available_languages:
         source.reply(
             self.tr('mcdr_command.set_language.not_available', language))
         lang_texts = []
         for lang in available_languages:
             lang_texts.append(
                 RText(lang, color=RColor.yellow).c(
                     RAction.run_command,
                     '{} setlang {}'.format(self.control_command_prefix,
                                            lang)))
         source.reply(
             self.tr('mcdr_command.set_language.language_list',
                     RText.join(', ', lang_texts)))
     else:
         self.mcdr_server.config.set_value('language', language)
         self.mcdr_server.translation_manager.set_language(language)
         source.reply(self.tr('mcdr_command.set_language.success',
                              language))
예제 #21
0
    def __init__(self, translation_key: str, *args, **kwargs):
        self.translation_key: str = translation_key
        self.args = args
        self.kwargs = kwargs
        self.__translator = lambda *args_, **kwargs_: RText(self.
                                                            translation_key)
        self.__post_process: List[Callable[[RTextBase], RTextBase]] = []

        from mcdreforged.plugin.server_interface import ServerInterface
        server: Optional[ServerInterface] = ServerInterface.get_instance()
        if server is not None:
            self.set_translator(server.tr)
예제 #22
0
    def get_rtext_list(self):
        voxel_command = '/newWaypoint [name:{}, x:{}, y:{}, z:{}, dim:{}, world:{}]'.format(
            self.name, self.x, self.y, self.z, self.get_dim_str(self.dim_id),
            waypoint_config['world'])
        xaero_command = 'xaero_waypoint_add:{}:{}:{}:{}:{}:6:false:0:Internal_{}_waypoints'.format(
            self.name.replace(':', '^col^'), self.name[0], self.x, self.y,
            self.z,
            self.get_dim_str(self.dim_id).replace('minecraft:', ''))
        ret = RTextList(
            RText('[+V]', color=RColor.gold).h(
                '§6Voxemapl§r: 左键高亮路径点, ctrl + 左键点击添加路径点').c(
                    RAction.run_command, voxel_command),
            RText('[+X] ',
                  color=RColor.gold).h('§6Xaeros Minimap§r: 点击添加路径点').c(
                      RAction.run_command, xaero_command))
        ret.append(self.name + ' ')
        ret.append(
            RText('({}, {}, {})'.format(self.x, self.y, self.z),
                  color=self.color_map[self.dim_id]))
        ret.append(' ')
        ret.append(self.get_dim_rtext(self.dim_id))

        if self.dim_id == 0:
            ret.append(' -> ')
            ret.append(
                RText('({}, {}, {})'.format(self.x // 8, self.y // 8,
                                            self.z // 8),
                      color=self.color_map[-1]))
            ret.append(' ')
            ret.append(self.get_dim_rtext(-1))
        elif self.dim_id == -1:
            ret.append(' -> ')
            ret.append(
                RText('({}, {}, {})'.format(self.x * 8, self.y * 8,
                                            self.z * 8),
                      color=self.color_map[0]))
            ret.append(' ')
            ret.append(self.get_dim_rtext(0))

        return ret
예제 #23
0
 def add_if_not_empty(msg: RTextList, lst: List['AbstractPlugin'
                                                or str], key: str):
     if len(lst) > 0:
         text_list = []
         for ele in lst:
             if isinstance(ele, str):
                 text_list.append(
                     ele if show_path else os.path.basename(ele))
             else:
                 text_list.append(str(ele))
         add_element(
             msg,
             RText(self.__mcdr_server.tr(key, len(lst))).h(
                 '\n'.join(text_list)))
예제 #24
0
 def get_help_message(self, source: CommandSource, translation_key: str):
     lst = RTextList()
     with source.preferred_language_context():
         for line in self.tr(translation_key).to_plain_text().splitlines(
                 keepends=True):
             prefix = re.search(
                 r'(?<=§7)' + self.control_command_prefix + r'[\w ]*(?=§)',
                 line)
             if prefix is not None:
                 lst.append(
                     RText(line).c(RAction.suggest_command, prefix.group()))
             else:
                 lst.append(line)
     return lst
예제 #25
0
    def register_help_message(
            self,
            prefix: str,
            message: Union[str, RTextBase],
            permission: int = PermissionLevel.MINIMUM_LEVEL) -> None:
        """
		Register a help message for the current plugin, which is used in !!help command
		:param prefix: The help command of your plugin. When player click on the displayed message it will suggest this
		prefix parameter to the player. It's recommend to set it to the entry command of your plugin
		:param message: A neat command description
		:param permission: The minimum permission level for the user to see this help message. With default, anyone
		can see this message
		:raise: IllegalCallError if it's not invoked in the task executor thread
		"""
        plugin = self.__get_current_plugin()
        if isinstance(message, str):
            message = RText(message)
        plugin.register_help_message(
            HelpMessage(plugin, prefix, message, permission))
예제 #26
0
class RequirementNotMet(CommandError):
    """
	The specified requirement for the command source to enter this node is not met
	"""
    __NO_REASON = RText('Requirement not met')

    def __init__(self, parsed_command: str, failed_command: str,
                 reason: Optional[MessageText]):
        self.__reason: MessageText = reason if reason is not None else self.__NO_REASON
        super().__init__(self.__reason, parsed_command, failed_command)

    def has_custom_reason(self) -> bool:
        return self.__reason is not self.__NO_REASON

    def get_reason(self) -> MessageText:
        return self.__reason

    def get_error_data(self) -> tuple:
        return (self.get_reason(), )
예제 #27
0
    def add_help_message(self,
                         prefix,
                         message,
                         permission=PermissionLevel.MINIMUM_LEVEL):
        """
		Add a help message for the current plugin, which is used in !!help command

		:param str prefix: The help command of your plugin
		When player click on the displayed message it will suggest this prefix parameter to the player
		:param str or RTextBase message: A neat command description
		:param int permission: The minimum permission level for the user to see this help message. With default, anyone
		can see this message
		:raise: IllegalCallError if it's not called in a MCDR provided thread
		"""
        plugin = self.__get_current_plugin()
        if isinstance(message, str):
            message = RText(message)
        plugin.add_help_message(
            HelpMessage(plugin, prefix, message, permission))
예제 #28
0
    def print_mcdr_status(self, source: CommandSource):
        def bool_formatter(bl: bool) -> RText:
            return RText(bl, RColor.green if bl else RColor.red)

        rcon_status_dict = {
            True: self.tr('mcdr_command.print_mcdr_status.online'),
            False: self.tr('mcdr_command.print_mcdr_status.offline')
        }

        source.reply(
            RText(
                self.tr('mcdr_command.print_mcdr_status.line1',
                        core_constant.NAME, core_constant.VERSION)).c(
                            RAction.open_url, core_constant.GITHUB_URL).h(
                                RText(core_constant.GITHUB_URL,
                                      styles=RStyle.underlined,
                                      color=RColor.blue)))

        if not source.has_permission(PermissionLevel.MCDR_CONTROL_LEVEL):
            return
        source.reply(
            RText.join('\n', [
                RText(
                    self.tr('mcdr_command.print_mcdr_status.line2',
                            self.tr(self.mcdr_server.mcdr_state.value))),
                RText(
                    self.tr('mcdr_command.print_mcdr_status.line3',
                            self.tr(self.mcdr_server.server_state.value))),
                RText(
                    self.tr(
                        'mcdr_command.print_mcdr_status.line4',
                        bool_formatter(self.mcdr_server.is_server_startup()))),
                RText(
                    self.tr(
                        'mcdr_command.print_mcdr_status.line5',
                        bool_formatter(
                            self.mcdr_server.should_exit_after_stop()))),
                RText(
                    self.tr(
                        'mcdr_command.print_mcdr_status.line6',
                        rcon_status_dict[
                            self.server_interface.is_rcon_running()])),
                RText(
                    self.
                    tr('mcdr_command.print_mcdr_status.line7',
                       self.mcdr_server.plugin_manager.get_plugin_amount())).c(
                           RAction.suggest_command, '!!MCDR plugin list')
            ]))

        if not source.has_permission(
                PermissionLevel.PHYSICAL_SERVER_CONTROL_LEVEL):
            return
        source.reply(
            RText.join('\n', [
                self.tr(
                    'mcdr_command.print_mcdr_status.extra_line1',
                    self.mcdr_server.process.pid
                    if self.mcdr_server.process is not None else '§rN/A§r'),
                self.tr('mcdr_command.print_mcdr_status.extra_line2',
                        self.mcdr_server.task_executor.task_queue.qsize(),
                        core_constant.MAX_TASK_QUEUE_SIZE),
                self.tr('mcdr_command.print_mcdr_status.extra_line3',
                        threading.active_count())
            ]))
        thread_pool_counts = 0
        for thread in threading.enumerate():
            name = thread.getName()
            if not name.startswith('ThreadPoolExecutor-'):
                source.reply('  §7-§r {}'.format(name))
            else:
                thread_pool_counts += 1
        if thread_pool_counts > 0:
            source.reply('  §7-§r ThreadPoolExecutor thread x{}'.format(
                thread_pool_counts))
예제 #29
0
 def bool_formatter(bl: bool) -> RText:
     return RText(bl, RColor.green if bl else RColor.red)
예제 #30
0
    def list_plugin(self, source: CommandSource):
        not_loaded_plugin_list = self.get_files_in_plugin_directories(
            lambda fp: fp.endswith(plugin_constant.SOLO_PLUGIN_FILE_SUFFIX) and
            not self.mcdr_server.plugin_manager.contains_plugin_file(
                fp))  # type: List[str]
        disabled_plugin_list = self.get_files_in_plugin_directories(
            lambda fp: fp.endswith(plugin_constant.DISABLED_PLUGIN_FILE_SUFFIX)
        )  # type: List[str]
        current_plugins = list(self.mcdr_server.plugin_manager.get_all_plugins(
        ))  # type: List[AbstractPlugin]

        source.reply(
            self.tr('mcdr_command.list_plugin.info_loaded_plugin',
                    len(current_plugins)))
        for plugin in current_plugins:
            meta = plugin.get_metadata()
            displayed_name = RText(meta.name)
            if not self.can_see_rtext(source):
                displayed_name += RText(' ({})'.format(
                    plugin.get_identifier()),
                                        color=RColor.gray)
            texts = RTextList(
                '§7-§r ',
                displayed_name.c(
                    RAction.run_command, '{} plugin info {}'.format(
                        self.control_command_prefix, meta.id)).h(
                            self.tr('mcdr_command.list_plugin.suggest_info',
                                    plugin.get_identifier())))
            if self.can_see_rtext(source) and not plugin.is_permanent():
                texts.append(
                    ' ',
                    RText('[↻]', color=RColor.gray).c(
                        RAction.run_command, '{} plugin reload {}'.format(
                            self.control_command_prefix, meta.id)).h(
                                self.tr(
                                    'mcdr_command.list_plugin.suggest_reload',
                                    meta.id)), ' ',
                    RText('[↓]', color=RColor.gray).c(
                        RAction.run_command, '{} plugin unload {}'.format(
                            self.control_command_prefix, meta.id)).h(
                                self.tr(
                                    'mcdr_command.list_plugin.suggest_unload',
                                    meta.id)), ' ',
                    RText('[×]', color=RColor.gray).c(
                        RAction.run_command, '{} plugin disable {}'.format(
                            self.control_command_prefix, meta.id)).h(
                                self.tr(
                                    'mcdr_command.list_plugin.suggest_disable',
                                    meta.id)))
            source.reply(texts)

        def get_file_name(fp) -> Tuple[str, RText]:
            name = os.path.basename(fp)
            name_text = RText(name)
            if source.has_permission(
                    PermissionLevel.PHYSICAL_SERVER_CONTROL_LEVEL):
                name_text.h(fp)
            return name, name_text

        source.reply(
            self.tr('mcdr_command.list_plugin.info_disabled_plugin',
                    len(disabled_plugin_list)))
        for file_path in disabled_plugin_list:
            file_name, file_name_text = get_file_name(file_path)
            texts = RTextList(RText('- ', color=RColor.gray), file_name_text)
            if self.can_see_rtext(source):
                texts.append(
                    ' ',
                    RText('[✔]', color=RColor.gray).c(
                        RAction.run_command, '{} plugin enable {}'.format(
                            self.control_command_prefix, file_name)).h(
                                self.tr(
                                    'mcdr_command.list_plugin.suggest_enable',
                                    file_name)))
            source.reply(texts)

        source.reply(
            self.tr('mcdr_command.list_plugin.info_not_loaded_plugin',
                    len(not_loaded_plugin_list)))
        for file_path in not_loaded_plugin_list:
            file_name, file_name_text = get_file_name(file_path)
            texts = RTextList(RText('- ', color=RColor.gray), file_name_text)
            if self.can_see_rtext(source):
                texts.append(
                    ' ',
                    RText('[↑]', color=RColor.gray).c(
                        RAction.run_command, '{} plugin load {}'.format(
                            self.control_command_prefix, file_name)).h(
                                self.tr(
                                    'mcdr_command.list_plugin.suggest_load',
                                    file_name)))
            source.reply(texts)