-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathmodels.py
1247 lines (1071 loc) · 41.5 KB
/
models.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
from django.conf import settings
from django.contrib.admin.utils import flatten
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.core.files.images import get_image_dimensions
from django.core.cache import cache
from django.db import models
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
from modelcluster.contrib.taggit import ClusterTaggableManager
from iogt.settings.base import WAGTAIL_CONTENT_LANGUAGES
from modelcluster.fields import ParentalKey
from rest_framework import status
from taggit.models import TaggedItemBase
from wagtail.admin.panels import (
FieldPanel,
InlinePanel,
MultiFieldPanel,
ObjectList,
TabbedInterface,
)
from wagtail.contrib.settings.models import BaseSetting
from wagtail.contrib.settings.registry import register_setting
from wagtail import blocks
from wagtail.fields import StreamField
from wagtail.models import Orderable, Page, Site, Locale
from wagtail.rich_text import get_text_for_indexing
from wagtail.images.blocks import ImageChooserBlock
from wagtail.images.models import Image
from wagtail.search import index
from wagtailmarkdown.blocks import MarkdownBlock
from wagtailmenus.models import AbstractFlatMenuItem
from wagtailsvg.models import Svg
from wagtailsvg.edit_handlers import SvgChooserPanel
from messaging.blocks import ChatBotButtonBlock
from comments.models import CommentableMixin
from home.blocks import (
MediaBlock, SocialMediaLinkBlock, SocialMediaShareButtonBlock, EmbeddedPollBlock, EmbeddedSurveyBlock,
EmbeddedQuizBlock, PageButtonBlock, NumberedListBlock, RawHTMLBlock, ArticleBlock, DownloadButtonBlock,
)
from .forms import SectionPageForm
from .mixins import PageUtilsMixin, TitleIconMixin
from .utils.image import convert_svg_to_png_bytes
from .utils.progress_manager import ProgressManager
from home.utils import (
collect_urls_from_streamfield,
get_all_renditions_urls,
)
import iogt.iogt_globals as globals_
User = get_user_model()
logger = logging.getLogger(__name__)
class HomePage(Page, PageUtilsMixin, TitleIconMixin):
parent_page_types = ['wagtailcore.page']
template = 'home/home_page.html'
show_in_menus_default = True
home_featured_content = StreamField(
[
('page_button', PageButtonBlock()),
('embedded_poll', EmbeddedPollBlock()),
('embedded_survey', EmbeddedSurveyBlock()),
('embedded_quiz', EmbeddedQuizBlock()),
('article', ArticleBlock()),
('download', DownloadButtonBlock()),
],
null=True,
blank=True,
use_json_field=True,
)
content_panels = Page.content_panels + [
MultiFieldPanel([
InlinePanel('home_page_banners', label=_("Home Page Banner")),
], heading=_('Home Page Banners')),
FieldPanel('home_featured_content')
]
def get_context(self, request):
context = super().get_context(request)
banners = []
for home_page_banner in self.home_page_banners.select_related('banner_page', 'banner_page__banner_link_page').all():
banner_page = home_page_banner.banner_page
if banner_page.live and ((banner_page.banner_link_page and banner_page.banner_link_page.live) or
banner_page.banner_link_page == None):
banners.append(banner_page.specific)
context['banners'] = banners
return context
@property
def offline_urls(self):
return [self.url] + collect_urls_from_streamfield(self.home_featured_content)
class FeaturedContent(Orderable):
source = ParentalKey(Page, related_name='featured_content',
on_delete=models.CASCADE, blank=True)
content = models.ForeignKey(Page, on_delete=models.CASCADE)
panels = [
FieldPanel('content'),
]
class HomePageBanner(Orderable):
source = ParentalKey(Page, related_name='home_page_banners',
on_delete=models.CASCADE, blank=True)
banner_page = models.ForeignKey('home.BannerPage', on_delete=models.CASCADE)
panels = [
FieldPanel('banner_page'),
]
class SectionTaggedItem(TaggedItemBase):
"""The through model between Section and Tag"""
content_object = ParentalKey('Section', related_name='tagged_items',
on_delete=models.CASCADE)
class ArticleTaggedItem(TaggedItemBase):
"""The through model between Article and Tag"""
content_object = ParentalKey('Article', related_name='tagged_items',
on_delete=models.CASCADE)
class SectionIndexPage(Page):
parent_page_types = ['home.HomePage']
subpage_types = ['home.Section']
@classmethod
def get_top_level_sections(cls):
section_index_page = cls.objects.filter(locale=Locale.get_active()).first()
if section_index_page:
return section_index_page.get_children().live().specific()
return cls.objects.none()
class Section(Page, PageUtilsMixin, CommentableMixin, TitleIconMixin):
lead_image = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
icon = models.ForeignKey(
Svg,
related_name='+',
null=True,
blank=True,
on_delete=models.PROTECT,
)
image_icon = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
background_color = models.CharField(
max_length=8,
blank=True,
null=True,
)
font_color = models.CharField(
max_length=8,
blank=True,
null=True,
)
body = StreamField(
[('download', DownloadButtonBlock())],
null=True,
blank=True,
use_json_field=True,
)
tags = ClusterTaggableManager(through='SectionTaggedItem', blank=True)
show_progress_bar = models.BooleanField(default=False)
larger_image_for_top_page_in_list_as_in_v1 = models.BooleanField(default=False)
show_in_menus_default = True
promote_panels = Page.promote_panels + [
MultiFieldPanel([FieldPanel("tags"), ], heading='Metadata'),
]
content_panels = Page.content_panels + [
FieldPanel('lead_image'),
SvgChooserPanel('icon'),
FieldPanel('image_icon'),
FieldPanel('background_color'),
FieldPanel('font_color'),
FieldPanel('larger_image_for_top_page_in_list_as_in_v1'),
MultiFieldPanel([
InlinePanel('featured_content', max_num=1,
label=_("Featured Content")),
], heading=_('Featured Content')),
FieldPanel('body'),
]
settings_panels = Page.settings_panels + [
FieldPanel('show_progress_bar')
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(promote_panels, heading='Promote'),
ObjectList(settings_panels, heading='Settings'),
ObjectList(CommentableMixin.comments_panels, heading='Comments')
])
base_form_class = SectionPageForm
def get_descendant_articles(self):
return Article.objects.descendant_of(self).live().exact_type(Article)
def get_progress_bar_enabled_ancestor(self):
return Section.objects.ancestor_of(self, inclusive=True).exact_type(
Section).live().filter(
show_progress_bar=True).first()
def get_user_progress_dict(self, request):
progress_manager = ProgressManager(request)
read_article_count, total_article_count = progress_manager.get_progress(self)
return {
'read': read_article_count,
'total': total_article_count,
'range_': list(range(total_article_count)) if total_article_count else 0,
'width_': 100 / total_article_count if total_article_count else 0,
}
def is_complete(self, request):
progress_manager = ProgressManager(request)
return progress_manager.is_section_complete(self)
def get_context(self, request):
context = super().get_context(request)
featured_content = self.featured_content.all().first()
context['featured_content'] = featured_content.content.specific if featured_content and featured_content.content.live else None
context['children'] = self.get_children().live().specific()
context['user_progress'] = self.get_user_progress_dict(request)
return context
@staticmethod
def get_progress_bar_eligible_sections():
"""
Eligibility criteria:
Sections whose ancestors don't have show_progress_bar=True are eligible to
show progress bars.
:return:e
"""
progress_bar_sections = Section.objects.filter(show_progress_bar=True)
all_descendants = [list(
Section.objects.type(Section).descendant_of(section).values_list(
'pk', flat=True)) for
section in
progress_bar_sections]
all_descendants = set(flatten(all_descendants))
return Section.objects.exclude(pk__in=all_descendants)
@property
def offline_urls(self):
urls = [self.url] + collect_urls_from_streamfield(self.body)
if self.lead_image:
urls += get_all_renditions_urls(self.lead_image)
if self.image_icon:
urls += get_all_renditions_urls(self.image_icon)
return urls
class Meta:
verbose_name = _("section")
verbose_name_plural = _("sections")
class ArticleRecommendation(Orderable):
source = ParentalKey('Article', related_name='recommended_articles',
on_delete=models.CASCADE, blank=True)
article = models.ForeignKey('Article', on_delete=models.CASCADE)
panels = [
FieldPanel('article')
]
class AbstractArticle(Page, PageUtilsMixin, CommentableMixin, TitleIconMixin):
lead_image = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
icon = models.ForeignKey(
Svg,
related_name='+',
null=True,
blank=True,
on_delete=models.SET_NULL,
)
image_icon = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
index_page_description = models.TextField(null=True, blank=True)
body = StreamField(
[
('heading', blocks.CharBlock(form_classname="full title", template='blocks/heading.html')),
('paragraph', blocks.RichTextBlock(features=settings.WAGTAIL_RICH_TEXT_FIELD_FEATURES)),
('markdown', MarkdownBlock(icon='code')),
('paragraph_v1_legacy', RawHTMLBlock(icon='code')),
('image', ImageChooserBlock(template='blocks/image.html')),
('list', blocks.ListBlock(MarkdownBlock(icon='code'))),
('numbered_list', NumberedListBlock(MarkdownBlock(icon='code'))),
('page_button', PageButtonBlock()),
('embedded_poll', EmbeddedPollBlock()),
('embedded_survey', EmbeddedSurveyBlock()),
('embedded_quiz', EmbeddedQuizBlock()),
('media', MediaBlock(icon='media')),
('chat_bot', ChatBotButtonBlock()),
('download', DownloadButtonBlock()),
],
use_json_field=True,
)
show_in_menus_default = True
content_panels = Page.content_panels + [
FieldPanel('lead_image'),
SvgChooserPanel('icon'),
FieldPanel('image_icon'),
FieldPanel('body'),
FieldPanel('index_page_description'),
]
edit_handler_list = [
ObjectList(content_panels, heading='Content'),
ObjectList(Page.settings_panels, heading='Settings'),
ObjectList(CommentableMixin.comments_panels, heading='Comments')
]
edit_handler = TabbedInterface(edit_handler_list)
search_fields = Page.search_fields + [
index.SearchField('get_heading_values', partial_match=True, boost=1),
index.SearchField('get_paragraph_values', partial_match=True),
]
def _get_child_block_values(self, block_type):
searchable_content = []
for block in self.body:
if block.block_type == block_type:
value = force_str(block.value)
searchable_content.append(get_text_for_indexing(value))
return searchable_content
def get_heading_values(self):
heading_values = self._get_child_block_values('heading')
return '\n'.join(heading_values)
def get_paragraph_values(self):
paragraph_values = self._get_child_block_values('paragraph')
return '\n'.join(paragraph_values)
def get_progress_enabled_section(self):
"""
Returning .first() will bypass any discrepancies in settings show_progress_bar=True
for sections
:return:
"""
return Section.objects.ancestor_of(self).type(Section).filter(
show_progress_bar=True).first()
def get_context(self, request):
context = super().get_context(request)
progress_enabled_section = self.get_progress_enabled_section()
if progress_enabled_section:
context.update({
'user_progress': progress_enabled_section.get_user_progress_dict(
request)
})
return context
def description(self):
for block in self.body:
if block.block_type == 'paragraph':
return block
return ''
def is_complete(self, request):
progress_manager = ProgressManager(request)
return progress_manager.is_article_complete(self)
@property
def top_level_section(self):
return self.get_ancestors().filter(depth=4).first().specific
@property
def offline_urls(self):
urls = [self.url] + collect_urls_from_streamfield(self.body)
if self.lead_image:
urls += get_all_renditions_urls(self.lead_image)
if self.image_icon:
urls += get_all_renditions_urls(self.image_icon)
return urls
class Meta:
abstract = True
verbose_name = _("article")
verbose_name_plural = _("articles")
class Article(AbstractArticle):
tags = ClusterTaggableManager(through='ArticleTaggedItem', blank=True)
content_panels = AbstractArticle.content_panels + [
MultiFieldPanel([
InlinePanel('recommended_articles',
label=_("Recommended Articles")),
],
heading='Recommended Content')
]
promote_panels = AbstractArticle.promote_panels + [
MultiFieldPanel([FieldPanel("tags"), ], heading='Metadata'),
]
edit_handler_list = [
ObjectList(content_panels, heading='Content'),
ObjectList(Page.settings_panels, heading='Settings'),
ObjectList(CommentableMixin.comments_panels, heading='Comments'),
ObjectList(promote_panels, heading='Promote'),
]
edit_handler = TabbedInterface(edit_handler_list)
def get_context(self, request):
context = super().get_context(request)
context['recommended_articles'] = [
recommended_article.article.specific
for recommended_article in self.recommended_articles.all() if recommended_article.article.live
]
return context
def serve(self, request):
response = super().serve(request)
if response.status_code == status.HTTP_200_OK:
User.record_article_read(request=request, article=self)
return response
class MiscellaneousIndexPage(Page):
parent_page_types = ['home.HomePage']
subpage_types = ['home.OfflineContentIndexPage']
class OfflineContentIndexPage(AbstractArticle):
template = 'home/article.html'
parent_page_types = ['home.MiscellaneousIndexPage']
subpage_types = []
class Meta:
verbose_name = 'Offline Content Index Page'
class BannerIndexPage(Page):
parent_page_types = ['home.HomePage']
subpage_types = ['home.BannerPage']
class BannerPage(Page, PageUtilsMixin):
parent_page_types = ['home.BannerIndexPage']
subpage_types = []
banner_image = models.ForeignKey(
'wagtailimages.Image',
related_name='+',
on_delete=models.PROTECT,
null=True, blank=True,
help_text=_('Image to display as the banner')
)
banner_link_page = models.ForeignKey(
Page, null=True, blank=True, related_name='banners',
on_delete=models.SET_NULL,
help_text=_('Optional page to which the banner will link to'))
content_panels = Page.content_panels + [
FieldPanel('banner_image'),
FieldPanel('banner_link_page'),
]
@property
def offline_urls(self):
return get_all_renditions_urls(self.banner_image)
class FooterIndexPage(Page):
parent_page_types = ['home.HomePage']
subpage_types = [
'home.Section', 'home.Article', 'home.PageLinkPage', 'questionnaires.Poll',
'questionnaires.Survey', 'questionnaires.Quiz',
]
@classmethod
def get_active_footers(cls):
footer_index_page = cls.objects.filter(locale=Locale.get_active()).first()
if footer_index_page:
footers = footer_index_page.get_children().live().specific()
return [footer for footer in footers if footer.get_page()]
return cls.objects.none()
def __str__(self):
return self.title
class FooterPage(Article, TitleIconMixin):
parent_page_types = []
subpage_types = []
template = 'home/article.html'
class Meta:
verbose_name = _("footer")
verbose_name_plural = _("footers")
class PageLinkPage(Page, PageUtilsMixin, TitleIconMixin):
parent_page_types = ['home.FooterIndexPage', 'home.Section']
subpage_types = []
show_in_menus_default = True
icon = models.ForeignKey(
Svg,
related_name='+',
null=True,
blank=True,
on_delete=models.SET_NULL,
)
image_icon = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
page = models.ForeignKey(Page, null=True, blank=True, related_name='page_link_pages', on_delete=models.PROTECT)
external_link = models.URLField(null=True, blank=True)
content_panels = Page.content_panels + [
SvgChooserPanel('icon'),
FieldPanel('image_icon'),
FieldPanel('page'),
FieldPanel('external_link'),
]
def get_page(self):
return self.page.specific if self.page and self.page.live else self
def get_icon(self):
icon = super().get_icon()
if not icon.url and self.page and self.page.live:
icon = self.page.specific.get_icon()
return icon
def get_url(self, request=None, current_site=None):
url = ''
if self.page and self.page.live:
url = self.page.specific.url
elif self.external_link:
url = self.external_link
return url
url = property(get_url)
@register_setting
class SiteSettings(BaseSetting):
logo = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
help_text="Upload an image file (.jpg, .png). The ideal size is 120px x 48px"
)
favicon = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
help_text="Upload an image file (.jpg, .png). The ideal size is 40px x 40px"
)
apple_touch_icon = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
help_text="Upload an image file (.jpg, .png) to be used as apple touch icon. "
"The ideal size is 120px x 120px"
)
show_only_translated_pages = models.BooleanField(
default=False,
help_text=_('When selecting this option, untranslated pages'
' will not be visible to the front end user'
' when viewing a child language of the site'))
fb_analytics_app_id = models.CharField(
verbose_name=_('Facebook Analytics App ID'),
max_length=25,
null=True,
blank=True,
help_text=_(
"The tracking ID to be used to view Facebook Analytics")
)
# Begin GA settings
# These are now obsolete and should be removed once it is deemed safe for these
# fields to be removed.
local_ga_tag_manager = models.CharField(
verbose_name=_('Local GA Tag Manager'),
max_length=255,
null=True,
blank=True,
help_text=_(
"Local GA Tag Manager tracking code (e.g GTM-XXX) to be used to "
"view analytics on this site only")
)
global_ga_tag_manager = models.CharField(
verbose_name=_('Global GA Tag Manager'),
max_length=255,
null=True,
blank=True,
help_text=_(
"Global GA Tag Manager tracking code (e.g GTM-XXX) to be used"
" to view analytics on more than one site globally")
)
local_ga_tracking_code = models.CharField(
verbose_name=_('Local GA Tracking Code'),
max_length=255,
null=True,
blank=True,
help_text=_(
"Local GA tracking code to be used to "
"view analytics on this site only")
)
global_ga_tracking_code = models.CharField(
verbose_name=_('Global GA Tracking Code'),
max_length=255,
null=True,
blank=True,
help_text=_(
"Global GA tracking code to be used"
" to view analytics on more than one site globally")
)
# End GA settings
social_media_link = StreamField(
[('social_media_link', SocialMediaLinkBlock())],
null=True,
blank=True,
use_json_field=True,
)
social_media_content_sharing_button = StreamField([
('social_media_content_sharing_button', SocialMediaShareButtonBlock()),
], null=True, blank=True)
media_file_size_threshold = models.IntegerField(
default=9437184,
help_text=_('Show warning if uploaded media file size is greater than this in bytes. Default is 9 MB'))
allow_anonymous_comment = models.BooleanField(default=False)
registration_survey = models.ForeignKey('questionnaires.Survey', null=True,
blank=True,
on_delete=models.SET_NULL)
# Obsolete - Web Light service discontinued Dec 2022
opt_in_to_google_web_light = models.BooleanField(default=False)
mtm_container_id = models.CharField(
verbose_name=_("Matomo Tag Manager container ID"),
max_length=255,
null=True,
blank=True,
help_text=_(
"Currently this feature only works on devices using JavaScript (e.g. basic"
" feature phones are not supported), and does not work with MNO zero-rating"
" or Meta Free Basics.")
)
panels = [
FieldPanel('logo'),
FieldPanel('favicon'),
FieldPanel('apple_touch_icon'),
MultiFieldPanel(
[
FieldPanel('show_only_translated_pages'),
],
heading="Multi Language",
),
MultiFieldPanel(
[
FieldPanel('fb_analytics_app_id'),
],
heading="Facebook Analytics Settings",
),
MultiFieldPanel(
[
MultiFieldPanel(
[
FieldPanel('social_media_link'),
],
heading="Social Media Footer Page", ),
],
heading="Social Media Page Links", ),
MultiFieldPanel(
[
MultiFieldPanel(
[
FieldPanel('social_media_content_sharing_button'),
],
heading="Social Media Content Sharing Buttons", ),
],
heading="Social Media Content Sharing Buttons", ),
MultiFieldPanel(
[
FieldPanel('media_file_size_threshold'),
],
heading="Media File Size Threshold",
),
MultiFieldPanel(
[
FieldPanel('allow_anonymous_comment'),
],
heading="Allow Anonymous Comment",
),
MultiFieldPanel(
[
FieldPanel('registration_survey'),
],
heading="Registration Settings",
),
MultiFieldPanel(
[
FieldPanel(
"mtm_container_id",
heading="Tag Manager container ID",
),
],
heading="Matomo",
),
]
@classmethod
def get_for_default_site(cls):
default_site = Site.objects.filter(is_default_site=True).first()
return cls.for_site(default_site)
def __str__(self):
return self.site.site_name
class Meta:
verbose_name = _('Site Settings')
verbose_name_plural = _('Site Settings')
class IogtFlatMenuItem(AbstractFlatMenuItem, TitleIconMixin):
menu = ParentalKey(
'wagtailmenus.FlatMenu',
on_delete=models.CASCADE,
related_name="iogt_flat_menu_items",
)
link_url = models.CharField(
verbose_name=_('link to a custom URL'),
max_length=255,
blank=True,
null=True,
help_text=_(
'If you are linking back to a URL on your own IoGT site, be sure to remove the domain and everything '
'before it. For example "http://sd.goodinternet.org/url/" should instead be "/url/".'
),
)
icon = models.ForeignKey(
Svg,
related_name='+',
null=True,
blank=True,
on_delete=models.SET_NULL,
help_text=_('If Page link is a section page and icon is blank then the section icon will be used. '
'Specify an icon here to override this.')
)
image_icon = models.ForeignKey(
'wagtailimages.Image',
on_delete=models.PROTECT,
related_name='+',
blank=True,
null=True
)
background_color = models.CharField(
max_length=255,
blank=True,
null=True,
help_text=_('The background color of the flat menu item on Desktop + Mobile')
)
font_color = models.CharField(
max_length=255,
blank=True,
null=True,
help_text=_('The font color of the flat menu item on Desktop + Mobile')
)
display_only_in_single_column_view = models.BooleanField(default=False)
panels = [
FieldPanel('link_page'),
FieldPanel('link_url', classname='red-help-text'),
FieldPanel('url_append'),
FieldPanel('link_text'),
FieldPanel('handle'),
FieldPanel('allow_subnav'),
SvgChooserPanel('icon'),
FieldPanel('image_icon'),
FieldPanel('background_color'),
FieldPanel('font_color'),
FieldPanel('display_only_in_single_column_view'),
]
def get_icon(self):
icon = super().get_icon()
if not icon.url and self.link_page and hasattr(self.link_page, 'get_icon'):
icon = self.link_page.get_icon()
return icon
def get_background_color(self):
theme_settings = globals_.theme_settings
return self.background_color or theme_settings.navbar_background_color
def get_font_color(self):
theme_settings = globals_.theme_settings
return self.font_color or theme_settings.navbar_font_color
def get_single_column_view(self):
return 'single-column-view' if self.display_only_in_single_column_view else ''
@deconstructible
class ImageValidator:
def __init__(self, width=None, height=None):
self.width = width
self.height = height
def __call__(self, image):
img = Image.objects.get(id=image)
w, h = get_image_dimensions(img.file)
ext = os.path.splitext(img.filename)[1]
valid_extensions = [".png"]
if not ext.lower() in valid_extensions:
raise ValidationError("Only .png images can be used")
if self.width is not None and w != self.width:
raise ValidationError(
f"({img.filename} - Width: {w}px, Height: {h}px) - The width image must be {self.width}px"
)
if self.height is not None and h != self.height:
raise ValidationError(
f"({img.filename} - Height: {h}px, Width: {w}px) - The height image must be {self.height}px "
)
class ManifestSettings(models.Model):
name = models.CharField(
max_length=255,
verbose_name=_("Name"),
help_text=_("Provide name that usually represents the name of the web application to user"),
)
short_name = models.CharField(
max_length=255,
verbose_name=_("Short name"),
help_text=_("Provide short name to be displayed, if there is not enough space to display full name"),
)
scope = models.CharField(
max_length=255,
verbose_name=_("Scope"),
help_text=_(
"Provide navigation scope to limit what web pages can be viewed "
"Example: 'https://www.iogt.com/<page-url>/' limits navigation "
"to <page-url> of https://www.iogt.com:"
),
)
start_url = models.CharField(
max_length=255,
verbose_name=_("Start URL"),
help_text=_(
"Start URL is the preferred URL that should be loaded "
"when the user launches the web application"
),
)
display = models.CharField(
max_length=255,
choices=[
('FULLSCREEN', 'fullscreen'),
('STANDALONE', 'standalone'),
('MINIMAL_UI', 'minimal-ui'),
('BROWSER', 'browser')
],
verbose_name=_("Browser UI"),
help_text=_(
"Determines the preferred display mode for the website. The possible values are: "
"'fullscreen', 'standalone', 'minimal-ui', 'browser'. A better choice would be to use standalone "
"as it looks great on mobile as well. For further information refer to: "
"https://developer.mozilla.org/en-US/docs/Web/Manifest/display#values"
),
)
background_color = models.CharField(
max_length=10,
verbose_name=_("Background color"),
help_text=_(
"Background color member defines a placeholder background color "
"for the application page to display before its stylesheet is loaded. (example: #FFF)"
),
)
theme_color = models.CharField(
max_length=10,
verbose_name=_("Theme color"),
help_text=_("Theme color defines the default theme color for the application (example: #493174)"),
)
description = models.CharField(
max_length=500,
verbose_name=_("Description"),
help_text=_("Provide description for application"),
)
language = models.CharField(
max_length=3,
choices=WAGTAIL_CONTENT_LANGUAGES,
default="en",
verbose_name=_("Language"),
help_text=_("Choose language"),
)
icon_96_96 = models.ForeignKey(
"wagtailimages.Image",
on_delete=models.SET_NULL,
null=True,
related_name="+",
verbose_name=_("Icon 96x96"),
help_text=_("Add PNG icon 96x96 px"),
validators=[ImageValidator(width=96, height=96)],
)
icon_512_512 = models.ForeignKey(
"wagtailimages.Image",
on_delete=models.SET_NULL,
null=True,
related_name="+",
verbose_name=_("Icon 512x512"),
help_text=_("Add PNG icon 512x512 px"),
validators=[ImageValidator(width=512, height=512)],
)
icon_192_192 = models.ForeignKey(
"wagtailimages.Image",
on_delete=models.SET_NULL,
null=True,
related_name="+",
verbose_name=_("Icon 192x192 (maskable)"),
help_text=_(
"Add PNG icon 192x192 px (maskable image can be created using https://maskable.app/)"
),
validators=[ImageValidator(width=192, height=192)],
)
panels = [
MultiFieldPanel(
[
FieldPanel("language"),