Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: General fixing and clean-up on translate() #1364

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions src/viur/core/bones/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,18 @@

assert isinstance(values, (dict, OrderedDict))

prefix = self.translation_key_prefix
if callable(prefix):
prefix = prefix(self)

values = {
key: label if isinstance(label, translate) else translate(
f"{prefix}{label}", str(label),
f"value {key} for {self.name}<{type(self).__name__}> in {self.skel_cls.__name__} in {self.skel_cls}"
)
for key, label in values.items()
}
if self.languages:
prefix = self.translation_key_prefix
if callable(prefix):
prefix = prefix(self)

values = {
key: label if isinstance(label, translate) else translate(
f"{prefix}{label}", str(label),
f"value {key} for {self.name}<{type(self).__name__}> in {self.skel_cls.__name__} in {self.skel_cls}"

Check failure on line 103 in src/viur/core/bones/select.py

View workflow job for this annotation

GitHub Actions / linter (3.12)

E501: line too long (124 > 120 characters)
)
for key, label in values.items()
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wip


return values

Expand Down
11 changes: 10 additions & 1 deletion src/viur/core/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,12 @@ def __str__(self) -> str:

from viur.core.render.html.env.viur import translate as jinja_translate

if self.key not in systemTranslations and conf.i18n.add_missing_translations:
if (
not self.key.startswith("core.")
and not self.key.startswith("viur.")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wip

and self.key not in systemTranslations
and conf.i18n.add_missing_translations
):
# This translation seems to be new and should be added
filename = lineno = None
is_jinja = False
Expand Down Expand Up @@ -428,6 +433,10 @@ def add_missing_translation(
public: bool = False,
) -> None:
"""Add missing translations to datastore"""

logging.error(f"{key=} {hint=} {default_text=} {filename=} {lineno=} {variables=} {public=}")
raise RuntimeError("ICH WILL DAS NICHT")

try:
from viur.core.modules.translation import TranslationSkel, Creator
except ImportError as exc:
Expand Down
2 changes: 1 addition & 1 deletion src/viur/core/modules/moduleconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ModuleConfScriptSkel(skeleton.RelSkel):
access = SelectBone(
descr="Required access rights",
values=lambda: {
right: i18n.translate(f"viur.modules.user.accessright.{right}", defaultText=right)
right: i18n.translate(f"viur.core.modules.user.accessright.{right}", defaultText=right)
for right in sorted(conf.user.access_rights)
},
multiple=True,
Expand Down
2 changes: 1 addition & 1 deletion src/viur/core/modules/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class ScriptLeafSkel(BaseScriptAbstractSkel):
access = SelectBone(
descr="Required access rights to run this Script",
values=lambda: {
right: translate(f"viur.modules.user.accessright.{right}", defaultText=right)
right: translate(f"viur.core.modules.user.accessright.{right}", defaultText=right)
for right in sorted(conf.user.access_rights)
},
multiple=True,
Expand Down
42 changes: 23 additions & 19 deletions src/viur/core/modules/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,29 @@ class TranslationSkel(Skeleton):
kindName = KINDNAME

tr_key = StringBone(
required=True,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important!

descr=translate(
"core.translationskel.tr_key.descr",
"viur.core.translationskel.tr_key.descr",
"Translation key",
),
searchable=True,
unique=UniqueValue(UniqueLockMethod.SameValue, False,
"This translation key exist already"),
unique=UniqueValue(
UniqueLockMethod.SameValue,
False,
"This translation key exist already"
),
)

translations = StringBone(
descr=translate(
"core.translationskel.translations.descr",
"viur.core.translationskel.translations.descr",
"Translations",
),
searchable=True,
languages=conf.i18n.available_dialects,
params={
"tooltip": translate(
"core.translationskel.translations.tooltip",
"viur.core.translationskel.translations.tooltip",
"The languages {{main}} are required,\n {{accent}} can be filled out"
)(main=", ".join(conf.i18n.available_languages),
accent=", ".join(conf.i18n.language_alias_map.keys())),
Expand All @@ -48,7 +52,7 @@ class TranslationSkel(Skeleton):

translations_missing = SelectBone(
descr=translate(
"core.translationskel.translations_missing.descr",
"viur.core.translationskel.translations_missing.descr",
"Translation missing for language",
),
multiple=True,
Expand All @@ -64,37 +68,37 @@ class TranslationSkel(Skeleton):

default_text = StringBone(
descr=translate(
"core.translationskel.default_text.descr",
"viur.core.translationskel.default_text.descr",
"Fallback value",
),
)

hint = StringBone(
descr=translate(
"core.translationskel.hint.descr",
"viur.core.translationskel.hint.descr",
"Hint / Context (internal only)",
),
)

usage_filename = StringBone(
descr=translate(
"core.translationskel.usage_filename.descr",
"viur.core.translationskel.usage_filename.descr",
"Used and added from this file",
),
readOnly=True,
)

usage_lineno = NumericBone(
descr=translate(
"core.translationskel.usage_lineno.descr",
"viur.core.translationskel.usage_lineno.descr",
"Used and added from this lineno",
),
readOnly=True,
)

usage_variables = StringBone(
descr=translate(
"core.translationskel.usage_variables.descr",
"viur.core.translationskel.usage_variables.descr",
"Receives these substitution variables",
),
readOnly=True,
Expand All @@ -103,7 +107,7 @@ class TranslationSkel(Skeleton):

creator = SelectBone(
descr=translate(
"core.translationskel.creator.descr",
"viur.core.translationskel.creator.descr",
"Creator",
),
readOnly=True,
Expand All @@ -113,24 +117,24 @@ class TranslationSkel(Skeleton):

public = BooleanBone(
descr=translate(
"core.translationskel.public.descr",
"viur.core.translationskel.public.descr",
"Is this translation public?",
),
defaultValue=False,
)

@classmethod
def write(cls, skelValues: SkeletonInstance, **kwargs) -> db.Key:
def write(cls, skel: SkeletonInstance, **kwargs) -> db.Key:
# Ensure we have only lowercase keys
skelValues["tr_key"] = skelValues["tr_key"].lower()
return super().write(skelValues, **kwargs)
skel["tr_key"] = skel["tr_key"].lower()
return super().write(skel, **kwargs)

@classmethod
def preProcessSerializedData(cls, skelValues: SkeletonInstance, entity: db.Entity) -> db.Entity:
def preProcessSerializedData(cls, skel: SkeletonInstance, entity: db.Entity) -> db.Entity:
# Backward-compatibility: re-add the key for viur-core < v3.6
# TODO: Remove in ViUR4
entity["key"] = skelValues["tr_key"]
return super().preProcessSerializedData(skelValues, entity)
entity["key"] = skel["tr_key"]
return super().preProcessSerializedData(skel, entity)


class Translation(List):
Expand Down
42 changes: 21 additions & 21 deletions src/viur/core/modules/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class UserSkel(skeleton.Skeleton):
)

roles = SelectBone(
descr=i18n.translate("viur.user.bone.roles", defaultText="Roles"),
descr=i18n.translate("viur.core.modules.user.bone.roles", defaultText="Roles"),
values=conf.user.roles,
required=True,
multiple=True,
Expand All @@ -91,10 +91,10 @@ class UserSkel(skeleton.Skeleton):
)

access = SelectBone(
descr=i18n.translate("viur.user.bone.access", defaultText="Access rights"),
descr=i18n.translate("viur.core.modules.user.bone.access", defaultText="Access rights"),
type_suffix="access",
values=lambda: {
right: i18n.translate(f"viur.modules.user.accessright.{right}", defaultText=right)
right: i18n.translate(f"viur.core.modules.user.accessright.{right}", defaultText=right)
for right in sorted(conf.user.access_rights)
},
multiple=True,
Expand Down Expand Up @@ -282,7 +282,7 @@ class LostPasswordStep2Skel(skeleton.RelSkel):
required=True,
params={
"tooltip": i18n.translate(
key="viur.modules.user.userpassword.lostpasswordstep2.recoverykey",
key="viur.core.modules.user.userpassword.lostpasswordstep2.recoverykey",
defaultText="Please enter the validation key you've received via e-mail.",
hint="Shown when the user needs more than 15 minutes to paste the key",
),
Expand All @@ -302,7 +302,7 @@ class LostPasswordStep3Skel(skeleton.RelSkel):
required=True,
params={
"tooltip": i18n.translate(
key="viur.modules.user.userpassword.lostpasswordstep3.password",
key="viur.core.modules.user.userpassword.lostpasswordstep3.password",
defaultText="Please enter a new password for your account.",
),
}
Expand Down Expand Up @@ -418,7 +418,7 @@ def pwrecover(self, recovery_key: str | None = None, skey: str | None = None, *a
if not (recovery_request := securitykey.validate(recovery_key, session_bound=False)):
raise errors.PreconditionFailed(
i18n.translate(
key="viur.modules.user.passwordrecovery.keyexpired",
key="viur.core.modules.user.passwordrecovery.keyexpired",
defaultText="The recovery key is expired or invalid. Please start the recovery process again.",
hint="Shown when the user needs more than 15 minutes to paste the key, or entered an invalid key."
)
Expand All @@ -432,7 +432,7 @@ def pwrecover(self, recovery_key: str | None = None, skey: str | None = None, *a
if not user_skel:
raise errors.NotFound(
i18n.translate(
key="viur.modules.user.passwordrecovery.usernotfound",
key="viur.core.modules.user.passwordrecovery.usernotfound",
defaultText="There is no account with this name",
hint="We cant find an account with that name (Should never happen)"
)
Expand All @@ -442,7 +442,7 @@ def pwrecover(self, recovery_key: str | None = None, skey: str | None = None, *a
if not self._user_module.is_active(user_skel):
raise errors.NotFound(
i18n.translate(
key="viur.modules.user.passwordrecovery.accountlocked",
key="viur.core.modules.user.passwordrecovery.accountlocked",
defaultText="This account is currently locked. You cannot change its password.",
hint="Attempted password recovery on a locked account"
)
Expand Down Expand Up @@ -799,7 +799,7 @@ def start(self):
return self._user_module.render.edit(
self.OtpSkel(),
params={
"name": i18n.translate(self.NAME),
"name": i18n.translate("viur.core.modules.user." + self.NAME),
"action_name": self.ACTION_NAME,
"action_url": f"{self.modulePath}/{self.ACTION_NAME}",
},
Expand Down Expand Up @@ -843,7 +843,7 @@ def otp(self, *args, **kwargs):
skel.errors = [ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Wrong OTP Token", ["otptoken"])]
return self._user_module.render.edit(
skel,
name=i18n.translate(self.NAME),
name=i18n.translate("viur.core.modules.user.auth." + self.NAME),
action_name=self.ACTION_NAME,
action_url=f"{self.modulePath}/{self.ACTION_NAME}",
tpl=self.second_factor_login_template
Expand Down Expand Up @@ -981,23 +981,23 @@ def add(self, otp=None):
return self._user_module.render.second_factor_add(
tpl=self.second_factor_add_template,
action_name=self.ACTION_NAME,
name=i18n.translate(self.NAME),
name=i18n.translate("viur.core.modules.user.auth." + self.NAME),
add_url=self.add_url,
otp_uri=AuthenticatorOTP.generate_otp_app_secret_uri(otp_app_secret))
else:
if not AuthenticatorOTP.verify_otp(otp, otp_app_secret):
return self._user_module.render.second_factor_add(
tpl=self.second_factor_add_template,
action_name=self.ACTION_NAME,
name=i18n.translate(self.NAME),
name=i18n.translate(("viur.core.modules.user.auth." + self.NAME),
add_url=self.add_url,
otp_uri=AuthenticatorOTP.generate_otp_app_secret_uri(otp_app_secret)) # to add errors

# Now we can set the otp_app_secret to the current User and render der Success-template
AuthenticatorOTP.set_otp_app_secret(otp_app_secret)
return self._user_module.render.second_factor_add_success(
action_name=self.ACTION_NAME,
name=i18n.translate(self.NAME),
name=i18n.translate(("viur.core.modules.user.auth." + self.NAME),
)

def can_handle(self, skel: skeleton.SkeletonInstance) -> bool:
Expand Down Expand Up @@ -1073,7 +1073,7 @@ def start(self):
return self._user_module.render.edit(
TimeBasedOTP.OtpSkel(),
params={
"name": i18n.translate(self.NAME),
"name": i18n.translate("viur.core.modules.user.auth." + self.NAME),
"action_name": self.ACTION_NAME,
"action_url": self.action_url,
},
Expand Down Expand Up @@ -1112,7 +1112,7 @@ def authenticator_otp(self, **kwargs):
skel.errors = [ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Wrong OTP Token", ["otptoken"])]
return self._user_module.render.edit(
skel,
name=i18n.translate(self.NAME),
name=i18n.translate("viur.core.modules.user.auth." + self.NAME),
action_name=self.ACTION_NAME,
action_url=self.action_url,
tpl=self.second_factor_login_template,
Expand Down Expand Up @@ -1188,7 +1188,7 @@ class User(List):
"customActions": {
"trigger_kick": {
"name": i18n.translate(
key="viur.modules.user.customActions.kick",
key="viur.core.modules.user.customActions.kick",
defaultText="Kick user",
hint="Title of the kick user function"
),
Expand All @@ -1197,17 +1197,17 @@ class User(List):
"action": "fetch",
"url": "/vi/{{module}}/trigger/kick/{{key}}?skey={{skey}}",
"confirm": i18n.translate(
key="viur.modules.user.customActions.kick.confirm",
key="viur.core.modules.user.customActions.kick.confirm",
defaultText="Do you really want to drop all sessions of the selected user from the system?",
),
"success": i18n.translate(
key="viur.modules.user.customActions.kick.success",
key="viur.core.modules.user.customActions.kick.success",
defaultText="Sessions of the user are being invalidated.",
),
},
"trigger_takeover": {
"name": i18n.translate(
key="viur.modules.user.customActions.takeover",
key="viur.core.modules.user.customActions.takeover",
defaultText="Take-over user",
hint="Title of the take user over function"
),
Expand All @@ -1216,12 +1216,12 @@ class User(List):
"action": "fetch",
"url": "/vi/{{module}}/trigger/takeover/{{key}}?skey={{skey}}",
"confirm": i18n.translate(
key="viur.modules.user.customActions.takeover.confirm",
key="viur.core.modules.user.customActions.takeover.confirm",
defaultText="Do you really want to replace your current user session by a "
"user session of the selected user?",
),
"success": i18n.translate(
key="viur.modules.user.customActions.takeover.success",
key="viur.core.modules.user.customActions.takeover.success",
defaultText="You're now know as the selected user!",
),
"then": "reload-vi",
Expand Down
Loading