diff --git a/Makefile b/Makefile index 07becb494..3d7a62c6c 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,8 @@ L10N_MODULES := \ services/activitylog \ services/graph \ services/notifications \ - services/userlog + services/userlog \ + services/settings # if you add a module here please also add it to the .drone.star file OCIS_MODULES = \ diff --git a/changelog/unreleased/notification-settings-translations.md b/changelog/unreleased/notification-settings-translations.md new file mode 100644 index 000000000..ef52a1568 --- /dev/null +++ b/changelog/unreleased/notification-settings-translations.md @@ -0,0 +1,5 @@ +Enhancement: Translate Notification Settings + +Translates the notification settings according to the users language preference. + +https://github.com/owncloud/ocis/pull/10812 diff --git a/docs/services/general-info/add-translations.md b/docs/services/general-info/add-translations.md index 46065f642..481302270 100644 --- a/docs/services/general-info/add-translations.md +++ b/docs/services/general-info/add-translations.md @@ -29,7 +29,13 @@ Translations have a `context` and a `translatable string`. The context is shown * Add the `OCIS_DEFAULT_LANGUAGE` envvar in `services//pkg/config/config.go`.\ For details see the userlog or notifications service code. -* Use `"github.com/owncloud/ocis/v2/ocis-pkg/l10n"` for the translation. +* Add the `_TRANSLATION_PATH` envvar in `services//pkg/config/config.go`.\ + For details see the userlog or notifications service code. + +* Use `"github.com/owncloud/ocis/v2/ocis-pkg/l10n"` for the translation.\ + Use `l10n.Template` to define the translation string.\ + Use `l10n.NewTranslator` or `l10n.NewTranslatorFromCommonConfig` to get the translator.\ + Use `t.Get` to translate the string. See package for more advanced usage. * Create a config in `services//pkg/service/l10n/.tx/config` with the following content. Note that it is important to stick with `ocis-` to easily identify all ocis translations on Transifex: ``` @@ -46,9 +52,11 @@ Translations have a `context` and a `translatable string`. The context is shown ``` Note: o: organization, p: project, r: resource -* Create a go file like `templates.go` in `ocis/services//pkg/service` that will define your translation sources like the following: +* Create an empty file `services//pkg/service/l10n/locale/en/LC_MESSAGES/.po`. This is required for ocis to build. This file will be replaced nightly with the latest translations from Transifex. + +* Create a go file like `templates.go` in e.g. `ocis/services//pkg/service` that will define your translation sources like the following: ``` - // context string + // this comment will appear in transifex as context var yourString = l10n.Template("Translation String") ``` @@ -85,7 +93,7 @@ Translations have a `context` and a `translatable string`. The context is shown l10n-read: $(GO_XGETTEXT) go-xgettext -o $(OUTPUT_DIR)/.pot \ --keyword=l10n.Template --add-comments -s \ - ocis/services//pkg/service/templates.go + pkg/service/templates.go .PHONY: l10n-write l10n-write: diff --git a/ocis-pkg/l10n/l10n.go b/ocis-pkg/l10n/l10n.go index 58680666f..0908c187f 100644 --- a/ocis-pkg/l10n/l10n.go +++ b/ocis-pkg/l10n/l10n.go @@ -11,7 +11,6 @@ import ( "github.com/leonelquinteros/gotext" "github.com/owncloud/ocis/v2/ocis-pkg/middleware" settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0" - "github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults" micrometadata "go-micro.dev/v4/metadata" ) @@ -140,7 +139,8 @@ func GetUserLocale(ctx context.Context, userID string, vc settingssvc.ValueServi micrometadata.Set(ctx, middleware.AccountID, userID), &settingssvc.GetValueByUniqueIdentifiersRequest{ AccountUuid: userID, - SettingId: defaults.SettingUUIDProfileLanguage, + // this defaults.SettingUUIDProfileLanguage. Copied here to avoid import cycles. + SettingId: "aa8cfbe5-95d4-4f7e-a032-c3c01f5f062f", }, ) if err != nil { diff --git a/protogen/proto/ocis/services/settings/v0/settings.proto b/protogen/proto/ocis/services/settings/v0/settings.proto index 19f4e4475..3cf50a960 100644 --- a/protogen/proto/ocis/services/settings/v0/settings.proto +++ b/protogen/proto/ocis/services/settings/v0/settings.proto @@ -168,6 +168,7 @@ message GetBundleResponse { message ListBundlesRequest { repeated string bundle_ids = 1; + string locale = 2; } message ListBundlesResponse { diff --git a/services/frontend/pkg/config/config.go b/services/frontend/pkg/config/config.go index 7eda98ef3..b4e3c721f 100644 --- a/services/frontend/pkg/config/config.go +++ b/services/frontend/pkg/config/config.go @@ -58,6 +58,8 @@ type Config struct { PasswordPolicy PasswordPolicy `yaml:"password_policy"` + ConfigurableNotifications bool `yaml:"configurable_notifications" env:"FRONTEND_CONFIGURABLE_NOTIFICATIONS" desc:"Allow configuring notifications via web client." introductionVersion:"7.1"` + Context context.Context `yaml:"-"` } diff --git a/services/frontend/pkg/revaconfig/config.go b/services/frontend/pkg/revaconfig/config.go index e58a93c25..3cd7ad87a 100644 --- a/services/frontend/pkg/revaconfig/config.go +++ b/services/frontend/pkg/revaconfig/config.go @@ -333,7 +333,8 @@ func FrontendConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string }, "password_policy": passwordPolicyCfg, "notifications": map[string]interface{}{ - "endpoints": []string{"list", "get", "delete"}, + "endpoints": []string{"list", "get", "delete"}, + "configurable": cfg.ConfigurableNotifications, }, }, "version": map[string]interface{}{ diff --git a/services/settings/Makefile b/services/settings/Makefile index f426f34a6..1d6046e35 100644 --- a/services/settings/Makefile +++ b/services/settings/Makefile @@ -1,6 +1,10 @@ SHELL := bash NAME := settings +# Where to write the files generated by this makefile. +OUTPUT_DIR = ./pkg/service/v0/l10n +TEMPLATE_FILE = ./pkg/service/v0/l10n/settings.pot + include ../../.make/recursion.mk ############ tooling ############ @@ -45,3 +49,25 @@ ci-node-check-licenses: .PHONY: ci-node-save-licenses ci-node-save-licenses: + +############ translations ######## +.PHONY: l10n-pull +l10n-pull: + cd $(OUTPUT_DIR) && tx pull --all --force --skip --minimum-perc=75 + +.PHONY: l10n-push +l10n-push: + cd $(OUTPUT_DIR) && tx push -s --skip + +.PHONY: l10n-read +l10n-read: $(GO_XGETTEXT) + go-xgettext -o $(OUTPUT_DIR)/settings.pot \ + --keyword=l10n.Template --add-comments -s \ + pkg/store/defaults/templates.go + +.PHONY: l10n-write +l10n-write: + +.PHONY: l10n-clean +l10n-clean: + rm -f $(TEMPLATE_FILE); diff --git a/services/settings/README.md b/services/settings/README.md index 122441ea1..621845a9b 100644 --- a/services/settings/README.md +++ b/services/settings/README.md @@ -64,6 +64,28 @@ Services can set or query Infinite Scale *setting values* of a user from setting The settings service needs to know the IDs of service accounts but it doesn't need their secrets. They can be configured using the `SETTINGS_SERVICE_ACCOUNTS_IDS` envvar. When only using one service account `OCIS_SERVICE_ACCOUNT_ID` can also be used. All configured service accounts will get a hidden 'service-account' role. This role contains all permissions the service account needs but will not appear calls to the list roles endpoint. It is not possible to assign the 'service-account' role to a normal user. +## Translations + +The `settings` service has embedded translations sourced via transifex to provide a basic set of translated languages. These embedded translations are available for all deployment scenarios. In addition, the service supports custom translations, though it is currently not possible to just add custom translations to embedded ones. If custom translations are configured, the embedded ones are not used. To configure custom translations, the `SETTINGS_TRANSLATION_PATH` environment variable needs to point to a base folder that will contain the translation files. This path must be available from all instances of the userlog service, a shared storage is recommended. Translation files must be of type [.po](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html#PO-Files) or [.mo](https://www.gnu.org/software/gettext/manual/html_node/Binaries.html). For each language, the filename needs to be `settings.po` (or `settings.mo`) and stored in a folder structure defining the language code. In general the path/name pattern for a translation file needs to be: + +```text +{SETTINGS_TRANSLATION_PATH}/{language-code}/LC_MESSAGES/settings.po +``` + +The language code pattern is composed of `language[_territory]` where `language` is the base language and `_territory` is optional and defines a country. + +For example, for the language `de`, one needs to place the corresponding translation files to `{SETTINGS_TRANSLATION_PATH}/de_DE/LC_MESSAGES/settings.po`. + + + +Important: For the time being, the embedded ownCloud Web frontend only supports the main language code but does not handle any territory. When strings are available in the language code `language_territory`, the web frontend does not see it as it only requests `language`. In consequence, any translations made must exist in the requested `language` to avoid a fallback to the default. + +### Translation Rules + +* If a requested language code is not available, the service tries to fall back to the base language if available. For example, if the requested language-code `de_DE` is not available, the service tries to fall back to translations in the `de` folder. +* If the base language `de` is also not available, the service falls back to the system's default English (`en`), +which is the source of the texts provided by the code. + ## Default Language The default language can be defined via the `OCIS_DEFAULT_LANGUAGE` environment variable. If this variable is not defined, English will be used as default. The value has the ISO 639-1 format ("de", "en", etc.) and is limited by the list supported languages. This setting can be used to set the default language for notification and invitation emails. diff --git a/services/settings/pkg/config/config.go b/services/settings/pkg/config/config.go index 6126e854e..a85f8eb16 100644 --- a/services/settings/pkg/config/config.go +++ b/services/settings/pkg/config/config.go @@ -38,6 +38,7 @@ type Config struct { ServiceAccountIDs []string `yaml:"service_account_ids" env:"SETTINGS_SERVICE_ACCOUNT_IDS;OCIS_SERVICE_ACCOUNT_ID" desc:"The list of all service account IDs. These will be assigned the hidden 'service-account' role. Note: When using 'OCIS_SERVICE_ACCOUNT_ID' this will contain only one value while 'SETTINGS_SERVICE_ACCOUNT_IDS' can have multiple. See the 'auth-service' service description for more details about service accounts." introductionVersion:"5.0"` DefaultLanguage string `yaml:"default_language" env:"OCIS_DEFAULT_LANGUAGE" desc:"The default language used by services and the WebUI. If not defined, English will be used as default. See the documentation for more details." introductionVersion:"5.0"` + TranslationPath string `yaml:"translation_path" env:"OCIS_TRANSLATION_PATH;SETTINGS_TRANSLATION_PATH" desc:"(optional) Set this to a path with custom translations to overwrite the builtin translations. Note that file and folder naming rules apply, see the documentation for more details." introductionVersion:"7.1"` Context context.Context `yaml:"-"` } diff --git a/services/settings/pkg/service/v0/l10n/.tx/config b/services/settings/pkg/service/v0/l10n/.tx/config new file mode 100644 index 000000000..e03a69ea2 --- /dev/null +++ b/services/settings/pkg/service/v0/l10n/.tx/config @@ -0,0 +1,10 @@ +[main] +host = https://www.transifex.com + +[o:owncloud-org:p:owncloud:r:ocis-settings] +file_filter = locale//LC_MESSAGES/settings.po +minimum_perc = 75 +resource_name = ocis-settings +source_file = settings.pot +source_lang = en +type = PO diff --git a/services/settings/pkg/service/v0/l10n/locale/en/LC_MESSAGES/settings.po b/services/settings/pkg/service/v0/l10n/locale/en/LC_MESSAGES/settings.po new file mode 100644 index 000000000..e69de29bb diff --git a/services/settings/pkg/service/v0/service.go b/services/settings/pkg/service/v0/service.go index 97ffea318..cc53fabda 100644 --- a/services/settings/pkg/service/v0/service.go +++ b/services/settings/pkg/service/v0/service.go @@ -2,13 +2,17 @@ package svc import ( "context" + "embed" "errors" "fmt" "strings" cs3permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1" rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + ctxpkg "github.com/cs3org/reva/v2/pkg/ctx" "github.com/cs3org/reva/v2/pkg/rgrpc/status" + "github.com/leonelquinteros/gotext" + "github.com/owncloud/ocis/v2/ocis-pkg/l10n" "github.com/owncloud/ocis/v2/ocis-pkg/log" "github.com/owncloud/ocis/v2/ocis-pkg/middleware" "github.com/owncloud/ocis/v2/ocis-pkg/roles" @@ -23,6 +27,11 @@ import ( "google.golang.org/protobuf/types/known/emptypb" ) +//go:embed l10n/locale +var _translationFS embed.FS + +var _domain = "settings" + // Service represents a service. type Service struct { id string @@ -46,14 +55,14 @@ func NewService(cfg *config.Config, logger log.Logger) settings.ServiceHandler { // CheckPermission implements the CS3 API Permssions service. // It's used to check if a subject (user or group) has a permission. func (g Service) CheckPermission(ctx context.Context, req *cs3permissions.CheckPermissionRequest) (*cs3permissions.CheckPermissionResponse, error) { - spec := req.SubjectRef.Spec + spec := req.GetSubjectRef().GetSpec() var accountID string switch ref := spec.(type) { case *cs3permissions.SubjectReference_UserId: - accountID = ref.UserId.OpaqueId + accountID = ref.UserId.GetOpaqueId() case *cs3permissions.SubjectReference_GroupId: - accountID = ref.GroupId.OpaqueId + accountID = ref.GroupId.GetOpaqueId() } assignments, err := g.manager.ListRoleAssignments(accountID) @@ -65,10 +74,10 @@ func (g Service) CheckPermission(ctx context.Context, req *cs3permissions.CheckP roleIDs := make([]string, 0, len(assignments)) for _, a := range assignments { - roleIDs = append(roleIDs, a.RoleId) + roleIDs = append(roleIDs, a.GetRoleId()) } - permission, err := g.manager.ReadPermissionByName(req.Permission, roleIDs) + permission, err := g.manager.ReadPermissionByName(req.GetPermission(), roleIDs) if err != nil { if !errors.Is(err, settings.ErrNotFound) { return &cs3permissions.CheckPermissionResponse{ @@ -94,15 +103,15 @@ func (g Service) CheckPermission(ctx context.Context, req *cs3permissions.CheckP // SaveBundle implements the BundleServiceHandler interface func (g Service) SaveBundle(ctx context.Context, req *settingssvc.SaveBundleRequest, res *settingssvc.SaveBundleResponse) error { - cleanUpResource(ctx, req.Bundle.Resource) - if err := g.checkStaticPermissionsByBundleType(ctx, req.Bundle.Type); err != nil { + cleanUpResource(ctx, req.GetBundle().GetResource()) + if err := g.checkStaticPermissionsByBundleType(ctx, req.GetBundle().GetType()); err != nil { return err } if validationError := validateSaveBundle(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - r, err := g.manager.WriteBundle(req.Bundle) + r, err := g.manager.WriteBundle(req.GetBundle()) if err != nil { return merrors.BadRequest(g.id, "%s", err) } @@ -115,13 +124,13 @@ func (g Service) GetBundle(ctx context.Context, req *settingssvc.GetBundleReques if validationError := validateGetBundle(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - bundle, err := g.manager.ReadBundle(req.BundleId) + bundle, err := g.manager.ReadBundle(req.GetBundleId()) if err != nil { return merrors.NotFound(g.id, "%s", err) } filteredBundle := g.getFilteredBundle(g.getRoleIDs(ctx), bundle) - if len(filteredBundle.Settings) == 0 { - err = fmt.Errorf("could not read bundle: %s", req.BundleId) + if len(filteredBundle.GetSettings()) == 0 { + err = fmt.Errorf("could not read bundle: %s", req.GetBundleId()) return merrors.NotFound(g.id, "%s", err) } res.Bundle = filteredBundle @@ -134,18 +143,29 @@ func (g Service) ListBundles(ctx context.Context, req *settingssvc.ListBundlesRe if validationError := validateListBundles(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - bundles, err := g.manager.ListBundles(settingsmsg.Bundle_TYPE_DEFAULT, req.BundleIds) + bundles, err := g.manager.ListBundles(settingsmsg.Bundle_TYPE_DEFAULT, req.GetBundleIds()) if err != nil { return merrors.NotFound(g.id, "%s", err) } roleIDs := g.getRoleIDs(ctx) + // find user locale + var locale string + if u, ok := ctxpkg.ContextGetUser(ctx); ok { + var err error + locale, err = g.getUserLocale(ctx, u.GetId().GetOpaqueId()) + if err != nil { + g.logger.Error().Err(err).Str("userid", u.GetId().GetOpaqueId()).Msg("failed to get user locale") + } + } + // filter settings in bundles that are allowed according to roles var filteredBundles []*settingsmsg.Bundle for _, bundle := range bundles { filteredBundle := g.getFilteredBundle(roleIDs, bundle) - if len(filteredBundle.Settings) > 0 { - filteredBundles = append(filteredBundles, filteredBundle) + if len(filteredBundle.GetSettings()) > 0 { + t := l10n.NewTranslatorFromCommonConfig(g.config.DefaultLanguage, _domain, g.config.TranslationPath, _translationFS, "l10n/locale").Locale(locale) + filteredBundles = append(filteredBundles, translateBundle(filteredBundle, t)) } } @@ -157,7 +177,7 @@ func (g Service) getFilteredBundle(roleIDs []string, bundle *settingsmsg.Bundle) // check if full bundle is whitelisted bundleResource := &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_BUNDLE, - Id: bundle.Id, + Id: bundle.GetId(), } if g.hasPermission( roleIDs, @@ -170,10 +190,10 @@ func (g Service) getFilteredBundle(roleIDs []string, bundle *settingsmsg.Bundle) // filter settings based on permissions var filteredSettings []*settingsmsg.Setting - for _, setting := range bundle.Settings { + for _, setting := range bundle.GetSettings() { settingResource := &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_SETTING, - Id: setting.Id, + Id: setting.GetId(), } if g.hasPermission( roleIDs, @@ -190,15 +210,15 @@ func (g Service) getFilteredBundle(roleIDs []string, bundle *settingsmsg.Bundle) // AddSettingToBundle implements the BundleServiceHandler interface func (g Service) AddSettingToBundle(ctx context.Context, req *settingssvc.AddSettingToBundleRequest, res *settingssvc.AddSettingToBundleResponse) error { - cleanUpResource(ctx, req.Setting.Resource) - if err := g.checkStaticPermissionsByBundleID(ctx, req.BundleId); err != nil { + cleanUpResource(ctx, req.GetSetting().GetResource()) + if err := g.checkStaticPermissionsByBundleID(ctx, req.GetBundleId()); err != nil { return err } if validationError := validateAddSettingToBundle(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - r, err := g.manager.AddSettingToBundle(req.BundleId, req.Setting) + r, err := g.manager.AddSettingToBundle(req.GetBundleId(), req.GetSetting()) if err != nil { return merrors.BadRequest(g.id, "%s", err) } @@ -208,14 +228,14 @@ func (g Service) AddSettingToBundle(ctx context.Context, req *settingssvc.AddSet // RemoveSettingFromBundle implements the BundleServiceHandler interface func (g Service) RemoveSettingFromBundle(ctx context.Context, req *settingssvc.RemoveSettingFromBundleRequest, _ *emptypb.Empty) error { - if err := g.checkStaticPermissionsByBundleID(ctx, req.BundleId); err != nil { + if err := g.checkStaticPermissionsByBundleID(ctx, req.GetBundleId()); err != nil { return err } if validationError := validateRemoveSettingFromBundle(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - if err := g.manager.RemoveSettingFromBundle(req.BundleId, req.SettingId); err != nil { + if err := g.manager.RemoveSettingFromBundle(req.GetBundleId(), req.GetSettingId()); err != nil { return merrors.BadRequest(g.id, "%s", err) } @@ -224,17 +244,17 @@ func (g Service) RemoveSettingFromBundle(ctx context.Context, req *settingssvc.R // SaveValue implements the ValueServiceHandler interface func (g Service) SaveValue(ctx context.Context, req *settingssvc.SaveValueRequest, res *settingssvc.SaveValueResponse) error { - req.Value.AccountUuid = getValidatedAccountUUID(ctx, req.Value.AccountUuid) - if !g.isCurrentUser(ctx, req.Value.AccountUuid) { + req.Value.AccountUuid = getValidatedAccountUUID(ctx, req.GetValue().GetAccountUuid()) + if !g.isCurrentUser(ctx, req.GetValue().GetAccountUuid()) { return merrors.Forbidden(g.id, "can't save value for another user") } - cleanUpResource(ctx, req.Value.Resource) + cleanUpResource(ctx, req.GetValue().GetResource()) // TODO: we need to check, if the authenticated user has permission to write the value for the specified resource (e.g. global, file with id xy, ...) if validationError := validateSaveValue(req); validationError != nil { return merrors.BadRequest(g.id, validationError.Error()) } - r, err := g.manager.WriteValue(req.Value) + r, err := g.manager.WriteValue(req.GetValue()) if err != nil { return merrors.BadRequest(g.id, err.Error()) } @@ -247,11 +267,11 @@ func (g Service) SaveValue(ctx context.Context, req *settingssvc.SaveValueReques } // GetValue implements the ValueServiceHandler interface -func (g Service) GetValue(ctx context.Context, req *settingssvc.GetValueRequest, res *settingssvc.GetValueResponse) error { +func (g Service) GetValue(_ context.Context, req *settingssvc.GetValueRequest, res *settingssvc.GetValueResponse) error { if validationError := validateGetValue(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - r, err := g.manager.ReadValue(req.Id) + r, err := g.manager.ReadValue(req.GetId()) if err != nil { return merrors.NotFound(g.id, "%s", err) } @@ -265,19 +285,19 @@ func (g Service) GetValue(ctx context.Context, req *settingssvc.GetValueRequest, // GetValueByUniqueIdentifiers implements the ValueService interface func (g Service) GetValueByUniqueIdentifiers(ctx context.Context, req *settingssvc.GetValueByUniqueIdentifiersRequest, res *settingssvc.GetValueResponse) error { - req.AccountUuid = getValidatedAccountUUID(ctx, req.AccountUuid) - if !g.isCurrentUser(ctx, req.AccountUuid) { + req.AccountUuid = getValidatedAccountUUID(ctx, req.GetAccountUuid()) + if !g.isCurrentUser(ctx, req.GetAccountUuid()) { return merrors.Forbidden(g.id, "can't get value of another user") } if validationError := validateGetValueByUniqueIdentifiers(req); validationError != nil { return merrors.BadRequest(g.id, validationError.Error()) } - v, err := g.manager.ReadValueByUniqueIdentifiers(req.AccountUuid, req.SettingId) + v, err := g.manager.ReadValueByUniqueIdentifiers(req.GetAccountUuid(), req.GetSettingId()) if err != nil { return merrors.NotFound(g.id, err.Error()) } - if v.BundleId != "" { + if v.GetBundleId() != "" { valueWithIdentifier, err := g.getValueWithIdentifier(v) if err != nil { return merrors.NotFound(g.id, err.Error()) @@ -290,15 +310,15 @@ func (g Service) GetValueByUniqueIdentifiers(ctx context.Context, req *settingss // ListValues implements the ValueServiceHandler interface func (g Service) ListValues(ctx context.Context, req *settingssvc.ListValuesRequest, res *settingssvc.ListValuesResponse) error { - req.AccountUuid = getValidatedAccountUUID(ctx, req.AccountUuid) - if !g.isCurrentUser(ctx, req.AccountUuid) { + req.AccountUuid = getValidatedAccountUUID(ctx, req.GetAccountUuid()) + if !g.isCurrentUser(ctx, req.GetAccountUuid()) { return merrors.Forbidden(g.id, "can't list values of another user") } if validationError := validateListValues(req); validationError != nil { return merrors.BadRequest(g.id, validationError.Error()) } - values, err := g.manager.ListValues(req.BundleId, req.AccountUuid) + values, err := g.manager.ListValues(req.GetBundleId(), req.GetAccountUuid()) if err != nil { return merrors.NotFound(g.id, err.Error()) } @@ -314,12 +334,12 @@ func (g Service) ListValues(ctx context.Context, req *settingssvc.ListValuesRequ } // ListRoles implements the RoleServiceHandler interface -func (g Service) ListRoles(c context.Context, req *settingssvc.ListBundlesRequest, res *settingssvc.ListBundlesResponse) error { +func (g Service) ListRoles(_ context.Context, req *settingssvc.ListBundlesRequest, res *settingssvc.ListBundlesResponse) error { //accountUUID := getValidatedAccountUUID(c, "me") if validationError := validateListRoles(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - r, err := g.manager.ListBundles(settingsmsg.Bundle_TYPE_ROLE, req.BundleIds) + r, err := g.manager.ListBundles(settingsmsg.Bundle_TYPE_ROLE, req.GetBundleIds()) if err != nil { return merrors.NotFound(g.id, "%s", err) } @@ -330,11 +350,11 @@ func (g Service) ListRoles(c context.Context, req *settingssvc.ListBundlesReques // ListRoleAssignments implements the RoleServiceHandler interface func (g Service) ListRoleAssignments(ctx context.Context, req *settingssvc.ListRoleAssignmentsRequest, res *settingssvc.ListRoleAssignmentsResponse) error { - req.AccountUuid = getValidatedAccountUUID(ctx, req.AccountUuid) + req.AccountUuid = getValidatedAccountUUID(ctx, req.GetAccountUuid()) if validationError := validateListRoleAssignments(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - r, err := g.manager.ListRoleAssignments(req.AccountUuid) + r, err := g.manager.ListRoleAssignments(req.GetAccountUuid()) if err != nil { return merrors.NotFound(g.id, "%s", err) } @@ -342,6 +362,7 @@ func (g Service) ListRoleAssignments(ctx context.Context, req *settingssvc.ListR return nil } +// ListRoleAssignmentsFiltered implements the RoleServiceHandler interface. Who made this up? And why is everyone copying it? So this methods lists role assignments filtered by account or role. func (g Service) ListRoleAssignmentsFiltered(ctx context.Context, req *settingssvc.ListRoleAssignmentsFilteredRequest, res *settingssvc.ListRoleAssignmentsResponse) error { if validationError := validateListRoleAssignmentsFiltered(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) @@ -367,7 +388,7 @@ func (g Service) ListRoleAssignmentsFiltered(ctx context.Context, req *settingss // AssignRoleToUser implements the RoleServiceHandler interface func (g Service) AssignRoleToUser(ctx context.Context, req *settingssvc.AssignRoleToUserRequest, res *settingssvc.AssignRoleToUserResponse) error { - req.AccountUuid = getValidatedAccountUUID(ctx, req.AccountUuid) + req.AccountUuid = getValidatedAccountUUID(ctx, req.GetAccountUuid()) if validationError := validateAssignRoleToUser(req); validationError != nil { return merrors.BadRequest(g.id, validationError.Error()) } @@ -379,13 +400,13 @@ func (g Service) AssignRoleToUser(ctx context.Context, req *settingssvc.AssignRo } switch { - case ownAccountUUID == req.AccountUuid: + case ownAccountUUID == req.GetAccountUuid(): // Allow users to assign themself to the user or user light role // deny any other attempt to change the user's own assignment - if r, err := g.manager.ListRoleAssignments(req.AccountUuid); err == nil && len(r) > 0 { + if r, err := g.manager.ListRoleAssignments(req.GetAccountUuid()); err == nil && len(r) > 0 { return merrors.Forbidden(g.id, "Changing own role assignment forbidden") } - if req.RoleId != defaults.BundleUUIDRoleUser && req.RoleId != defaults.BundleUUIDRoleUserLight { + if req.GetRoleId() != defaults.BundleUUIDRoleUser && req.GetRoleId() != defaults.BundleUUIDRoleUserLight { return merrors.Forbidden(g.id, "Changing own role assignment forbidden") } g.logger.Debug().Str("userid", ownAccountUUID).Msg("Self-assignment for default 'user' role permitted") @@ -394,7 +415,7 @@ func (g Service) AssignRoleToUser(ctx context.Context, req *settingssvc.AssignRo return merrors.Forbidden(g.id, "user has no role management permission") } - r, err := g.manager.WriteRoleAssignment(req.AccountUuid, req.RoleId) + r, err := g.manager.WriteRoleAssignment(req.GetAccountUuid(), req.GetRoleId()) if err != nil { return merrors.BadRequest(g.id, err.Error()) } @@ -425,13 +446,13 @@ func (g Service) RemoveRoleFromUser(ctx context.Context, req *settingssvc.Remove } for _, a := range al { - if a.Id == req.Id { + if a.GetId() == req.GetId() { g.logger.Debug().Str("id", g.id).Msg("Removing own role assignment forbidden") return merrors.Forbidden(g.id, "Removing own role assignment forbidden") } } - if err := g.manager.RemoveRoleAssignment(req.Id); err != nil { + if err := g.manager.RemoveRoleAssignment(req.GetId()); err != nil { return merrors.BadRequest(g.id, err.Error()) } return nil @@ -445,11 +466,11 @@ func (g Service) ListPermissions(ctx context.Context, req *settingssvc.ListPermi return merrors.InternalServerError(g.id, "user not in context") } - if ownAccountUUID != req.AccountUuid { - return merrors.NotFound(g.id, "user not found: %s", req.AccountUuid) + if ownAccountUUID != req.GetAccountUuid() { + return merrors.NotFound(g.id, "user not found: %s", req.GetAccountUuid()) } - assignments, err := g.manager.ListRoleAssignments(req.AccountUuid) + assignments, err := g.manager.ListRoleAssignments(req.GetAccountUuid()) if err != nil { return err } @@ -457,7 +478,7 @@ func (g Service) ListPermissions(ctx context.Context, req *settingssvc.ListPermi // deduplicate role ids roleIDs := map[string]struct{}{} for _, a := range assignments { - roleIDs[a.RoleId] = struct{}{} + roleIDs[a.GetRoleId()] = struct{}{} } // deduplicate permission names @@ -491,7 +512,7 @@ func (g Service) ListPermissionsByResource(ctx context.Context, req *settingssvc if validationError := validateListPermissionsByResource(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - permissions, err := g.manager.ListPermissionsByResource(req.Resource, g.getRoleIDs(ctx)) + permissions, err := g.manager.ListPermissionsByResource(req.GetResource(), g.getRoleIDs(ctx)) if err != nil { return merrors.BadRequest(g.id, "%s", err) } @@ -504,12 +525,12 @@ func (g Service) GetPermissionByID(ctx context.Context, req *settingssvc.GetPerm if validationError := validateGetPermissionByID(req); validationError != nil { return merrors.BadRequest(g.id, "%s", validationError) } - permission, err := g.manager.ReadPermissionByID(req.PermissionId, g.getRoleIDs(ctx)) + permission, err := g.manager.ReadPermissionByID(req.GetPermissionId(), g.getRoleIDs(ctx)) if err != nil { return merrors.BadRequest(g.id, "%s", err) } if permission == nil { - return merrors.NotFound(g.id, "%s", fmt.Errorf("permission %s not found in roles", req.PermissionId)) + return merrors.NotFound(g.id, "%s", fmt.Errorf("permission %s not found in roles", req.GetPermissionId())) } res.Permission = permission return nil @@ -517,8 +538,8 @@ func (g Service) GetPermissionByID(ctx context.Context, req *settingssvc.GetPerm // cleanUpResource makes sure that the account uuid of the authenticated user is injected if needed. func cleanUpResource(ctx context.Context, resource *settingsmsg.Resource) { - if resource != nil && resource.Type == settingsmsg.Resource_TYPE_USER { - resource.Id = getValidatedAccountUUID(ctx, resource.Id) + if resource != nil && resource.GetType() == settingsmsg.Resource_TYPE_USER { + resource.Id = getValidatedAccountUUID(ctx, resource.GetId()) } } @@ -551,7 +572,7 @@ func (g Service) getRoleIDs(ctx context.Context) []string { ownRoleIDs := make([]string, 0, len(assignments)) for _, a := range assignments { - ownRoleIDs = append(ownRoleIDs, a.RoleId) + ownRoleIDs = append(ownRoleIDs, a.GetRoleId()) } return ownRoleIDs } @@ -560,19 +581,19 @@ func (g Service) getRoleIDs(ctx context.Context) []string { } func (g Service) getValueWithIdentifier(value *settingsmsg.Value) (*settingsmsg.ValueWithIdentifier, error) { - bundle, err := g.manager.ReadBundle(value.BundleId) + bundle, err := g.manager.ReadBundle(value.GetBundleId()) if err != nil { return nil, err } - setting, err := g.manager.ReadSetting(value.SettingId) + setting, err := g.manager.ReadSetting(value.GetSettingId()) if err != nil { return nil, err } return &settingsmsg.ValueWithIdentifier{ Identifier: &settingsmsg.Identifier{ - Extension: bundle.Extension, - Bundle: bundle.Name, - Setting: setting.Name, + Extension: bundle.GetExtension(), + Bundle: bundle.GetName(), + Setting: setting.GetName(), }, Value: value, }, nil @@ -596,12 +617,12 @@ func (g Service) hasStaticPermission(ctx context.Context, permissionID string) b } // deduplicate roleids - uniqueRoleIds := make(map[string]struct{}) + uniqueRoleIDs := make(map[string]struct{}) for _, a := range assignments { - uniqueRoleIds[a.GetRoleId()] = struct{}{} + uniqueRoleIDs[a.GetRoleId()] = struct{}{} } - roleIDs = make([]string, 0, len(uniqueRoleIds)) - for a := range uniqueRoleIds { + roleIDs = make([]string, 0, len(uniqueRoleIDs)) + for a := range uniqueRoleIDs { roleIDs = append(roleIDs, a) } } @@ -614,7 +635,7 @@ func (g Service) checkStaticPermissionsByBundleID(ctx context.Context, bundleID if err != nil { return merrors.NotFound(g.id, "bundle not found: %s", err) } - return g.checkStaticPermissionsByBundleType(ctx, bundle.Type) + return g.checkStaticPermissionsByBundleType(ctx, bundle.GetType()) } func (g Service) checkStaticPermissionsByBundleType(ctx context.Context, bundleType settingsmsg.Bundle_Type) error { @@ -642,7 +663,58 @@ func (g Service) canManageRoles(ctx context.Context) bool { return g.hasStaticPermission(ctx, RoleManagementPermissionID) } +func (g Service) getUserLocale(ctx context.Context, userID string) (string, error) { + var resp settingssvc.GetValueResponse + err := g.GetValueByUniqueIdentifiers( + ctx, + &settingssvc.GetValueByUniqueIdentifiersRequest{ + AccountUuid: userID, + SettingId: defaults.SettingUUIDProfileLanguage, + }, + &resp, + ) + if err != nil { + return "", err + } + val := resp.GetValue().GetValue().GetListValue().GetValues() + if len(val) == 0 { + return "", errors.New("no language setting found") + } + return val[0].GetStringValue(), nil +} + func formatPermissionName(setting *settingsmsg.Setting) string { constraint := strings.TrimPrefix(setting.GetPermissionValue().GetConstraint().String(), "CONSTRAINT_") - return setting.Name + "." + strings.ToLower(constraint) + return setting.GetName() + "." + strings.ToLower(constraint) +} + +func translateBundle(bundle *settingsmsg.Bundle, t *gotext.Locale) *settingsmsg.Bundle { + for i, set := range bundle.GetSettings() { + switch set.GetId() { + default: + continue + case defaults.SettingUUIDProfileEmailSendingInterval: + // translate interval names ('Instant', 'Daily', 'Weekly', 'Never') + value := set.GetSingleChoiceValue() + for i, v := range value.GetOptions() { + value.Options[i].DisplayValue = t.Get(v.GetDisplayValue()) + } + set.Value = &settingsmsg.Setting_SingleChoiceValue{SingleChoiceValue: value} + fallthrough + case defaults.SettingUUIDProfileEventShareCreated, + defaults.SettingUUIDProfileEventShareRemoved, + defaults.SettingUUIDProfileEventShareExpired, + defaults.SettingUUIDProfileEventSpaceShared, + defaults.SettingUUIDProfileEventSpaceUnshared, + defaults.SettingUUIDProfileEventSpaceMembershipExpired, + defaults.SettingUUIDProfileEventSpaceDisabled, + defaults.SettingUUIDProfileEventSpaceDeleted: + // translate event names ('Share Received', 'Share Removed', ...) + set.DisplayName = t.Get(set.GetDisplayName()) + // translate event descriptions ('Notify me when I receive a share', ...) + set.Description = t.Get(set.GetDescription()) + bundle.Settings[i] = set + } + } + return bundle } diff --git a/services/settings/pkg/store/defaults/defaults.go b/services/settings/pkg/store/defaults/defaults.go index efc22008b..32a85bb68 100644 --- a/services/settings/pkg/store/defaults/defaults.go +++ b/services/settings/pkg/store/defaults/defaults.go @@ -282,8 +282,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEmailSendingInterval, Name: "email-sending-interval-options", - DisplayName: "Email Notifications options", - Description: "Email notifications options", + DisplayName: TemplateEmailSendingInterval, + Description: TemplateEmailSendingIntervalDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -292,8 +292,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventShareCreated, Name: "event-share-created-options", - DisplayName: "Share created", - Description: "Share created", + DisplayName: TemplateShareCreated, + Description: TemplateShareCreatedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -309,8 +309,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventShareRemoved, Name: "event-share-removed-options", - DisplayName: "Share removed", - Description: "Share removed", + DisplayName: TemplateShareRemoved, + Description: TemplateShareRemovedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -326,8 +326,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventShareExpired, Name: "event-share-expired-options", - DisplayName: "Share expired", - Description: "Share expired", + DisplayName: TemplateShareExpired, + Description: TemplateShareExpiredDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -343,8 +343,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventSpaceShared, Name: "event-space-shared-options", - DisplayName: "Space shared", - Description: "Space shared", + DisplayName: TemplateSpaceShared, + Description: TemplateSpaceSharedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -360,8 +360,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventSpaceUnshared, Name: "event-space-unshared-options", - DisplayName: "Space unshared", - Description: "Space unshared", + DisplayName: TemplateSpaceUnshared, + Description: TemplateSpaceUnsharedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -377,8 +377,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventSpaceMembershipExpired, Name: "event-space-membership-expired-options", - DisplayName: "Space membership expired", - Description: "Space membership expired", + DisplayName: TemplateSpaceMembershipExpired, + Description: TemplateSpaceMembershipExpiredDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -394,8 +394,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventSpaceDisabled, Name: "event-space-disabled-options", - DisplayName: "Space disabled", - Description: "Space disabled", + DisplayName: TemplateSpaceDisabled, + Description: TemplateSpaceDisabledDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -411,8 +411,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventSpaceDeleted, Name: "event-space-deleted-options", - DisplayName: "Space deleted", - Description: "Space deleted", + DisplayName: TemplateSpaceDeleted, + Description: TemplateSpaceDeletedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -428,8 +428,8 @@ func generateBundleProfileRequest() *settingsmsg.Bundle { { Id: SettingUUIDProfileEventPostprocessingStepFinished, Name: "event-postprocessing-step-finished-options", - DisplayName: "Postprocessing Step Finished", - Description: "Postprocessing Step Finished", + DisplayName: TemplateFileRejected, + Description: TemplateFileRejectedDescription, Resource: &settingsmsg.Resource{ Type: settingsmsg.Resource_TYPE_USER, }, @@ -455,7 +455,7 @@ var sendEmailOptions = settingsmsg.Setting_SingleChoiceValue{ StringValue: "instant", }, }, - DisplayValue: "Instant", + DisplayValue: TemplateIntervalInstant, Default: true, }, { @@ -464,7 +464,7 @@ var sendEmailOptions = settingsmsg.Setting_SingleChoiceValue{ StringValue: "daily", }, }, - DisplayValue: "Daily", + DisplayValue: TemplateIntervalDaily, }, { Value: &settingsmsg.ListOptionValue{ @@ -472,7 +472,7 @@ var sendEmailOptions = settingsmsg.Setting_SingleChoiceValue{ StringValue: "weekly", }, }, - DisplayValue: "Weekly", + DisplayValue: TemplateIntervalWeekly, }, { Value: &settingsmsg.ListOptionValue{ @@ -480,7 +480,7 @@ var sendEmailOptions = settingsmsg.Setting_SingleChoiceValue{ StringValue: "never", }, }, - DisplayValue: "Never", + DisplayValue: TemplateIntervalNever, }, }, }, diff --git a/services/settings/pkg/store/defaults/templates.go b/services/settings/pkg/store/defaults/templates.go new file mode 100644 index 000000000..0158fe91e --- /dev/null +++ b/services/settings/pkg/store/defaults/templates.go @@ -0,0 +1,55 @@ +package defaults + +import "github.com/owncloud/ocis/v2/ocis-pkg/l10n" + +// Translatable configuration options +var ( + // name of the notification option 'Share Received' + TemplateShareCreated = l10n.Template("Share Received") + // description of the notification option 'Share Received' + TemplateShareCreatedDescription = l10n.Template("Notify me when I receive a share") + // name of the notification option 'Share Removed' + TemplateShareRemoved = l10n.Template("Share Removed") + // description of the notification option 'Share Removed' + TemplateShareRemovedDescription = l10n.Template("Notify me when my shares are removed") + // name of the notification option 'Share Expired' + TemplateShareExpired = l10n.Template("Share Expired") + // description of the notification option 'Share Expired' + TemplateShareExpiredDescription = l10n.Template("Notify me when my shares expire") + // name of the notification option 'Space Shared' + TemplateSpaceShared = l10n.Template("Added as space member") + // description of the notification option 'Space Shared' + TemplateSpaceSharedDescription = l10n.Template("Notify me when I am added as a member to a space") + // name of the notification option 'Space Unshared' + TemplateSpaceUnshared = l10n.Template("Removed as space member") + // description of the notification option 'Space Unshared' + TemplateSpaceUnsharedDescription = l10n.Template("Notify me when I am removed as a member from a space") + // name of the notification option 'Space Membership Expired' + TemplateSpaceMembershipExpired = l10n.Template("Space membership expired") + // description of the notification option 'Space Membership Expired' + TemplateSpaceMembershipExpiredDescription = l10n.Template("Notify me when my membership of a space expires") + // name of the notification option 'Space Disabled' + TemplateSpaceDisabled = l10n.Template("Space disabled") + // description of the notification option 'Space Disabled' + TemplateSpaceDisabledDescription = l10n.Template("Notify me when a space I am a member of is disabled") + // name of the notification option 'Space Deleted' + TemplateSpaceDeleted = l10n.Template("Space deleted") + // description of the notification option 'Space Deleted' + TemplateSpaceDeletedDescription = l10n.Template("Notify me when a space I am a member of is deleted") + // name of the notification option 'File Rejected' + TemplateFileRejected = l10n.Template("File rejected") + // description of the notification option 'File Rejected' + TemplateFileRejectedDescription = l10n.Template("Notify me when a file I uploaded is rejected because of virus infection or policy violation") + // name of the notification option 'Email Interval' + TemplateEmailSendingInterval = l10n.Template("Email sending interval") + // description of the notification option 'Email Interval' + TemplateEmailSendingIntervalDescription = l10n.Template("Notifiy me via email:") + // translation for the 'instant' email interval option + TemplateIntervalInstant = l10n.Template("Instant") + // translation for the 'daily' email interval option + TemplateIntervalDaily = l10n.Template("Daily") + // translation for the 'weekly' email interval option + TemplateIntervalWeekly = l10n.Template("Weekly") + // translation for the 'never' email interval option + TemplateIntervalNever = l10n.Template("Never") +)