Esempio n. 1
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()
 def get_send_message_command(
         self, target: str, message: Any,
         server_information: ServerInformation) -> Optional[str]:
     can_do_execute = False
     try:
         from mcdreforged.plugin.meta.version import Version
         version = Version(server_information.version.split(' ')[0])
         if version >= Version('1.13.0'):
             can_do_execute = True
     except:
         pass
     command = 'tellraw {} {}'.format(target, self.format_message(message))
     if can_do_execute:
         command = 'execute at @p run ' + command
     return command
Esempio n. 3
0
 def test_and_return(version_str: str) -> Optional[str]:
     try:
         Version(version_str, allow_wildcard=False)
     except:
         return None
     else:
         return version_str
Esempio n. 4
0
def version_compare(v1: str, v2: str) -> int:
    version1 = Version(v1, allow_wildcard=False)
    version2 = Version(v2, allow_wildcard=False)
    return version1.compare_to(version2)
Esempio n. 5
0
	def __init__(self, data: Optional[dict], *, plugin: Optional['AbstractPlugin'] = None):
		"""
		:param AbstractPlugin plugin: the plugin which this metadata is belong to
		:param dict or None data: a dict with information of the plugin
		"""
		if not isinstance(data, dict):
			data = {}

		def warn(*args, **kwargs):
			if plugin is not None:
				plugin.mcdr_server.logger.warning(*args, **kwargs)

		plugin_name_text = repr(plugin)

		use_fallback_id_reason = None
		self.id = data.get('id')
		if self.id is None:
			use_fallback_id_reason = 'Plugin ID of {} not found'.format(plugin_name_text)
		elif not isinstance(self.id, str) or re.fullmatch(r'[a-z0-9_]{1,64}', self.id) is None:
			use_fallback_id_reason = 'Plugin ID "{}" of {} is invalid'.format(self.id, plugin_name_text)
		if use_fallback_id_reason is not None:
			if plugin is not None:
				self.id = plugin.get_fallback_metadata_id()
				warn('{}, use fallback id {} instead'.format(use_fallback_id_reason, self.id))
			else:
				raise ValueError('Plugin id not found in metadata')

		self.name = data.get('name', self.id)
		if isinstance(self.name, RTextBase):
			self.name = self.name.to_plain_text()

		description = data.get('description')
		if isinstance(description, RTextBase):
			description = description.to_plain_text()
		self.description = description

		self.author = data.get('author')
		if isinstance(self.author, str):
			self.author = [self.author]
		if isinstance(self.author, list):
			for i in range(len(self.author)):
				self.author[i] = str(self.author[i])
			if len(self.author) == 0:
				self.author = None

		self.link = data.get('link')
		if not isinstance(self.link, str):
			self.link = None

		version_str = data.get('version')
		if version_str:
			try:
				self.version = Version(version_str, allow_wildcard=False)
			except VersionParsingError as e:
				warn('Version "{}" of {} is invalid ({}), ignore and use fallback version instead {}'.format(version_str, plugin_name_text, e, self.FALLBACK_VERSION))
				version_str = None
		else:
			warn('{} doesn\'t specific a version, use fallback version {}'.format(plugin_name_text, self.FALLBACK_VERSION))
		if version_str is None:
			self.version = Version(self.FALLBACK_VERSION)

		self.dependencies = {}
		for plugin_id, requirement in data.get('dependencies', {}).items():
			try:
				self.dependencies[plugin_id] = VersionRequirement(requirement)
			except VersionParsingError as e:
				warn('Dependency "{}: {}" of {} is invalid ({}), ignore'.format(
					plugin_id, requirement, plugin_name_text, e
				))

		self.entrypoint = data.get('entrypoint', self.id)
		# entrypoint module should be inside the plugin module
		if self.entrypoint != self.id and not self.entrypoint.startswith(self.id + '.'):
			raise ValueError('Invalid entry point "{}" for plugin id "{}"'.format(self.entrypoint, self.id))
		self.archive_name = data.get('archive_name')
		self.resources = data.get('resources', [])
Esempio n. 6
0
    def __init__(self, plugin: 'AbstractPlugin', data: dict):
        """
		:param AbstractPlugin plugin: the plugin which this metadata is belong to
		:param dict or None data: a dict with information of the plugin
		"""
        if not isinstance(data, dict):
            data = {}
        logger = plugin.mcdr_server.logger

        use_fallback_id_reason = None
        self.id = data.get('id')
        if self.id is None:
            use_fallback_id_reason = 'Plugin ID of {} not found'.format(plugin)
        elif not isinstance(self.id, str) or re.fullmatch(
                r'[a-z0-9_]{1,64}', self.id) is None:
            use_fallback_id_reason = 'Plugin ID "{}" of {} is invalid'.format(
                self.id, plugin)
        if use_fallback_id_reason is not None:
            self.id = plugin.get_fallback_metadata_id()
            logger.warning('{}, use fallback id {} instead'.format(
                use_fallback_id_reason, self.id))

        self.name = RTextBase.from_any(data.get('name', self.id))

        self.description = data.get('description')
        if self.description is not None:
            self.description = RTextBase.from_any(self.description)

        self.author = data.get('author')
        if isinstance(self.author, str):
            self.author = [self.author]
        if isinstance(self.author, list):
            for i in range(len(self.author)):
                self.author[i] = str(self.author[i])
            if len(self.author) == 0:
                self.author = None

        self.link = data.get('link')
        if not isinstance(self.link, str):
            self.link = None

        version_str = data.get('version')
        if version_str:
            try:
                self.version = Version(version_str, allow_wildcard=False)
            except VersionParsingError as e:
                logger.warning(
                    'Version "{}" of {} is invalid ({}), ignore and use fallback version instead {}'
                    .format(version_str, plugin, e, self.FALLBACK_VERSION))
                version_str = None
        else:
            logger.warning(
                '{} doesn\'t specific a version, use fallback version {}'.
                format(plugin, self.FALLBACK_VERSION))
        if version_str is None:
            self.version = Version(self.FALLBACK_VERSION)

        self.dependencies = {}
        for plugin_id, requirement in data.get('dependencies', {}).items():
            try:
                self.dependencies[plugin_id] = VersionRequirement(requirement)
            except VersionParsingError as e:
                logger.warning(
                    'Dependency "{}: {}" of {} is invalid ({}), ignore'.format(
                        plugin_id, requirement, plugin.get_name(), e))