diff --git a/README.md b/README.md index 820c4b5..50ca692 100644 --- a/README.md +++ b/README.md @@ -219,12 +219,27 @@ conflict strategy **Abort import** still aborts on existing objects. - Encrypted credentials of NetBox-VM-Import are only usable with an identical Django `SECRET_KEY`; otherwise set the password again on the target. +### Language + +The plugin is available in English (source) and German. Switch the display +language as usual in the user profile (**Preferences → Language**); import +reports and error messages follow it. Translations live in +`netbox_export/locale/de/LC_MESSAGES/`. + ## Development and tests ```bash python -m pytest ``` +After changing user-visible strings, update and compile the German catalogue: + +```bash +cd netbox_export +django-admin makemessages -l de --no-location +msgfmt -o locale/de/LC_MESSAGES/django.mo locale/de/LC_MESSAGES/django.po +``` + ## License Apache License 2.0 — see [LICENSE](LICENSE). diff --git a/netbox_export/forms.py b/netbox_export/forms.py index 7a89d6d..e34a727 100644 --- a/netbox_export/forms.py +++ b/netbox_export/forms.py @@ -1,26 +1,27 @@ from dcim.models import Location, Region, Site from django import forms +from django.utils.translation import gettext_lazy as _ from tenancy.models import Tenant, TenantGroup class ExportForm(forms.Form): scope_type = forms.ChoiceField( - label="Exportbereich", + label=_("Export scope"), choices=( - ("tenant_group", "Mandantengruppe"), - ("tenant", "Mandant"), - ("region", "Region"), - ("site", "Standort"), - ("location", "Lokation"), + ("tenant_group", _("Tenant group")), + ("tenant", _("Tenant")), + ("region", _("Region")), + ("site", _("Site")), + ("location", _("Location")), ), ) tenant_group = forms.ModelChoiceField( - label="Mandantengruppe", queryset=TenantGroup.objects.all(), required=False + label=_("Tenant group"), queryset=TenantGroup.objects.all(), required=False ) - tenant = forms.ModelChoiceField(label="Mandant", queryset=Tenant.objects.all(), required=False) - region = forms.ModelChoiceField(label="Region", queryset=Region.objects.all(), required=False) - site = forms.ModelChoiceField(label="Standort", queryset=Site.objects.all(), required=False) - location = forms.ModelChoiceField(label="Lokation", queryset=Location.objects.all(), required=False) + tenant = forms.ModelChoiceField(label=_("Tenant"), queryset=Tenant.objects.all(), required=False) + region = forms.ModelChoiceField(label=_("Region"), queryset=Region.objects.all(), required=False) + site = forms.ModelChoiceField(label=_("Site"), queryset=Site.objects.all(), required=False) + location = forms.ModelChoiceField(label=_("Location"), queryset=Location.objects.all(), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -32,47 +33,47 @@ class ExportForm(forms.Form): scope_type = cleaned.get("scope_type") selected = cleaned.get(scope_type) if scope_type else None if scope_type and selected is None: - self.add_error(scope_type, "Bitte ein Objekt für den Exportbereich auswählen.") + self.add_error(scope_type, _("Select an object for the export scope.")) cleaned["scope_object"] = selected return cleaned class ImportForm(forms.Form): archive = forms.FileField( - label="NetBox-Export-Archiv", + label=_("NetBox-Export archive"), widget=forms.ClearableFileInput(attrs={"accept": ".zip,application/zip"}), ) conflict_strategy = forms.ChoiceField( - label="Vorhandene Objekte", + label=_("Existing objects"), choices=( - ("update", "Aktualisieren"), - ("skip", "Überspringen"), - ("fail", "Import abbrechen"), + ("update", _("Update")), + ("skip", _("Skip")), + ("fail", _("Abort import")), ), initial="update", ) dry_run = forms.BooleanField( - label="Nur prüfen (keine Änderungen)", + label=_("Check only (no changes)"), required=False, initial=True, - help_text="Führt den vollständigen Import aus und setzt die Datenbanktransaktion anschließend zurück.", + help_text=_("Runs the complete import and then rolls back the database transaction."), ) force = forms.BooleanField( - label="Force-Modus (Fehler überspringen)", + label=_("Force mode (skip errors)"), required=False, initial=False, - help_text=( - "Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den gesamten Import " - "zurückzurollen. Übersprungene Objekte werden im Bericht als Warnung aufgeführt." + help_text=_( + "Objects that fail to import are skipped individually instead of rolling back the whole import. " + "Skipped objects are listed as warnings in the report." ), ) confirm_apply = forms.BooleanField( - label="Ich bestätige den schreibenden Import", + label=_("I confirm the writing import"), required=False, ) def clean(self): cleaned = super().clean() if not cleaned.get("dry_run") and not cleaned.get("confirm_apply"): - self.add_error("confirm_apply", "Für einen schreibenden Import ist die Bestätigung erforderlich.") + self.add_error("confirm_apply", _("Confirmation is required for a writing import.")) return cleaned diff --git a/netbox_export/locale/de/LC_MESSAGES/django.mo b/netbox_export/locale/de/LC_MESSAGES/django.mo new file mode 100644 index 0000000..211d600 Binary files /dev/null and b/netbox_export/locale/de/LC_MESSAGES/django.mo differ diff --git a/netbox_export/locale/de/LC_MESSAGES/django.po b/netbox_export/locale/de/LC_MESSAGES/django.po new file mode 100644 index 0000000..f5d3218 --- /dev/null +++ b/netbox_export/locale/de/LC_MESSAGES/django.po @@ -0,0 +1,428 @@ +msgid "" +msgstr "" +"Project-Id-Version: netbox-export\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-10-26 21:17+0100\n" +"PO-Revision-Date: 2026-10-26 21:20+0100\n" +"Language-Team: German\n" +"Language: de\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +msgid "Export scope" +msgstr "Exportbereich" + +msgid "Tenant group" +msgstr "Mandantengruppe" + +msgid "Tenant" +msgstr "Mandant" + +msgid "Region" +msgstr "Region" + +msgid "Site" +msgstr "Standort" + +msgid "Location" +msgstr "Lokation" + +msgid "Select an object for the export scope." +msgstr "Bitte ein Objekt für den Exportbereich auswählen." + +msgid "NetBox-Export archive" +msgstr "NetBox-Export-Archiv" + +msgid "Existing objects" +msgstr "Vorhandene Objekte" + +msgid "Update" +msgstr "Aktualisieren" + +msgid "Skip" +msgstr "Überspringen" + +msgid "Abort import" +msgstr "Import abbrechen" + +msgid "Check only (no changes)" +msgstr "Nur prüfen (keine Änderungen)" + +msgid "Runs the complete import and then rolls back the database transaction." +msgstr "" +"Führt den vollständigen Import aus und setzt die Datenbanktransaktion " +"anschließend zurück." + +msgid "Force mode (skip errors)" +msgstr "Force-Modus (Fehler überspringen)" + +msgid "" +"Objects that fail to import are skipped individually instead of rolling back " +"the whole import. Skipped objects are listed as warnings in the report." +msgstr "" +"Objekte, deren Import fehlschlägt, werden einzeln übersprungen, statt den " +"gesamten Import zurückzurollen. Übersprungene Objekte werden im Bericht als " +"Warnung aufgeführt." + +msgid "I confirm the writing import" +msgstr "Ich bestätige den schreibenden Import" + +msgid "Confirmation is required for a writing import." +msgstr "Für einen schreibenden Import ist die Bestätigung erforderlich." + +msgid "Export / Import" +msgstr "Export / Import" + +#, python-format +msgid "Duplicate file path in archive: %(path)s" +msgstr "Doppelter Dateipfad im Archiv: %(path)s" + +#, python-format +msgid "Unsafe file path in archive: %(path)s" +msgstr "Unsicherer Dateipfad im Archiv: %(path)s" + +msgid "The archive exceeds the configured maximum size." +msgstr "Das Archiv überschreitet die konfigurierte Maximalgröße." + +msgid "The uploaded file is not a valid ZIP archive." +msgstr "Die hochgeladene Datei ist kein gültiges ZIP-Archiv." + +msgid "The archive contains too many files." +msgstr "Das Archiv enthält zu viele Dateien." + +msgid "manifest.json or objects.ndjson is missing from the archive." +msgstr "manifest.json oder objects.ndjson fehlt im Archiv." + +msgid "The extracted archive content is too large." +msgstr "Der entpackte Archivinhalt ist zu groß." + +msgid "The archive has an impermissible compression ratio." +msgstr "Das Archiv weist ein unzulässiges Kompressionsverhältnis auf." + +msgid "The archive metadata is invalid." +msgstr "Die Metadaten im Archiv sind ungültig." + +msgid "The archive format or its version is not supported." +msgstr "Das Archivformat oder dessen Version wird nicht unterstützt." + +msgid "The object file does not match its checksum." +msgstr "Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein." + +msgid "The archive signature is invalid or missing." +msgstr "Die Archivsignatur ist ungültig oder fehlt." + +msgid "" +"The archive is signed but was not verified because no key is configured." +msgstr "" +"Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht " +"verifiziert." + +msgid "The archive is not signed." +msgstr "Das Archiv ist nicht signiert." + +msgid "The archive contains too many objects." +msgstr "Das Archiv enthält zu viele Objekte." + +msgid "objects.ndjson contains invalid JSON." +msgstr "objects.ndjson enthält ungültiges JSON." + +msgid "The file list does not match the manifest." +msgstr "Die Dateiliste stimmt nicht mit dem Manifest überein." + +#, python-format +msgid "The checksum of file %(name)s is invalid." +msgstr "Die Prüfsumme der Datei %(name)s ist ungültig." + +msgid "The object count does not match the manifest." +msgstr "Die Objektanzahl stimmt nicht mit dem Manifest überein." + +#, python-format +msgid "" +"The export would contain more than %(max)s objects. Narrow the scope or " +"increase max_objects." +msgstr "" +"Der Export würde mehr als %(max)s Objekte enthalten. Bitte den Bereich " +"verkleinern oder max_objects erhöhen." + +#, python-format +msgid "The model %(model)s is not installed on the target instance." +msgstr "Das Modell %(model)s ist auf der Zielinstanz nicht installiert." + +#, python-format +msgid "" +"Stored mapping for %(record)s was corrected from target ID %(old)s to target " +"ID %(new)s because the natural key %(key)s already exists." +msgstr "" +"Gespeicherte Zuordnung für %(record)s wurde von Ziel-ID %(old)s auf Ziel-ID " +"%(new)s korrigiert, da der Fachschlüssel %(key)s bereits existiert." + +#, python-format +msgid "Rack reference for %(record)s could not be resolved." +msgstr "Rack-Referenz für %(record)s konnte nicht aufgelöst werden." + +#, python-format +msgid "Rack position for %(record)s was omitted because no rack is assigned." +msgstr "" +"Rackplatz für %(record)s wurde ausgelassen, da kein Rack zugeordnet ist." + +#, python-format +msgid "" +"Rack position conflict for %(record)s: %(target)s is occupied by target " +"device(s) %(occupants)s." +msgstr "" +"Rackplatzkonflikt für %(record)s: %(target)s ist durch Zielgerät(e) " +"%(occupants)s belegt." + +#, python-format +msgid "" +"Rack position for %(record)s was skipped: %(target)s remains occupied by " +"target device(s) %(occupants)s. The imported device was saved without a rack " +"position." +msgstr "" +"Rackplatz für %(record)s wurde übersprungen: %(target)s bleibt durch " +"Zielgerät(e) %(occupants)s belegt. Das importierte Gerät wurde ohne Position" +" im Rack gespeichert." + +#, python-format +msgid "" +"Rack position conflict for %(record)s resolved: target device(s) " +"%(occupants)s were removed from %(target)s and left without a rack position." +msgstr "" +"Rackplatzkonflikt für %(record)s gelöst: Zielgerät(e) %(occupants)s wurden " +"aus %(target)s gelöst und ohne Position im Rack belassen." + +#, python-format +msgid "" +"Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port " +"cabling matches the source." +msgstr "" +"Portzuordnung(en) %(ids)s wurden durch %(record)s ersetzt, damit die " +"Front-/Rear-Port-Verkabelung der Quelle entspricht." + +#, python-format +msgid "The image exceeds the safe import limit of %(max)s pixels." +msgstr "Das Bild überschreitet die sichere Importgrenze von %(max)s Pixeln." + +#, python-format +msgid "" +"The image with %(pixels)s pixels exceeds the safe import limit of %(max)s " +"pixels." +msgstr "" +"Das Bild mit %(pixels)s Pixeln überschreitet die sichere Importgrenze von " +"%(max)s Pixeln." + +#, python-format +msgid "Image for %(record)s was downscaled from %(old)s to %(new)s pixels." +msgstr "Bild für %(record)s wurde von %(old)s auf %(new)s Pixel verkleinert." + +#, python-format +msgid "M2M reference for %(record)s could not be resolved." +msgstr "M2M-Referenz für %(record)s konnte nicht aufgelöst werden." + +#, python-format +msgid "Force mode: %(label)s was skipped because of an error: %(error)s" +msgstr "" +"Force-Modus: %(label)s wurde wegen eines Fehlers übersprungen: %(error)s" + +#, python-format +msgid "" +"Objects of type %(model)s were skipped because the related optional plugin " +"is not installed on the target instance." +msgstr "" +"Objekte vom Typ %(model)s wurden übersprungen, da das zugehörige optionale " +"Plugin auf der Zielinstanz nicht installiert ist." + +msgid "Unknown conflict strategy." +msgstr "Unbekannte Konfliktstrategie." + +#, python-format +msgid "" +"NetBox versions are not compatible: source %(source)s, target %(target)s." +msgstr "" +"NetBox-Versionen sind nicht kompatibel: Quelle %(source)s, Ziel %(target)s." + +msgid "The source instance ID is missing or invalid." +msgstr "Die Quellinstanz-Kennung fehlt oder ist ungültig." + +msgid "An object record is incomplete." +msgstr "Ein Objektdatensatz ist unvollständig." + +#, python-format +msgid "Duplicate object ID in archive: %(record)s" +msgstr "Doppelte Objekt-ID im Archiv: %(record)s" + +#, python-format +msgid "Target object already exists: %(record)s" +msgstr "Zielobjekt existiert bereits: %(record)s" + +#, python-format +msgid "" +"Force mode: %(count)s object(s) with unresolvable references were skipped: " +"%(blocked)s" +msgstr "" +"Force-Modus: %(count)s Objekt(e) mit nicht auflösbaren Referenzen wurden " +"übersprungen: %(blocked)s" + +#, python-format +msgid "Required references could not be resolved: %(blocked)s" +msgstr "Erforderliche Referenzen konnten nicht aufgelöst werden: %(blocked)s" + +#, python-format +msgid "Reference %(name)s for %(record)s could not be resolved." +msgstr "Referenz %(name)s für %(record)s konnte nicht aufgelöst werden." + +#, python-format +msgid "Reference %(name)s for %(record)s" +msgstr "Referenz %(name)s für %(record)s" + +#, python-format +msgid "Generic reference %(name)s for %(record)s is missing." +msgstr "Generische Referenz %(name)s für %(record)s fehlt." + +#, python-format +msgid "Generic reference %(name)s for %(record)s" +msgstr "Generische Referenz %(name)s für %(record)s" + +#, python-format +msgid "Custom field reference %(name)s for %(record)s is missing." +msgstr "Custom-Field-Referenz %(name)s für %(record)s fehlt." + +#, python-format +msgid "Custom field value %(name)s for %(record)s" +msgstr "Custom-Field-Wert %(name)s für %(record)s" + +msgid "Rack placement of devices" +msgstr "Rackplatzierung der Geräte" + +#, python-format +msgid "Many-to-many assignments for %(record)s" +msgstr "Mehrfachzuordnungen für %(record)s" + +msgid "Recalculation of cable paths" +msgstr "Neuberechnung der Kabelpfade" + +#, python-format +msgid "The import was rolled back: %(error)s" +msgstr "Der Import wurde zurückgerollt: %(error)s" + +msgid "" +"The tenant \"Auto-Import\" was used automatically as a fallback tenant for " +"the dry run; it is not created or changed permanently." +msgstr "" +"Für den Prüflauf wurde der Mandant \"Auto-Import\" automatisch als " +"Ersatzmandant verwendet; er wird nicht dauerhaft angelegt oder geändert." + +msgid "" +"The tenant \"Auto-Import\" was created automatically and assigned to objects " +"without a resolvable tenant." +msgstr "" +"Der Mandant \"Auto-Import\" wurde automatisch erstellt und Objekten ohne " +"auflösbaren Mandanten zugewiesen." + +msgid "" +"The existing tenant \"Auto-Import\" was selected automatically for objects " +"without a resolvable tenant." +msgstr "" +"Der vorhandene Mandant \"Auto-Import\" wurde automatisch für Objekte ohne " +"auflösbaren Mandanten ausgewählt." + +#, python-format +msgid "" +"Unique reference %(field)s was released from target object(s) %(ids)s and " +"reassigned to the imported object." +msgstr "" +"Eindeutige Referenz %(field)s wurde von Zielobjekt(en) %(ids)s gelöst und " +"dem importierten Objekt neu zugeordnet." + +#, python-format +msgid "" +"%(record)s (%(model)s) was skipped because of a missing required reference: " +"%(fields)s." +msgstr "" +"%(record)s (%(model)s) wurde wegen fehlender Pflichtreferenz übersprungen: " +"%(fields)s." + +msgid "not found" +msgstr "nicht gefunden" + +msgid "not unique" +msgstr "nicht eindeutig" + +#, python-format +msgid "External reference omitted: %(model)s with %(lookup)s (%(reason)s)." +msgstr "Externe Referenz ausgelassen: %(model)s mit %(lookup)s (%(reason)s)." + +#, python-format +msgid "References to the skipped object %(record)s were omitted." +msgstr "Referenzen auf das übersprungene Objekt %(record)s wurden ausgelassen." + +msgid "An object reference in the archive is invalid." +msgstr "Eine Objektreferenz im Archiv ist ungültig." + +msgid "Dry run successful" +msgstr "Prüflauf erfolgreich" + +msgid "Import completed" +msgstr "Import abgeschlossen" + +#, python-format +msgid "%(created)s created, %(updated)s updated, %(skipped)s skipped." +msgstr "" +"%(created)s erstellt, %(updated)s aktualisiert, %(skipped)s übersprungen." + +#, python-format +msgid "Source: %(label)s (%(count)s objects)." +msgstr "Quelle: %(label)s (%(count)s Objekte)." + +msgid "Model" +msgstr "Modell" + +msgid "Created" +msgstr "Erstellt" + +msgid "Updated" +msgstr "Aktualisiert" + +msgid "Skipped" +msgstr "Übersprungen" + +msgid "Export" +msgstr "Export" + +msgid "Preparing export ..." +msgstr "Export wird vorbereitet ..." + +msgid "Export progress" +msgstr "Exportfortschritt" + +msgid "Export ZIP" +msgstr "ZIP exportieren" + +msgid "Import" +msgstr "Import" + +msgid "Uploading archive ..." +msgstr "Archiv wird hochgeladen ..." + +msgid "Import progress" +msgstr "Importfortschritt" + +msgid "Process archive" +msgstr "Archiv verarbeiten" + +msgid "Transferring ZIP ..." +msgstr "ZIP wird übertragen ..." + +msgid "Export completed" +msgstr "Export abgeschlossen" + +msgid "Export failed" +msgstr "Export fehlgeschlagen" + +msgid "Checking and processing archive ..." +msgstr "Archiv wird geprüft und verarbeitet ..." + +msgid "Import failed" +msgstr "Import fehlgeschlagen" diff --git a/netbox_export/navigation.py b/netbox_export/navigation.py index a2c8991..4fbccd0 100644 --- a/netbox_export/navigation.py +++ b/netbox_export/navigation.py @@ -1,9 +1,10 @@ +from django.utils.translation import gettext_lazy as _ from netbox.plugins import PluginMenuItem menu_items = ( PluginMenuItem( link="plugins:netbox_export:dashboard", - link_text="Export / Import", + link_text=_("Export / Import"), staff_only=True, ), ) diff --git a/netbox_export/services/archive.py b/netbox_export/services/archive.py index d69c461..1c0b6ba 100644 --- a/netbox_export/services/archive.py +++ b/netbox_export/services/archive.py @@ -12,6 +12,7 @@ from pathlib import PurePosixPath from typing import BinaryIO from django.core.serializers.json import DjangoJSONEncoder +from django.utils.translation import gettext as _ from .exceptions import ArchiveValidationError @@ -54,7 +55,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt for path, content in assets.items(): safe_path = _safe_member_name(path) if safe_path in normalized_assets: - raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {safe_path}") + raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": safe_path}) normalized_assets[safe_path] = content assets = normalized_assets object_data = b"\n".join(_json_bytes(record) for record in records) + b"\n" @@ -94,7 +95,7 @@ def build_archive(manifest: dict, records: Iterable[dict], assets: dict[str, byt def _safe_member_name(name: str) -> str: normalized = posixpath.normpath(name.replace("\\", "/")) if normalized.startswith(("../", "/")) or normalized in ("", ".", ".."): - raise ArchiveValidationError(f"Unsicherer Dateipfad im Archiv: {name}") + raise ArchiveValidationError(_("Unsafe file path in archive: %(path)s") % {"path": name}) return normalized @@ -118,52 +119,52 @@ def read_archive( else: raw = source.read(max_size + 1) if len(raw) > max_size: - raise ArchiveValidationError("Das Archiv überschreitet die konfigurierte Maximalgröße.") + raise ArchiveValidationError(_("The archive exceeds the configured maximum size.")) try: archive = zipfile.ZipFile(io.BytesIO(raw)) except zipfile.BadZipFile as exc: - raise ArchiveValidationError("Die hochgeladene Datei ist kein gültiges ZIP-Archiv.") from exc + raise ArchiveValidationError(_("The uploaded file is not a valid ZIP archive.")) from exc with archive: names = {} for info in archive.infolist(): name = _safe_member_name(info.filename) if name in names: - raise ArchiveValidationError(f"Doppelter Dateipfad im Archiv: {name}") + raise ArchiveValidationError(_("Duplicate file path in archive: %(path)s") % {"path": name}) names[name] = info if len(names) > max_objects * 5 + 2: - raise ArchiveValidationError("Das Archiv enthält zu viele Dateien.") + raise ArchiveValidationError(_("The archive contains too many files.")) if MANIFEST_NAME not in names or OBJECTS_NAME not in names: - raise ArchiveValidationError("manifest.json oder objects.ndjson fehlt im Archiv.") + raise ArchiveValidationError(_("manifest.json or objects.ndjson is missing from the archive.")) total_size = sum(info.file_size for info in names.values()) if total_size > max_size * 4: - raise ArchiveValidationError("Der entpackte Archivinhalt ist zu groß.") + raise ArchiveValidationError(_("The extracted archive content is too large.")) if any(info.file_size > 0 and info.compress_size * 200 < info.file_size for info in names.values()): - raise ArchiveValidationError("Das Archiv weist ein unzulässiges Kompressionsverhältnis auf.") + raise ArchiveValidationError(_("The archive has an impermissible compression ratio.")) try: manifest = json.loads(archive.read(MANIFEST_NAME)) object_data = archive.read(OBJECTS_NAME) except (KeyError, ValueError, UnicodeDecodeError) as exc: - raise ArchiveValidationError("Die Metadaten im Archiv sind ungültig.") from exc + raise ArchiveValidationError(_("The archive metadata is invalid.")) from exc if manifest.get("format") != FORMAT_NAME or manifest.get("format_version") != FORMAT_VERSION: - raise ArchiveValidationError("Das Archivformat oder dessen Version wird nicht unterstützt.") + raise ArchiveValidationError(_("The archive format or its version is not supported.")) checksum = hashlib.sha256(object_data).hexdigest() if not hmac.compare_digest(checksum, str(manifest.get("objects_sha256", ""))): - raise ArchiveValidationError("Die Objektdatei stimmt nicht mit ihrer Prüfsumme überein.") + raise ArchiveValidationError(_("The object file does not match its checksum.")) warnings = [] signature = manifest.get("signature") if signing_key: expected = _signature(manifest, signing_key) if not signature or not hmac.compare_digest(expected, signature): - raise ArchiveValidationError("Die Archivsignatur ist ungültig oder fehlt.") + raise ArchiveValidationError(_("The archive signature is invalid or missing.")) elif signature: - warnings.append("Das Archiv ist signiert, aber ohne konfigurierten Schlüssel nicht verifiziert.") + warnings.append(_("The archive is signed but was not verified because no key is configured.")) else: - warnings.append("Das Archiv ist nicht signiert.") + warnings.append(_("The archive is not signed.")) records = [] try: @@ -171,9 +172,9 @@ def read_archive( if line: records.append(json.loads(line)) if len(records) > max_objects: - raise ArchiveValidationError("Das Archiv enthält zu viele Objekte.") + raise ArchiveValidationError(_("The archive contains too many objects.")) except (ValueError, UnicodeDecodeError) as exc: - raise ArchiveValidationError("objects.ndjson enthält ungültiges JSON.") from exc + raise ArchiveValidationError(_("objects.ndjson contains invalid JSON.")) from exc assets = { name: archive.read(name) @@ -182,11 +183,11 @@ def read_archive( } declared_assets = manifest.get("assets_sha256", {}) if set(declared_assets) != set(assets): - raise ArchiveValidationError("Die Dateiliste stimmt nicht mit dem Manifest überein.") + raise ArchiveValidationError(_("The file list does not match the manifest.")) for name, content in assets.items(): actual = hashlib.sha256(content).hexdigest() if not hmac.compare_digest(actual, str(declared_assets.get(name, ""))): - raise ArchiveValidationError(f"Die Prüfsumme der Datei {name} ist ungültig.") + raise ArchiveValidationError(_("The checksum of file %(name)s is invalid.") % {"name": name}) if manifest.get("object_count") != len(records): - raise ArchiveValidationError("Die Objektanzahl stimmt nicht mit dem Manifest überein.") + raise ArchiveValidationError(_("The object count does not match the manifest.")) return ParsedArchive(manifest=manifest, records=records, assets=assets, warnings=warnings) diff --git a/netbox_export/services/graph.py b/netbox_export/services/graph.py index d1e6a1f..24ed01e 100644 --- a/netbox_export/services/graph.py +++ b/netbox_export/services/graph.py @@ -6,6 +6,7 @@ from django.apps import apps from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models +from django.utils.translation import gettext as _ from .codec import object_key from .exceptions import GraphLimitError @@ -153,8 +154,10 @@ class ObjectGraph: object_count = len(self.members) + len(self.dependencies) if object_count > self.max_objects: raise GraphLimitError( - f"Der Export würde mehr als {self.max_objects} Objekte enthalten. " - "Bitte den Bereich verkleinern oder max_objects erhöhen." + _( + "The export would contain more than %(max)s objects. " + "Narrow the scope or increase max_objects." + ) % {"max": self.max_objects} ) def add_member(self, obj) -> bool: diff --git a/netbox_export/services/importer.py b/netbox_export/services/importer.py index 60bcaea..7a4f74b 100644 --- a/netbox_export/services/importer.py +++ b/netbox_export/services/importer.py @@ -18,6 +18,7 @@ from django.contrib.contenttypes.models import ContentType from django.core.files.base import ContentFile from django.db import IntegrityError, models, transaction from django.db.models import Value +from django.utils.translation import gettext as _ from PIL import Image as PillowImage from netbox_export.models import ImportedObjectMapping @@ -105,9 +106,9 @@ def _model_for(label: str): try: model = apps.get_model(label) except (LookupError, ValueError) as exc: - raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.") from exc + raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label}) from exc if model is None: - raise ArchiveValidationError(f"Das Modell {label} ist auf der Zielinstanz nicht installiert.") + raise ArchiveValidationError(_("The model %(model)s is not installed on the target instance.") % {"model": label}) return model @@ -313,8 +314,11 @@ def _find_existing(source_instance, model, record, resolver): if mapped is not None and mapped.pk != natural.pk: resolver.warn( ("mapping-rebound", record["id"]), - f"Gespeicherte Zuordnung für {record['id']} wurde von Ziel-ID {mapped.pk} auf " - f"Ziel-ID {natural.pk} korrigiert, da der Fachschlüssel {dict(lookup)} bereits existiert.", + _( + "Stored mapping for %(record)s was corrected from target ID %(old)s to target ID %(new)s " + "because the natural key %(key)s already exists." + ) + % {"record": record["id"], "old": mapped.pk, "new": natural.pk, "key": dict(lookup)}, ) return natural @@ -418,7 +422,7 @@ def _apply_device_placements( for record_id, placement in placements: rack, available = resolver.resolve(placement.rack_spec) if not available: - raise ArchiveValidationError(f"Rack-Referenz für {record_id} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("Rack reference for %(record)s could not be resolved.") % {"record": record_id}) if rack is MISSING_REFERENCE: continue @@ -428,7 +432,7 @@ def _apply_device_placements( if rack is None and (position is not None or face is not None): resolver.warn( ("device-placement-without-rack", record_id), - f"Rackplatz für {record_id} wurde ausgelassen, da kein Rack zugeordnet ist.", + _("Rack position for %(record)s was omitted because no rack is assigned.") % {"record": record_id}, ) position = None face = None @@ -445,14 +449,18 @@ def _apply_device_placements( occupants = _conflicting_devices(conflicts) if conflict_strategy == "fail": raise ImportConflictError( - f"Rackplatzkonflikt für {record_id}: {target} ist durch Zielgerät(e) {occupants} belegt." + _("Rack position conflict for %(record)s: %(target)s is occupied by target device(s) %(occupants)s.") + % {"record": record_id, "target": target, "occupants": occupants} ) if conflict_strategy == "skip": _save_device_placement(device, rack, None, None, compatibility) resolver.warn( ("device-placement-skipped", record_id), - f"Rackplatz für {record_id} wurde übersprungen: {target} bleibt durch " - f"Zielgerät(e) {occupants} belegt. Das importierte Gerät wurde ohne Position im Rack gespeichert.", + _( + "Rack position for %(record)s was skipped: %(target)s remains occupied by target device(s) " + "%(occupants)s. The imported device was saved without a rack position." + ) + % {"record": record_id, "target": target, "occupants": occupants}, ) continue @@ -463,8 +471,11 @@ def _apply_device_placements( _save_device_placement(device, rack, position, face, compatibility) resolver.warn( ("device-placement-released", record_id), - f"Rackplatzkonflikt für {record_id} gelöst: Zielgerät(e) {occupants} wurden aus {target} " - "gelöst und ohne Position im Rack belassen.", + _( + "Rack position conflict for %(record)s resolved: target device(s) %(occupants)s were removed " + "from %(target)s and left without a rack position." + ) + % {"record": record_id, "occupants": occupants, "target": target}, ) @@ -503,8 +514,10 @@ def _release_port_mapping_conflicts(obj, resolver, record_id): conflict.delete() resolver.warn( ("port-mapping-replaced", record_id), - f"Portzuordnung(en) {conflict_ids} wurden durch {record_id} ersetzt, damit die " - "Front-/Rear-Port-Verkabelung der Quelle entspricht.", + _( + "Port mapping(s) %(ids)s were replaced by %(record)s so the front/rear port cabling matches the source." + ) + % {"ids": conflict_ids, "record": record_id}, ) @@ -640,8 +653,8 @@ def _open_image_with_bounded_override(data): except PillowImage.DecompressionBombError as exc: stream.close() raise ArchiveValidationError( - "Das Bild überschreitet die sichere Importgrenze von " - f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln." + _("The image exceeds the safe import limit of %(max)s pixels.") + % {"max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"} ) from exc except Exception: stream.close() @@ -673,8 +686,8 @@ def _prepare_image_asset(data): source_pixels = width * height if source_pixels > IMPORTED_IMAGE_SOURCE_MAX_PIXELS: raise ArchiveValidationError( - f"Das Bild mit {source_pixels:,} Pixeln überschreitet die sichere Importgrenze von " - f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,} Pixeln." + _("The image with %(pixels)s pixels exceeds the safe import limit of %(max)s pixels.") + % {"pixels": f"{source_pixels:,}", "max": f"{IMPORTED_IMAGE_SOURCE_MAX_PIXELS:,}"} ) if source_pixels <= NETBOX_IMAGE_MAX_PIXELS: return data, width, height, None @@ -714,8 +727,8 @@ def _set_files(obj, record, assets, saved_files, *, dry_run: bool, import_warnin old_width, old_height, new_width, new_height = resize_info record_id = record.get("id", obj._meta.label_lower) import_warnings.append( - f"Bild für {record_id} wurde von {old_width}×{old_height} auf " - f"{new_width}×{new_height} Pixel verkleinert." + _("Image for %(record)s was downscaled from %(old)s to %(new)s pixels.") + % {"record": record_id, "old": f"{old_width}×{old_height}", "new": f"{new_width}×{new_height}"} ) if dry_run: continue @@ -748,7 +761,7 @@ def _apply_m2m(obj, record, resolver): for spec in specs: value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"M2M-Referenz für {record['id']} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("M2M reference for %(record)s could not be resolved.") % {"record": record["id"]}) if value is MISSING_REFERENCE: continue values.append(value) @@ -781,7 +794,7 @@ def _forced(force, warnings, label, func, *args, **kwargs): except ImportConflictError: raise except Exception as exc: # noqa: BLE001 - force mode skips any failing step - warnings.append(f"Force-Modus: {label} wurde wegen eines Fehlers übersprungen: {exc}") + warnings.append(_("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": label, "error": exc}) return None @@ -801,8 +814,11 @@ def _skip_uninstalled_optional_models(records, resolver, report): del records[record_id] for label in sorted(missing_labels): report.warnings.append( - f"Objekte vom Typ {label} wurden übersprungen, da das zugehörige optionale Plugin " - "auf der Zielinstanz nicht installiert ist." + _( + "Objects of type %(model)s were skipped because the related optional plugin is not installed " + "on the target instance." + ) + % {"model": label} ) @@ -810,24 +826,25 @@ def import_archive( parsed: ParsedArchive, *, conflict_strategy: str, dry_run: bool, force: bool = False ) -> ImportReport: if conflict_strategy not in ("update", "skip", "fail"): - raise ArchiveValidationError("Unbekannte Konfliktstrategie.") + raise ArchiveValidationError(_("Unknown conflict strategy.")) source_version = str(parsed.manifest.get("source_netbox_version", "")) target_version = str(getattr(getattr(settings, "RELEASE", None), "version", "")) if source_version and target_version and source_version.split(".")[:2] != target_version.split(".")[:2]: raise ArchiveValidationError( - f"NetBox-Versionen sind nicht kompatibel: Quelle {source_version}, Ziel {target_version}." + _("NetBox versions are not compatible: source %(source)s, target %(target)s.") + % {"source": source_version, "target": target_version} ) try: source_instance = uuid.UUID(parsed.manifest["source_instance"]) except (KeyError, TypeError, ValueError) as exc: - raise ArchiveValidationError("Die Quellinstanz-Kennung fehlt oder ist ungültig.") from exc + raise ArchiveValidationError(_("The source instance ID is missing or invalid.")) from exc records = {} for record in parsed.records: if not all(key in record for key in ("id", "model", "source_pk")): - raise ArchiveValidationError("Ein Objektdatensatz ist unvollständig.") + raise ArchiveValidationError(_("An object record is incomplete.")) if record["id"] in records: - raise ArchiveValidationError(f"Doppelte Objekt-ID im Archiv: {record['id']}") + raise ArchiveValidationError(_("Duplicate object ID in archive: %(record)s") % {"record": record["id"]}) records[record["id"]] = record report = ImportReport(dry_run=dry_run, warnings=list(parsed.warnings)) @@ -867,7 +884,7 @@ def import_archive( except IdentityNotReady: continue if existing is not None and conflict_strategy == "fail": - raise ImportConflictError(f"Zielobjekt existiert bereits: {record_id}") + raise ImportConflictError(_("Target object already exists: %(record)s") % {"record": record_id}) if existing is not None and conflict_strategy == "skip": obj = existing @@ -905,7 +922,7 @@ def import_archive( raise resolver.skipped.add(record_id) report.warnings.append( - f"Force-Modus: {record_id} wurde wegen eines Fehlers übersprungen: {exc}" + _("Force mode: %(label)s was skipped because of an error: %(error)s") % {"label": record_id, "error": exc} ) report.add(record["model"], "skipped") pending.pop(record_id) @@ -934,12 +951,12 @@ def import_archive( resolver.skipped.add(record_id) report.add(record["model"], "skipped") report.warnings.append( - f"Force-Modus: {len(pending)} Objekt(e) mit nicht auflösbaren Referenzen " - f"wurden übersprungen: {blocked}" + _("Force mode: %(count)s object(s) with unresolvable references were skipped: %(blocked)s") + % {"count": len(pending), "blocked": blocked} ) break raise ArchiveValidationError( - f"Erforderliche Referenzen konnten nicht aufgelöst werden: {blocked}" + _("Required references could not be resolved: %(blocked)s") % {"blocked": blocked} ) for record_id, name, spec in deferred_relations: @@ -947,13 +964,13 @@ def import_archive( continue value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"Referenz {name} für {record_id} konnte nicht aufgelöst werden.") + raise ArchiveValidationError(_("Reference %(name)s for %(record)s could not be resolved.") % {"name": name, "record": record_id}) if value is MISSING_REFERENCE: continue _forced( force, report.warnings, - f"Referenz {name} für {record_id}", + _("Reference %(name)s for %(record)s") % {"name": name, "record": record_id}, _apply_deferred_relation, resolved[record_id], name, @@ -966,7 +983,7 @@ def import_archive( continue value, available = resolver.resolve(spec) if not available: - raise ArchiveValidationError(f"Generische Referenz {name} für {record_id} fehlt.") + raise ArchiveValidationError(_("Generic reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id}) if value is MISSING_REFERENCE: continue obj = resolved[record_id] @@ -975,7 +992,7 @@ def import_archive( _forced( force, report.warnings, - f"Generische Referenz {name} für {record_id}", + _("Generic reference %(name)s for %(record)s") % {"name": name, "record": record_id}, compatibility.save, obj, update_fields=[field.ct_field, field.fk_field], @@ -986,13 +1003,13 @@ def import_archive( continue value, available = _decode_archived_value(encoded, resolver) if not available: - raise ArchiveValidationError(f"Custom-Field-Referenz {name} für {record_id} fehlt.") + raise ArchiveValidationError(_("Custom field reference %(name)s for %(record)s is missing.") % {"name": name, "record": record_id}) obj = resolved[record_id] setattr(obj, name, value) _forced( force, report.warnings, - f"Custom-Field-Wert {name} für {record_id}", + _("Custom field value %(name)s for %(record)s") % {"name": name, "record": record_id}, compatibility.save, obj, update_fields=[name], @@ -1001,7 +1018,7 @@ def import_archive( _forced( force, report.warnings, - "Rackplatzierung der Geräte", + _("Rack placement of devices"), _apply_device_placements, deferred_device_placements, resolved, @@ -1015,7 +1032,7 @@ def import_archive( _forced( force, report.warnings, - f"Mehrfachzuordnungen für {record_id}", + _("Many-to-many assignments for %(record)s") % {"record": record_id}, _apply_m2m, resolved[record_id], record, @@ -1025,7 +1042,7 @@ def import_archive( _forced( force, report.warnings, - "Neuberechnung der Kabelpfade", + _("Recalculation of cable paths"), _rebuild_imported_cable_paths, records, resolved, @@ -1035,11 +1052,11 @@ def import_archive( transaction.set_rollback(True) except (IntegrityError, ValueError, TypeError) as exc: _cleanup_files(saved_files) - raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc + raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc except ExportImportError: _cleanup_files(saved_files) raise except Exception as exc: _cleanup_files(saved_files) - raise ArchiveValidationError(f"Der Import wurde zurückgerollt: {exc}") from exc + raise ArchiveValidationError(_("The import was rolled back: %(error)s") % {"error": exc}) from exc return report diff --git a/netbox_export/services/plugin_compat.py b/netbox_export/services/plugin_compat.py index 03a1d4e..834fa8a 100644 --- a/netbox_export/services/plugin_compat.py +++ b/netbox_export/services/plugin_compat.py @@ -5,10 +5,12 @@ from functools import cache from django.apps import apps from django.core.exceptions import FieldDoesNotExist, ValidationError from django.db import models +from django.utils.translation import gettext as _ AUTO_IMPORT_TENANT_NAME = "Auto-Import" AUTO_IMPORT_TENANT_SLUG = "auto-import" -MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." +MISSING_TENANT_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden." # netbox_utilities before i18n +MISSING_TENANT_CODE = "tenant_required" # Apps of optional plugins whose data is exported when installed on the source # and skipped (instead of failing the import) when missing on the target. OPTIONAL_PLUGIN_APP_LABELS = frozenset({"netbox_utilities"}) @@ -20,6 +22,8 @@ def is_optional_plugin_model(label: str) -> bool: def netbox_utilities_tenant_required() -> bool: """Return the effective tenant policy without requiring the optional plugin.""" + if not apps.is_installed("netbox_utilities"): # importing its models while disabled raises RuntimeError + return False try: from netbox_utilities.runtime import tenant_required except ImportError: @@ -27,6 +31,19 @@ def netbox_utilities_tenant_required() -> bool: return bool(tenant_required()) +def netbox_utilities_tenant_messages() -> set[str]: + """Messages netbox_utilities may raise for a missing tenant, in the active language.""" + messages = {MISSING_TENANT_MESSAGE} + if not apps.is_installed("netbox_utilities"): + return messages + try: + from netbox_utilities.tenant_validation import VALIDATION_MESSAGE + except ImportError: + return messages + messages.add(str(VALIDATION_MESSAGE)) + return messages + + def is_tenant_relation(field) -> bool: if field.name != "tenant": return False @@ -99,7 +116,9 @@ class PluginCompatibility: @staticmethod def _is_missing_tenant_error(exc: ValidationError) -> bool: - return MISSING_TENANT_MESSAGE in exc.messages + if any(getattr(error, "code", None) == MISSING_TENANT_CODE for error in getattr(exc, "error_list", ())): + return True + return not netbox_utilities_tenant_messages().isdisjoint(exc.messages) def _auto_import_tenant(self): if self._fallback_tenant is not None: @@ -118,18 +137,24 @@ class PluginCompatibility: if self.dry_run: message = ( - 'Für den Prüflauf wurde der Mandant "Auto-Import" automatisch als Ersatzmandant ' - "verwendet; er wird nicht dauerhaft angelegt oder geändert." + _( + 'The tenant "Auto-Import" was used automatically as a fallback tenant for the dry run; ' + "it is not created or changed permanently." + ) ) elif created: message = ( - 'Der Mandant "Auto-Import" wurde automatisch erstellt und Objekten ohne ' - "auflösbaren Mandanten zugewiesen." + _( + 'The tenant "Auto-Import" was created automatically and assigned to objects without a ' + "resolvable tenant." + ) ) else: message = ( - 'Der vorhandene Mandant "Auto-Import" wurde automatisch für Objekte ohne ' - "auflösbaren Mandanten ausgewählt." + _( + 'The existing tenant "Auto-Import" was selected automatically for objects without a ' + "resolvable tenant." + ) ) self.warnings.append(message) self._fallback_tenant = tenant @@ -174,6 +199,9 @@ class PluginCompatibility: type(obj)._default_manager.filter(pk__in=conflict_ids).update(**{field.attname: None}) identifiers = ", ".join(str(pk) for pk in conflict_ids) self.warnings.append( - f"Eindeutige Referenz {obj._meta.label_lower}.{field_name} wurde von Zielobjekt(en) " - f"{identifiers} gelöst und dem importierten Objekt neu zugeordnet." + _( + "Unique reference %(field)s was released from target object(s) %(ids)s and reassigned to the " + "imported object." + ) + % {"field": f"{obj._meta.label_lower}.{field_name}", "ids": identifiers} ) diff --git a/netbox_export/services/references.py b/netbox_export/services/references.py index c522c46..3a61523 100644 --- a/netbox_export/services/references.py +++ b/netbox_export/services/references.py @@ -1,5 +1,7 @@ from __future__ import annotations +from django.utils.translation import gettext as _ + from .codec import decode_scalar from .exceptions import ArchiveValidationError @@ -25,7 +27,8 @@ class ReferenceResolver: fields = ", ".join(field_names) self.warn( ("skipped", record_id), - f"{record_id} ({model_label}) wurde wegen fehlender Pflichtreferenz übersprungen: {fields}.", + _("%(record)s (%(model)s) was skipped because of a missing required reference: %(fields)s.") + % {"record": record_id, "model": model_label, "fields": fields}, ) def _external_object(self, spec): @@ -39,14 +42,15 @@ class ReferenceResolver: value = model._default_manager.get(**lookup) except model.DoesNotExist: value = MISSING_REFERENCE - reason = "nicht gefunden" + reason = _("not found") except model.MultipleObjectsReturned: value = MISSING_REFERENCE - reason = "nicht eindeutig" + reason = _("not unique") if value is MISSING_REFERENCE: self.warn( ("external", cache_key), - f"Externe Referenz ausgelassen: {spec['model']} mit {lookup} ({reason}).", + _("External reference omitted: %(model)s with %(lookup)s (%(reason)s).") + % {"model": spec["model"], "lookup": lookup, "reason": reason}, ) self._external_cache[cache_key] = value return value @@ -59,10 +63,10 @@ class ReferenceResolver: if record_id in self.skipped: self.warn( ("internal", record_id), - f"Referenzen auf das übersprungene Objekt {record_id} wurden ausgelassen.", + _("References to the skipped object %(record)s were omitted.") % {"record": record_id}, ) return MISSING_REFERENCE, True return self.resolved.get(record_id), record_id in self.resolved if "external" in spec: return self._external_object(spec["external"]), True - raise ArchiveValidationError("Eine Objektreferenz im Archiv ist ungültig.") + raise ArchiveValidationError(_("An object reference in the archive is invalid.")) diff --git a/netbox_export/templates/netbox_export/dashboard.html b/netbox_export/templates/netbox_export/dashboard.html index 29e014a..d01ed7d 100644 --- a/netbox_export/templates/netbox_export/dashboard.html +++ b/netbox_export/templates/netbox_export/dashboard.html @@ -1,5 +1,6 @@ {% extends 'base/layout.html' %} {% load form_helpers %} +{% load i18n %} {% block title %}NetBox-Export{% endblock title %} @@ -19,18 +20,22 @@ {% if report %}
| Modell | Erstellt | Aktualisiert | Übersprungen |
|---|---|---|---|
| {% trans "Model" %} | {% trans "Created" %} | {% trans "Updated" %} | {% trans "Skipped" %} |