-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathwagtail_hooks.py
More file actions
518 lines (440 loc) · 19.2 KB
/
Copy pathwagtail_hooks.py
File metadata and controls
518 lines (440 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
from __future__ import annotations
from urllib.parse import urlencode
from django.conf import settings
from django.contrib.admin.utils import quote
from django.contrib.auth.models import Permission
from django.db import transaction
from django.db.models import Q
from django.shortcuts import redirect
from django.urls import include, path, reverse
from django.utils import timezone
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
from django.views.i18n import JavaScriptCatalog
from wagtail import VERSION as WAGTAIL_VERSION
from wagtail import hooks
from wagtail.admin.action_menu import ActionMenuItem as PageActionMenuItem
from wagtail.admin.menu import MenuItem
from wagtail.log_actions import LogFormatter
from wagtail.models import Locale, Page, TranslatableMixin
from wagtail.snippets.action_menu import ActionMenuItem as SnippetActionMenuItem
# Import synctree so it can register its signal handler
from . import synctree # noqa: F401
from .machine_translators import get_machine_translator
from .models import Translation, TranslationSource
from .views import (
convert,
edit_translation,
report,
snippets_api,
submit_translations,
update_translations,
)
if WAGTAIL_VERSION >= (7, 0):
from wagtail.admin.widgets.button import Button as ListingButton
from wagtail.admin.widgets.button import Button as SnippetListingButton
else:
from wagtail.admin.widgets import ListingButton
from wagtail.snippets.widgets import SnippetListingButton
@hooks.register("register_admin_urls")
def register_admin_urls():
urls = [
path(
"jsi18n/",
JavaScriptCatalog.as_view(packages=["wagtail_localize"]),
name="javascript_catalog",
),
path(
"submit/page/<int:page_id>/",
submit_translations.SubmitPageTranslationView.as_view(),
name="submit_page_translation",
),
path(
"submit/snippet/<slug:app_label>/<slug:model_name>/<str:pk>/",
submit_translations.SubmitSnippetTranslationView.as_view(),
name="submit_snippet_translation",
),
path(
"update/<int:translation_source_id>/",
update_translations.UpdateTranslationsView.as_view(),
name="update_translations",
),
path(
"translate/<int:translation_id>/strings/<int:string_segment_id>/edit/",
edit_translation.edit_string_translation,
name="edit_string_translation",
),
path(
"translate/<int:translation_id>/overrides/<int:overridable_segment_id>/edit/",
edit_translation.edit_override,
name="edit_override",
),
path(
"translate/<int:translation_id>/pofile/download/",
edit_translation.download_pofile,
name="download_pofile",
),
path(
"translate/<int:translation_id>/pofile/upload/",
edit_translation.upload_pofile,
name="upload_pofile",
),
path(
"translate/<int:translation_id>/machine_translate/",
edit_translation.machine_translate,
name="machine_translate",
),
path(
"translate/<int:translation_id>/preview/",
edit_translation.preview_translation,
name="preview_translation",
),
path(
"translate/<int:translation_id>/preview/<str:mode>/",
edit_translation.preview_translation,
name="preview_translation",
),
path(
"translate/<int:translation_id>/disable/",
edit_translation.stop_translation,
name="stop_translation",
),
path(
"page/<int:page_id>/convert_to_alias/",
convert.convert_to_alias,
name="convert_to_alias",
),
path(
"reports/translations/",
report.TranslationsReportView.as_view(),
name="translations_report",
),
path(
"api/snippets/<slug:app_label>/<slug:model_name>/",
snippets_api.SnippetViewSet.as_view({"get": "list"}),
name="snippets_api_listing",
),
path(
"api/snippets/<slug:app_label>/<slug:model_name>/<str:pk>/",
snippets_api.SnippetViewSet.as_view({"get": "retrieve"}),
name="snippets_api_detail",
),
path(
"reports/translations/results/",
report.TranslationsReportView.as_view(results_only=True),
name="translations_report_results",
),
]
return [
path(
"localize/",
include(
(urls, "wagtail_localize"),
namespace="wagtail_localize",
),
)
]
@hooks.register("register_permissions")
def register_submit_translation_permission():
return Permission.objects.filter(
content_type__app_label="wagtail_localize", codename="submit_translation"
)
def page_listing_more_buttons(page: Page, user, view_name=None, next_url=None):
if not page.is_root() and user.has_perm("wagtail_localize.submit_translation"):
# If there's at least one locale that we haven't translated into yet, show "Translate this page" button
has_locale_to_translate_to = Locale.objects.exclude(
id__in=page.get_translations(inclusive=True)
.exclude(alias_of__isnull=False)
.values_list("locale_id", flat=True)
).exists()
if has_locale_to_translate_to:
# note: if this is an alias page, we want to use the parent page id
url = reverse(
"wagtail_localize:submit_page_translation",
args=[page.alias_of_id or page.id],
)
yield ListingButton(
_("Translate this page"),
url,
priority=60,
icon_name="wagtail-localize-language",
)
# If the page is the source for translations, show "Sync translated pages" button
source = TranslationSource.objects.get_for_instance_or_none(page)
if source is not None and source.translations.filter(enabled=True).exists():
url = reverse("wagtail_localize:update_translations", args=[source.id])
if next_url is not None:
url += "?" + urlencode({"next": next_url})
yield ListingButton(
_("Sync translated pages"), url, priority=60, icon_name="resubmit"
)
hooks.register("register_page_header_buttons", page_listing_more_buttons)
hooks.register("register_page_listing_more_buttons", page_listing_more_buttons)
@hooks.register("register_snippet_listing_buttons")
def register_snippet_listing_buttons(snippet, user, next_url=None):
model = type(snippet)
if issubclass(model, TranslatableMixin) and user.has_perm(
"wagtail_localize.submit_translation"
):
# If there's at least one locale that we haven't translated into yet, show "Translate" button
has_locale_to_translate_to = Locale.objects.exclude(
id__in=snippet.get_translations(inclusive=True).values_list(
"locale_id", flat=True
)
).exists()
if has_locale_to_translate_to:
url = reverse(
"wagtail_localize:submit_snippet_translation",
args=[model._meta.app_label, model._meta.model_name, quote(snippet.pk)],
)
yield SnippetListingButton(
_("Translate"),
url,
attrs={
"aria-label": _("Translate '%(title)s'") % {"title": str(snippet)}
},
icon_name="wagtail-localize-language",
priority=100,
)
# If the snippet is the source for translations, show "Sync translated snippets" button
source = TranslationSource.objects.get_for_instance_or_none(snippet)
if source is not None and source.translations.filter(enabled=True).exists():
url = reverse("wagtail_localize:update_translations", args=[source.id])
if next_url is not None:
url += "?" + urlencode({"next": next_url})
yield SnippetListingButton(
_("Sync translated snippets"),
url,
attrs={
"aria-label": _("Sync translations of '%(title)s'")
% {"title": str(snippet)}
},
icon_name="resubmit",
priority=106,
)
@hooks.register("before_edit_page")
def before_edit_page(request, page):
# If the page is an alias of a page in another locale, override the edit page so that we can show a "Translate this page" option
if page.alias_of and page.alias_of.locale_id != page.locale_id:
return edit_translation.edit_translatable_alias_page(request, page)
# Check if the user has clicked the "Start Synced translation" menu item
if request.method == "POST":
if "localize-restart-translation" in request.POST:
try:
translation = Translation.objects.get(
source__object_id=page.translation_key,
target_locale_id=page.locale_id,
enabled=False,
)
except Translation.DoesNotExist:
pass
else:
return edit_translation.restart_translation(request, translation, page)
elif "localize-convert-to-alias" in request.POST:
return redirect(
reverse("wagtail_localize:convert_to_alias", args=[page.id])
)
elif "localize-publish-with-machine-translation" in request.POST:
request.POST = request.POST.copy()
request.POST["action-publish"] = "action-publish"
# This field will be checked by the "after_publish_page" hook. Since the page instance gets reloaded
# before "after_publish_page" is called, we have to use the request object to keep the flag.
request._localize_machine_translation_on_publish = page.id
# Overrides the edit page view if the page is the target of a translation
try:
translation = Translation.objects.get(
source__object_id=page.translation_key,
target_locale_id=page.locale_id,
enabled=True,
)
return edit_translation.edit_translation(request, translation, page)
except Translation.DoesNotExist:
pass
@hooks.register("after_publish_page")
def after_publish_page(request, page):
if getattr(request, "_localize_machine_translation_on_publish", None) == page.id:
# Note: Syncing the go-live-date to the translations is not supported yet. To avoid publishing the
# translations too early, we skip it.
# TODO: Remove/Adapt this code and PublishWithMachineTranslationPageActionMenuItem, when go_live_at is synced with translations.
go_live_at = page.go_live_at
if go_live_at and go_live_at > timezone.now():
return
if get_machine_translator() is None:
return
# This is executed after publication, so we don't have to check can_publish().
if not request.user.has_perm("wagtail_localize.submit_translation"):
return
source = TranslationSource.objects.get_for_instance_or_none(page)
if source is None or not source.translations.filter(enabled=True).exists():
return
with transaction.atomic():
update_translations.update_translations(
request,
source,
source.translations.filter(enabled=True),
use_machine_translation=True,
publish_translations=True,
)
elif getattr(settings, "WAGTAILLOCALIZE_UPDATE_TRANSLATIONS_ON_PUBLISH", False):
if not request.user.has_perm("wagtail_localize.submit_translation"):
return
source = TranslationSource.objects.get_for_instance_or_none(page)
if source is None or not source.translations.filter(enabled=True).exists():
return
with transaction.atomic():
update_translations.update_translations(
request,
source,
source.translations.filter(enabled=True),
)
class RestartTranslationPageActionMenuItem(PageActionMenuItem):
label = gettext_lazy("Start Synced translation")
name = "localize-restart-translation"
icon_name = "rotate"
classname = "action-secondary"
def is_shown(self, context):
# Only show this menu item on the edit view where there was a previous translation record
if context["view"] != "edit":
return False
return Translation.objects.filter(
source__object_id=context["page"].translation_key,
target_locale_id=context["page"].locale_id,
enabled=False,
).exists()
@hooks.register("register_page_action_menu_item")
def register_restart_translation_page_action_menu_item():
return RestartTranslationPageActionMenuItem(order=0)
class ConvertToAliasPageActionMenuItem(PageActionMenuItem):
label = gettext_lazy("Convert to alias page")
name = "localize-convert-to-alias"
icon_name = "wagtail-localize-convert"
classname = "action-secondary"
def is_shown(self, context):
# Only show this menu item on the edit view where there was a previous translation record
if context["view"] != "edit":
return False
page = context["page"]
try:
return (
page.alias_of_id is None
and Page.objects.filter(
~Q(pk=page.pk),
translation_key=page.translation_key,
locale_id=TranslationSource.objects.get(
object_id=page.translation_key,
specific_content_type=page.content_type_id,
translations__target_locale=page.locale_id,
).locale_id,
).exists()
)
except TranslationSource.DoesNotExist:
return False
@hooks.register("register_page_action_menu_item")
def register_convert_back_to_alias_page_action_menu_item():
return ConvertToAliasPageActionMenuItem(order=0)
class PublishWithMachineTranslationPageActionMenuItem(PageActionMenuItem):
label = gettext_lazy("Publish & machine translate")
name = "localize-publish-with-machine-translation"
icon_name = "upload"
classname = "action-secondary"
def is_shown(self, context):
# We only support the edit view for now.
if context["view"] != "edit":
return False
# See note in "after_publish_page" hook above.
go_live_at = context["page"].go_live_at
if go_live_at and go_live_at > timezone.now():
return False
if get_machine_translator() is None:
return False
page_perms = self.get_user_page_permissions_tester(context)
if not page_perms.can_publish() or not context["request"].user.has_perm(
"wagtail_localize.submit_translation"
):
return False
# As with the "Sync translated pages" button we only show this menu item, if enabled translations exist.
source = TranslationSource.objects.get_for_instance_or_none(context["page"])
return source is not None and source.translations.filter(enabled=True).exists()
@hooks.register("register_page_action_menu_item")
def register_publish_with_machine_translation_page_action_menu_item():
return PublishWithMachineTranslationPageActionMenuItem()
@hooks.register("before_edit_snippet")
def before_edit_snippet(request, instance):
if isinstance(instance, TranslatableMixin):
# Check if the user has clicked the "Start Synced translation" menu item
if request.method == "POST" and "localize-restart-translation" in request.POST:
try:
translation = Translation.objects.get(
source__object_id=instance.translation_key,
target_locale_id=instance.locale_id,
enabled=False,
)
except Translation.DoesNotExist:
pass
else:
return edit_translation.restart_translation(
request, translation, instance
)
# Overrides the edit snippet view if the snippet is translatable and the target of a translation
try:
translation = Translation.objects.get(
source__object_id=instance.translation_key,
target_locale_id=instance.locale_id,
enabled=True,
)
return edit_translation.edit_translation(request, translation, instance)
except Translation.DoesNotExist:
pass
class RestartTranslationSnippetActionMenuItem(SnippetActionMenuItem):
label = gettext_lazy("Start Synced translation")
name = "localize-restart-translation"
icon_name = "rotate"
classname = "action-secondary"
def is_shown(self, context):
# Only show this menu item on the edit view where there was a previous translation record
if context["view"] != "edit":
return False
if not issubclass(context["model"], TranslatableMixin):
return False
return Translation.objects.filter(
source__object_id=context["instance"].translation_key,
target_locale_id=context["instance"].locale_id,
enabled=False,
).exists()
@hooks.register("register_snippet_action_menu_item")
def register_restart_translation_snippet_action_menu_item(model):
return RestartTranslationSnippetActionMenuItem(order=0)
class TranslationsReportMenuItem(MenuItem):
def is_shown(self, request):
return True
@hooks.register("register_reports_menu_item")
def register_wagtail_localize2_report_menu_item():
return TranslationsReportMenuItem(
_("Translations"),
reverse("wagtail_localize:translations_report"),
icon_name="site",
order=9000,
)
@hooks.register("register_log_actions")
def wagtail_localize_log_actions(actions):
@actions.register_action("wagtail_localize.convert_to_alias")
class ConvertToAliasActionFormatter(LogFormatter):
label = gettext_lazy("Convert page to alias")
def format_message(self, log_entry):
try:
return _(
"Converted page '%(title)s' to an alias of the translation source page '%(source_title)s'"
) % {
"title": log_entry.data["page"]["title"],
"source_title": log_entry.data["source"]["title"],
}
except KeyError:
return _("Converted page to an alias of the translation source page")
@hooks.register("register_icons")
def register_icons(icons):
return icons + [
# icon id "wagtail-localize-convert" (which translates to `.icon-wagtail-localize-convert`)
"wagtail_localize/icons/wagtail-localize-convert.svg",
# icon id "wagtail-localize-language" (which translates to `.icon-wagtail-localize-language`)
"wagtail_localize/icons/wagtail-localize-language.svg",
]