-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathviews.py
More file actions
2251 lines (2001 loc) · 83 KB
/
Copy pathviews.py
File metadata and controls
2251 lines (2001 loc) · 83 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
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 os
import re
import requests
from django.utils import timezone
from textwrap import dedent
from urllib.parse import urljoin
import structlog
from bs4 import BeautifulSoup
import chardet
from dateutil.parser import parse
from django.conf import settings
from django.db.models import Exists, OuterRef
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.cache import caches
from django.http import (
Http404,
HttpResponse,
HttpResponseNotFound,
HttpResponseRedirect,
HttpRequest,
)
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView
from core.templatetags.custom_static import large_static
from config.settings import ENABLE_DB_CACHE
from libraries.constants import LATEST_RELEASE_URL_PATH_STR
from libraries.mixins import VersionAlertMixin
from libraries.utils import (
legacy_path_transform,
generate_canonical_library_uri,
get_prioritized_library_view,
get_prioritized_version,
set_selected_boost_version,
modernize_boost_slug,
)
from versions.models import Version, docs_path_to_boost_name
from . import context_processors
from .mixins import V3Mixin, iter_v3_views
from .asciidoc import convert_adoc_to_html
from .boostrenderer import (
convert_img_paths,
extract_file_data,
get_content_from_s3,
get_meta_redirect_from_html,
get_s3_client,
)
from .constants import (
BadgeToken,
SourceDocType,
BOOST_LIB_PATH_RE,
BOOST_VERSION_REGEX,
SLACK_MEMBER_COUNT,
STATIC_CONTENT_EARLY_EXIT_PATH_PREFIXES,
)
from .htmlhelper import (
modernize_legacy_page,
convert_name_to_id,
modernize_preprocessor_docs,
remove_library_boostlook,
is_in_no_process_libs,
is_in_fully_modernized_libs,
is_in_no_wrapper_libs,
is_managed_content_type,
is_valid_modernize_value,
get_is_iframe_destination,
remove_unwanted,
minimize_uris,
add_canonical_link,
)
from .markdown import process_md
from .models import RenderedContent, SiteSettings
from .tasks import (
clear_rendered_content_cache_by_cache_key,
clear_rendered_content_cache_by_content_type,
refresh_content_from_s3,
save_rendered_content,
)
from libraries.models import Library, LibraryVersion, Tier
from news.models import Entry
from libraries.utils import (
get_commit_data_by_release_for_library,
commit_data_to_stats_bars,
)
from .mock_data import SharedResources # noqa: F401
logger = structlog.get_logger()
def BSLView(request):
file_path = os.path.join(settings.BASE_DIR, "static/license.txt")
if os.path.exists(file_path):
with open(file_path, "r") as file:
content = file.read()
return HttpResponse(content, content_type="text/plain")
else:
raise Http404("File not found.")
class CalendarView(V3Mixin, TemplateView):
template_name = "calendar.html"
v3_template_name = "v3/calendar.html"
def get_context_data(self, **kwargs):
ctx = {}
ctx["boost_calendar"] = settings.BOOST_CALENDAR
return ctx
def get_v3_context_data(self, **kwargs):
ctx = super().get_v3_context_data(**kwargs)
ctx["timezone"] = "America/Chicago"
return ctx
class BoostDevelopmentView(CalendarView):
template_name = "boost_development.html"
class CommunityView(V3Mixin, TemplateView):
template_name = "community.html"
v3_template_name = "v3/community.html"
def render_v3_response(self):
version_slug = self.kwargs.get("version_slug")
if not version_slug:
version_data = context_processors.selected_version(self.request)
target = (
version_data["selected_version"].slug
if version_data["selected_version_is_non_latest"]
else LATEST_RELEASE_URL_PATH_STR
)
return redirect("community-version", version_slug=target)
response = super().render_v3_response()
if version_slug != LATEST_RELEASE_URL_PATH_STR:
set_selected_boost_version(version_slug, response)
return response
def get_v3_context_data(self, **kwargs):
libraries_shown_in_community_page = 4
ctx = super().get_v3_context_data(**kwargs)
ctx["slack_member_count"] = SLACK_MEMBER_COUNT
ctx["help_options"] = [
{
"quote": "I'm stuck on an error",
"description": "Visit the CPPLang Slack for fast responses, quick debugging and real-time conversation",
"cta_text": f"Join Slack {SLACK_MEMBER_COUNT} members",
"cta_url": "https://cppalliance.org/slack/",
"author": {
"name": "Character Name",
"role": "Contributor",
"avatar_url": large_static(
"img/v3/community-page/avatar-beaver-character.png"
),
},
},
{
"quote": "I have a proposal for a new feature",
"description": "Propose libraries, participate in the formal review and submit major features on the mailing list",
"cta_text": "Subscribe now",
"cta_url": "https://lists.boost.org/mailman3/lists/boost.lists.boost.org/",
"author": {
"name": "Character Name",
"role": "Author",
"avatar_url": large_static(
"img/v3/community-page/avatar-mouse-character.png"
),
},
},
{
"quote": "I found a bug",
"description": "Find the library you're looking for on GitHub, follow the reporting template and let the author know",
"cta_text": "Report it on GitHub",
"cta_url": "https://github.com/boostorg/boost",
"author": {
"name": "Character Name",
"role": "Maintainer",
"avatar_url": large_static(
"img/v3/community-page/avatar-cheetah-character.png"
),
},
},
{
"quote": "I have a general question",
"description": "Post on Reddit and engage in casual chat with fellow Boost enthusiasts",
"cta_text": "Visit Reddit",
"cta_url": "https://www.reddit.com/user/boostlibs/",
"author": {
"name": "Character Name",
"role": "Contributor",
"avatar_url": large_static(
"img/v3/community-page/avatar-fish-character.png"
),
},
},
]
version_slug = self.kwargs.get("version_slug", LATEST_RELEASE_URL_PATH_STR)
selected_version = context_processors.selected_version(self.request)[
"selected_version"
]
# Subquery: does this library have any LibraryVersion at or before the
# selected Boost version?
existed_at_selected = LibraryVersion.objects.filter(
library=OuterRef("pk"),
version__name__lte=selected_version.name,
version__full_release=True,
)
site_settings = SiteSettings.load()
pinned_libs = list(
site_settings.pinned_community_libraries.filter(
Exists(existed_at_selected)
).prefetch_related("categories")
)
pinned_slugs = [lib.slug for lib in pinned_libs]
remaining_slots = libraries_shown_in_community_page - len(pinned_libs)
random_libs = (
list(
Library.objects.filter(tier=Tier.FLAGSHIP)
.filter(Exists(existed_at_selected))
.exclude(slug__in=pinned_slugs)
.prefetch_related("categories")
.order_by("?")[:remaining_slots]
)
if remaining_slots > 0
else []
)
flagship_libs = pinned_libs + random_libs
libraries = []
for lib in flagship_libs:
lv = (
LibraryVersion.objects.filter(
library=lib,
version__name__lte=selected_version.name,
version__full_release=True,
)
.order_by("-version__name")
.first()
)
if not lv:
# Fallback: show the highest C++ version the library supports.
lv = (
LibraryVersion.objects.filter(
library=lib,
version__full_release=True,
)
.order_by("-version__name")
.first()
)
cpp_version = (
f"C++ {lv.cpp_standard_minimum}"
if lv and lv.cpp_standard_minimum
else ""
)
libraries.append(
{
"name": lib.display_name_short,
"url": reverse(
"library-detail",
kwargs={
"version_slug": version_slug,
"library_slug": lib.slug,
},
),
"description": lib.description or "",
"categories": [cat.name for cat in lib.categories.all()],
"cpp_version": cpp_version,
}
)
ctx["libraries"] = libraries
ctx["libraries_url"] = self.request.build_absolute_uri(
reverse(
"libraries-list",
kwargs={
"version_slug": version_slug,
"library_view_str": "list",
},
)
)
recent_entries = (
Entry.objects.published()
.filter(deleted_at__isnull=True)
.select_related("author")
.order_by("-publish_at")[:4]
)
tag_display = {"blogpost": "Blog"}
ctx["posts"] = [
{
"title": entry.title,
"url": self.request.build_absolute_uri(entry.get_absolute_url()),
"date": entry.publish_at,
"category": (
tag_display.get(str(entry.tag).lower(), entry.tag.capitalize())
if entry.tag
else ""
),
# TODO: populate from DB once entry tags are persisted
"tag": "",
"author": {
"name": entry.author.display_name or entry.author.get_full_name(),
"avatar_url": entry.author.get_avatar_url(),
"role": "",
},
}
for entry in recent_entries
]
ctx["news_url"] = self.request.build_absolute_uri(reverse("news"))
ctx["contribute_url"] = self.request.build_absolute_uri(
"/doc/contributor-guide/contributors-faq.html"
)
ctx["install_card_pkg_managers"] = SharedResources.install_card_pkg_managers
ctx["install_card_system_install"] = SharedResources.install_card_system_install
ctx["create_account_card_body_html"] = (
"<p>Your contribution badges appear on your Boost profile with:</p>"
"<ul>"
"<li>Contribution statistics</li>"
"<li>Progress towards next badge</li>"
"<li>Recent activity feed</li>"
"</ul>"
)
ctx["create_account_card_preview_url"] = large_static(
"img/v3/community-page/community-create-account-preview.png"
)
now = timezone.now()
ctx["recent_threads_url"] = (
f"https://lists.boost.org/archives/list/boost@lists.boost.org/"
f"{now.year}/{now.month}/"
)
ctx["archive_url"] = (
"https://lists.boost.org/archives/list/boost@lists.boost.org/latest"
)
return ctx
class ClearCacheView(UserPassesTestMixin, View):
http_method_names = ["get"]
login_url = "/login/"
def get(self, request, *args, **kwargs):
"""Clears the redis and database cache for given parameters.
Params (must pass one):
content_type: The content type to clear. Example: "text/asciidoc"
cache_key: The cache key to clear.
"""
content_type = self.request.GET.get("content_type")
cache_key = self.request.GET.get("cache_key")
if not content_type and not cache_key:
return HttpResponseNotFound()
if content_type:
clear_rendered_content_cache_by_content_type.delay(content_type)
if cache_key:
clear_rendered_content_cache_by_cache_key.delay(cache_key)
return HttpResponse("Cache cleared")
def handle_no_permission(self):
"""Handle a user without permission to access this page."""
return HttpResponse(
"You do not have permission to access this page.", status=403
)
def test_func(self):
"""Check if the user is a staff member"""
return self.request.user.is_staff
class MarkdownTemplateView(TemplateView):
template_name = "markdown_template.html"
content_dir = settings.BASE_CONTENT
markdown_local = None
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
self.markdown_local = kwargs.get("markdown_local", None)
def build_path(self):
"""
Builds the path from URL kwargs
"""
content_path = self.kwargs.get("content_path")
updated_legacy_path = legacy_path_transform(content_path)
if updated_legacy_path != content_path:
return redirect(
reverse(
self.request.resolver_match.view_name,
kwargs={"content_path": updated_legacy_path},
)
)
print(self.markdown_local)
if self.markdown_local:
# Can we find a file with this path?
path = (
f"{settings.TEMPLATES[0]['DIRS'][0]}/markdown/{self.markdown_local}.md"
)
if os.path.isfile(path):
return path
if not content_path:
return
# If the request includes the file extension, return that
if content_path[-5:] == ".html" or content_path[-3:] == ".md":
return f"{self.content_dir}/{content_path}"
# Trim any trailing slashes
if content_path[-1] == "/":
content_path = content_path[:-1]
# Can we find a markdown file with this path?
path = f"{self.content_dir}/{content_path}.md"
# Note: The get() method also checks isfile(), but since we need to try multiple
# paths/extensions, we need to call it here as well.
if os.path.isfile(path):
return path
# Can we find an HTML file with this path?
path = f"{self.content_dir}/{content_path}.html"
if os.path.isfile(path):
return path
# Can we find an index file with this path?
path = f"{self.content_dir}/{content_path}/index.html"
if os.path.isfile(path):
return path
# If we get here, there is nothing else for us to try.
return
def get(self, request, *args, **kwargs):
"""
Verifies the file and returns the frontmatter and content
"""
path = self.build_path()
# Avoids a TypeError from os.path.isfile if there is no path
if not path:
logger.info(
"markdown_template_view_no_valid_path",
content_path=kwargs.get("content_path"),
status_code=404,
)
raise Http404("Markdown not found")
if not os.path.isfile(path):
logger.info(
"markdown_template_view_no_valid_file",
content_path=kwargs.get("content_path"),
path=path,
status_code=404,
)
raise Http404("Post not found")
context = {}
context["frontmatter"], context["content"] = process_md(path)
logger.info(
"markdown_template_view_success",
content_path=kwargs.get("content_path"),
path=path,
status_code=200,
)
return self.render_to_response(context)
class TermsOfUseView(V3Mixin, MarkdownTemplateView):
"""Renders the v3 Terms of Use page when the v3 flag is active, else markdown template."""
v3_template_name = "v3/terms_of_use.html"
def get_v3_context_data(self, **kwargs):
return {"last_updated": "2024-02-22"}
class PrivacyPolicyView(V3Mixin, MarkdownTemplateView):
"""Renders the v3 Privacy Policy page when the v3 flag is active, else markdown template."""
v3_template_name = "v3/privacy_policy.html"
def get_v3_context_data(self, **kwargs):
return {"last_updated": "2024-02-17"}
class LearnPageView(V3Mixin, TemplateView):
v3_template_name = "v3/learn_page.html"
def get_v3_context_data(self, **kwargs):
ctx = super().get_v3_context_data(**kwargs)
ctx["learn_card_data"] = [
{
"title": "I want to learn:",
"text": "How to install Boost, use its libraries, build projects, and get help when you need it.",
"links": [
{
"label": "Explore common use cases",
"url": "https://www.example.com",
},
{"label": "Build with CMake", "url": "https://www.example.com"},
{"label": "Visit the FAQ", "url": "https://www.example.com"},
],
"url": "https://www.example.com",
"label": "Learn more about Boost",
"image_src": large_static("/img/v3/learn-page/learn-cheetah.png"),
"mobile_image_src": large_static(
"/img/v3/learn-page/cheetah-mobile.png"
),
},
{
"title": "I want to learn:",
"text": "How to install Boost, use its libraries, build projects, and get help when you need it.",
"links": [
{
"label": "Explore common use cases",
"url": "https://www.example.com",
},
{"label": "Build with CMake", "url": "https://www.example.com"},
{"label": "Visit the FAQ", "url": "https://www.example.com"},
],
"url": "https://www.example.com",
"label": "Learn more about Boost",
"image_src": large_static("img/v3/learn-page/learn-octopus.png"),
"mobile_image_src": large_static(
"/img/v3/learn-page/octopus-mobile.png"
),
},
]
demo_cards = [
{
"title": "Get help",
"description": "Tap into quick answers, networking, and chat with 24,000+ members.",
"cta_label": "Start here",
"cta_href": reverse("community"),
},
{
"title": "Documentation",
"description": "Browse library docs, examples, and release notes in one place.",
"cta_label": "View docs",
"cta_href": reverse("docs"),
},
{
"title": "Community",
"description": "Mailing lists, GitHub, and community guidelines for contributors.",
"cta_label": "Join",
"cta_href": reverse("community"),
},
{
"title": "Releases",
"description": "Latest releases, download links, and release notes.",
"cta_label": "Download",
"cta_href": reverse("releases-most-recent"),
},
{
"title": "Libraries",
"description": "Explore the full catalog of Boost C++ libraries with docs and metadata.",
"cta_label": "Browse libraries",
"cta_href": reverse("libraries"),
},
{
"title": "News",
"description": "Blog posts, announcements, and community news from the Boost project.",
"cta_label": "Read news",
"cta_href": reverse("news"),
},
{
"title": "Getting started",
"description": "Step-by-step guides to build and use Boost in your projects.",
"cta_label": "Get started",
"cta_href": reverse("getting-started"),
},
{
"title": "Resources",
"description": "Learning resources, books, and other materials for Boost users.",
"cta_label": "View resources",
"cta_href": reverse("resources"),
},
{
"title": "Calendar",
"description": "Community events, meetings, and review schedule.",
"cta_label": "View calendar",
"cta_href": reverse("calendar"),
},
{
"title": "Donate",
"description": "Support the Boost Software Foundation and open-source C++.",
"cta_label": "Donate",
"cta_href": reverse("donate"),
},
]
ctx["library_cards"] = demo_cards
ctx["why_boost_cards"] = demo_cards[:6]
ctx["calendar_card"] = {
"title": "Boost is released three times a year",
"text": "Each release has updates to existing libraries, and any new libraries that have passed the rigorous acceptance process.",
"primary_button_url": "www.example.com",
"primary_button_label": "View the Release Calendar",
"secondary_button_url": "www.example.com",
"secondary_button_label": "Secondary Button",
"image": large_static("/img/v3/demo-page/calendar.png"),
}
ctx["info_card"] = {
"title": "How we got here",
"text": "Since 1998, Boost has been where C++ innovation happens. What started with three developers has grown into the foundation of modern C++ development.",
"primary_button_url": "www.example.com",
"primary_button_label": "Explore Our History",
}
ctx["post_cards_data"] = {
"heading": "Posts from the Boost Community",
"view_all_url": "#",
"view_all_label": "View All Posts",
"variant": "Content Card",
"posts": SharedResources.demo_posts[0:4],
}
ctx["boost_community_data"] = {
"heading": "The Boost community",
"view_all_url": "#",
"view_all_label": "Explore the community",
"posts": 3
* [
{
"title": "A talk by Richard Thomson at the Utah C++ Programmers Group",
"description": "Lorem Ispum Sum Delores",
"url": "#",
"date": "03/03/2025",
"category": "Issues",
"tag": "beast",
"author": {
"name": "Richard Thomson",
"role": "Contributor",
"show_badge": True,
"avatar_url": large_static("img/v3/demo-page/avatar.png"),
},
"cta_url": "#",
"cta_label": "Learn More",
}
],
}
return ctx
class ContentNotFoundException(Exception):
pass
class BaseStaticContentTemplateView(TemplateView):
template_name = "adoc_content.html"
allowed_db_save_types = {"text/asciidoc"}
html_content_types = {"text/html", "text/html; charset=utf-8"}
def get(self, request, *args, **kwargs):
"""Return static content that originates in S3.
The result is cached in a couple of different places to avoid multiple
roundtrips to S3.
Any valid S3 key to the S3 bucket specified in settings can be returned by
this view. Pages like the Help page are stored in S3 and rendered via
this view, for example.
See the *_static_config.json files for URL mappings to specific S3 keys.
"""
content_path = self.kwargs.get("content_path")
# Exit early for paths we know we don't want to handle here. We know that these
# paths should have been resolved earlier by the URL router, and if we return
# a 404 here redirecting will be handled by the webserver configuration.
if content_path.startswith(STATIC_CONTENT_EARLY_EXIT_PATH_PREFIXES):
raise Http404("Content not found")
updated_legacy_path = legacy_path_transform(content_path)
if updated_legacy_path != content_path:
return redirect(
reverse(
self.request.resolver_match.view_name,
kwargs={"content_path": updated_legacy_path},
)
)
# For some reason, if a user cancels a social signup (cancelling a GitHub
# signup, for example), the redirect URL comes through this view, so we
# must manually redirect it.
if "accounts/github/login/callback" in content_path:
return redirect(content_path)
try:
content_path = self.get_library_content_path(content_path)
self.content_dict = self.get_content(content_path)
# If the content is an HTML file with a meta redirect, redirect the user.
if self.content_dict.get("redirect"):
return redirect(self.content_dict.get("redirect"))
except ContentNotFoundException:
logger.info(f"get_content_from_s3_view_not_in_cache {content_path} 404")
raise Http404("Content not found")
return super().get(request, *args, **kwargs)
def get_library_content_path(self, content_path):
# here we handle the translation from "release/..." to /$version_x_y_z/...
if content_path.startswith(f"{LATEST_RELEASE_URL_PATH_STR}/"):
version = Version.objects.most_recent()
content_path = content_path.replace(
f"{LATEST_RELEASE_URL_PATH_STR}/", f"{version.stripped_boost_url_slug}/"
)
return content_path
def cache_result(self, static_content_cache, cache_key, result):
static_content_cache.set(cache_key, result)
def get_content(self, content_path):
"""Return content from cache, database, or S3."""
static_content_cache = caches["static_content"]
cache_key = f"static_content_{content_path}"
result = self.get_from_cache(static_content_cache, cache_key)
if result is None:
result = self.get_from_database(cache_key)
if result:
# When we get a result from the database, we refresh its content
refresh_content_from_s3.delay(content_path, cache_key)
if result is None:
result = self.get_from_s3(content_path)
if result:
# Save to database
self.save_to_database(cache_key, result)
# Cache the result
self.cache_result(static_content_cache, cache_key, result)
if result is None:
logger.info(
"get_content_from_s3_view_no_valid_object",
key=content_path,
status_code=404,
)
raise ContentNotFoundException("Content not found")
return result
def get_context_data(self, **kwargs):
"""Return the content and content type for the template.
In some cases, the content type is changed depending on the context.
"""
context = super().get_context_data(**kwargs)
content_type = self.content_dict.get("content_type")
content = self.content_dict.get("content")
if content_type == "text/asciidoc":
content_type = "text/html"
context.update(
{
"content": content,
"content_type": content_type,
"selected_version": self.get_selected_version(),
}
)
logger.info(
"get_content_from_s3_view_success", key=self.kwargs.get("content_path")
)
return context
def get_selected_version(self) -> Version | None:
content_path = self.kwargs.get("content_path")
boost_name = docs_path_to_boost_name(content_path)
if not boost_name:
return None
try:
version = Version.objects.get(name=boost_name)
except Version.DoesNotExist:
version = None
return version
def get_from_cache(self, static_content_cache, cache_key):
cached_result = static_content_cache.get(cache_key)
return cached_result if cached_result else None
def get_from_database(self, cache_key) -> dict[str, str | bytes] | None:
rendered_content_cache_time = 2628288
dev_docs = ["static_content_develop/", "static_content_master/"]
for substring in dev_docs:
if substring in cache_key:
rendered_content_cache_time = 3600
now = timezone.now()
start_time = now - timezone.timedelta(seconds=rendered_content_cache_time)
try:
content_obj = RenderedContent.objects.filter(modified__gte=start_time).get(
cache_key=cache_key
)
return {
"content": content_obj.content_html.encode("utf-8"),
"content_type": content_obj.content_type,
"updated": content_obj.modified,
}
except RenderedContent.DoesNotExist:
return None
def get_from_s3(self, content_path):
result = get_content_from_s3(key=content_path)
if not result:
return None
content = result.get("content")
content_type = result.get("content_type")
result["source_content_type"] = None
# Check if the content is an asciidoc file. If so, convert it to HTML.
# todo: confirm necessary: not clear where this is still needed, as the
# content type for library docs is set to text/html, maybe descriptions and
# release notes
if content_type == "text/asciidoc":
result["content"] = self.convert_adoc_to_html(content)
# Check if the content is an HTML file. If so, check for a meta redirect.
if content_type.startswith("text/html"):
has_redirect = get_meta_redirect_from_html(content)
if not has_redirect and "spirit-nav".encode() not in content:
# Yes, this is a little gross, but it's the best we could think of.
# The 'assert', 'url' libraries (1.89) are examples that set this,
# is essentially everything that's not an antoradoc. Perfect is the
# enemy of good enough.
result["source_content_type"] = SourceDocType.ASCIIDOC
return result
def get_template_names(self):
content_type = self.content_dict.get("content_type")
if content_type == "text/asciidoc":
return [self.template_name]
return []
def render_to_response(self, context, **response_kwargs):
"""Return the HTML response with a template, or just the content directly."""
if self.get_template_names():
content = self.process_content(context["content"])
context["content"] = content
return super().render_to_response(context, **response_kwargs)
content = self.process_content(context["content"])
return HttpResponse(content, content_type=context["content_type"])
def save_to_database(self, cache_key, result):
"""Saves the rendered asciidoc content to the database."""
content_type = result.get("content_type")
if content_type in self.allowed_db_save_types:
last_updated_at_raw = result.get("last_updated_at")
last_updated_at = (
parse(last_updated_at_raw) if last_updated_at_raw else None
)
save_rendered_content.delay(
cache_key,
content_type,
result["content"],
last_updated_at=last_updated_at,
)
def convert_adoc_to_html(self, content):
"""Renders asciidoc content to HTML."""
return convert_adoc_to_html(content)
def process_content(self, content):
"""No op, override in children if required."""
return content
class StaticContentTemplateView(BaseStaticContentTemplateView):
def get(self, request, content_path, *args, **kwargs):
# filter out direct access to the doc paths
path_regexes = [
re.compile(rf"^{BOOST_VERSION_REGEX}/doc/html/.+$"),
re.compile(rf"^{BOOST_VERSION_REGEX}/libs/.+$"),
]
path_match = any(regex.match(content_path) for regex in path_regexes)
if path_match:
raise Http404("Content not found")
return super().get(request, *args, **kwargs)
def process_content(self, content):
"""Process the content we receive from S3"""
content_html = self.content_dict.get("content")
content_type = self.content_dict.get("content_type")
content_key = self.content_dict.get("content_key")
# Replace relative image paths will fully-qualified ones so they will render
if content_type == "text/html" or content_type == "text/asciidoc":
# Prefix the new URL path with "/images" so it routes through
# our ImageView class
url_parts = ["/images"]
if content_key:
# Get the path from the S3 key by stripping the filename from the S3 key
directory = os.path.dirname(content_key)
url_parts.append(directory.lstrip("/"))
# Generate the replacement path to the image
s3_path = "/".join(url_parts)
# Process the HTML to replace the image paths
content = convert_img_paths(str(content_html), s3_path)
return content
def normalize_boost_doc_path(content_path: str) -> str:
content_path = content_path.lstrip("boost_")
if content_path.startswith(LATEST_RELEASE_URL_PATH_STR):
version = Version.objects.most_recent()
content_path = content_path.replace(
f"{LATEST_RELEASE_URL_PATH_STR}/", f"{version.stripped_boost_url_slug}/"
)
# Special case for Boost.Process
if content_path == "1_88_0/doc/html/process.html":
content_path = "1_88_0/libs/process/doc/html/index.html"
# Match versioned library paths
matches = BOOST_LIB_PATH_RE.match(content_path)
if matches:
groups = matches.groups()
if groups and not groups[0]:
content_path = f"boost_{content_path}"
return f"/archives/{content_path}"
class DocLibsTemplateView(VersionAlertMixin, BaseStaticContentTemplateView):
allowed_db_save_types = {
"text/asciidoc",
"text/html",
"text/html; charset=utf-8",
"text/css; charset=utf-8",
}
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
old_version_slug = self.kwargs.get("content_path").split("/", 1)[0]
version_slug = modernize_boost_slug(old_version_slug)
set_selected_boost_version(version_slug, response)
return response
def get_from_s3(self, content_path):
legacy_url = normalize_boost_doc_path(content_path)
return super().get_from_s3(legacy_url)
def process_content(self, content: bytes):
"""Replace page header with the local one."""
context = super().get_context_data()
content_type = self.content_dict.get("content_type")
modernize = self.request.GET.get("modernize", "med").lower()
if (
not is_managed_content_type(content_type)
or not is_valid_modernize_value(modernize)
or get_is_iframe_destination(self.request.headers)
):
return content
# everything from this point should be html
req_uri = self.request.build_absolute_uri()
canonical_uri = generate_canonical_library_uri(req_uri)
soup = BeautifulSoup(content, "html.parser")
# handle libraries that expect no processing
if is_in_no_process_libs(self.request.path):
soup = self._required_content_changes(soup, canonical_uri=canonical_uri)
return str(soup)
soup = self._required_modernization_changes(soup)
context.update(
{
"content": str(soup),
"canonical_uri": canonical_uri if canonical_uri != req_uri else None,
}
)
template_name = "original_docs.html"
if is_in_fully_modernized_libs(self.request.path):
# prepare a fully modernized version in an iframe
logger.info(f"fully modernized lib {self.request.path=}")
context_update = self._fully_modernize_content(
soup, self.establish_source_content_type(self.request.path)
)
context.update(context_update)
template_name = "docsiframe.html"