Debian Codegraph @

sphinxext/opengraph/__init__.py

raw
1 from __future__ import annotations
2
3 import os
4 import posixpath
5 from pathlib import Path
6 from typing import TYPE_CHECKING
7 from urllib.parse import urljoin, urlparse, urlsplit, urlunsplit
8
9 from docutils import nodes
10
11 from sphinxext.opengraph._description_parser import get_description
12 from sphinxext.opengraph._meta_parser import get_meta_description
13 from sphinxext.opengraph._title_parser import get_title
14
15 try:
16 from types import NoneType
17 except ImportError:
18 NoneType = type(None)
19
20 if TYPE_CHECKING:
21 from typing import Any
22
23 from sphinx.application import Sphinx
24 from sphinx.builders import Builder
25 from sphinx.config import Config
26 from sphinx.environment import BuildEnvironment
27 from sphinx.util.typing import ExtensionMetadata
28
29 try:
30 from sphinxext.opengraph._social_cards import (
31 DEFAULT_SOCIAL_CONFIG,
32 create_social_card,
33 )
34 except ImportError:
35 print('matplotlib is not installed, social cards will not be generated')
36 create_social_card = None
37 DEFAULT_SOCIAL_CONFIG = {}
38
39 __version__ = '0.13.0'
40 version_info = (0, 13, 0)
41
42 DEFAULT_DESCRIPTION_LENGTH = 200
43 DEFAULT_DESCRIPTION_LENGTH_SOCIAL_CARDS = 160
44 DEFAULT_PAGE_LENGTH_SOCIAL_CARDS = 80
45
46 # A selection from https://www.iana.org/assignments/media-types/media-types.xhtml#image
47 IMAGE_MIME_TYPES = {
48 'gif': 'image/gif',
49 'apng': 'image/apng',
50 'webp': 'image/webp',
51 'jpeg': 'image/jpeg',
52 'jpg': 'image/jpeg',
53 'png': 'image/png',
54 'bmp': 'image/bmp',
55 'heic': 'image/heic',
56 'heif': 'image/heif',
57 'tiff': 'image/tiff',
58 }
59
60
61 def html_page_context(
62 app: Sphinx,
63 pagename: str,
64 templatename: str,
65 context: dict[str, Any],
66 doctree: nodes.document,
67 ) -> None:
68 if app.builder.name == 'epub':
69 return
70
71 if doctree:
72 context['metatags'] += get_tags(
73 context,
74 doctree,
75 srcdir=app.srcdir,
76 outdir=app.outdir,
77 config=app.config,
78 builder=app.builder,
79 env=app.env,
80 )
81
82
83 def get_tags(
84 context: dict[str, Any],
85 doctree: nodes.document,
86 *,
87 srcdir: str | Path,
88 outdir: str | Path,
89 config: Config,
90 builder: Builder,
91 env: BuildEnvironment,
92 ) -> str:
93 # Get field lists for per-page overrides
94 fields = context['meta']
95 if fields is None:
96 fields = {}
97
98 if 'ogp_disable' in fields:
99 return ''
100
101 tags = {}
102 meta_tags = {} # For non-og meta tags
103
104 # Set length of description
105 try:
106 desc_len = int(
107 fields.get('ogp_description_length', config.ogp_description_length)
108 )
109 except ValueError:
110 desc_len = DEFAULT_DESCRIPTION_LENGTH
111
112 # Get the title and parse any html in it
113 title, title_excluding_html = get_title(context['title'])
114
115 # Parse/walk doctree for metadata (tag/description)
116 description = get_description(doctree, desc_len, {title, title_excluding_html})
117
118 # title tag
119 tags['og:title'] = title
120
121 # type tag
122 tags['og:type'] = config.ogp_type
123
124 if not config.ogp_site_url and os.getenv('READTHEDOCS'):
125 ogp_site_url = ambient_site_url()
126 else:
127 ogp_site_url = config.ogp_site_url
128
129 # If ogp_canonical_url is not set, default to the value of ogp_site_url
130 ogp_canonical_url = config.ogp_canonical_url or ogp_site_url
131
132 # url tag
133 # Get the URL of the specific page
134 page_url = urljoin(ogp_canonical_url, builder.get_target_uri(context['pagename']))
135 tags['og:url'] = page_url
136
137 # site name tag, False disables, default to project if ogp_site_name not
138 # set.
139 if config.ogp_site_name is False:
140 site_name = None
141 elif config.ogp_site_name is None:
142 site_name = config.project
143 else:
144 site_name = config.ogp_site_name
145 if site_name:
146 tags['og:site_name'] = site_name
147
148 # description tag
149 if description:
150 tags['og:description'] = description
151
152 if config.ogp_enable_meta_description and not get_meta_description(
153 context['metatags']
154 ):
155 meta_tags['description'] = description
156
157 # image tag
158 # Get basic values from config
159 if 'og:image' in fields:
160 image_url = fields['og:image']
161 ogp_use_first_image = False
162 ogp_image_alt = fields.get('og:image:alt')
163 fields.pop('og:image', None)
164 else:
165 image_url = config.ogp_image
166 ogp_use_first_image = config.ogp_use_first_image
167 ogp_image_alt = fields.get('og:image:alt', config.ogp_image_alt)
168
169 # Decide whether to add social media card images for each page.
170 # Only do this as a fallback if the user hasn't given any configuration
171 # to add other images.
172 config_social = DEFAULT_SOCIAL_CONFIG.copy()
173 social_card_user_options = config.ogp_social_cards or {}
174 config_social.update(social_card_user_options)
175 if (
176 not (image_url or ogp_use_first_image)
177 and config_social.get('enable') is not False
178 and create_social_card is not None
179 ):
180 image_url = social_card_for_page(
181 config_social=config_social,
182 site_name=site_name,
183 title=title,
184 description=description,
185 pagename=context['pagename'],
186 ogp_site_url=ogp_site_url,
187 ogp_canonical_url=ogp_canonical_url,
188 srcdir=srcdir,
189 outdir=outdir,
190 config=config,
191 env=env,
192 )
193 ogp_use_first_image = False
194
195 # Alt text is taken from description unless given
196 if 'og:image:alt' in fields:
197 ogp_image_alt = fields.get('og:image:alt')
198 else:
199 ogp_image_alt = description
200
201 # If the social card objects have been added we add special metadata for them
202 # These are the dimensions *in pixels* of the card
203 # They were chosen by looking at the image pixel dimensions on disk
204 tags['og:image:width'] = '1146'
205 tags['og:image:height'] = '600'
206 meta_tags['twitter:card'] = 'summary_large_image'
207
208 fields.pop('og:image:alt', None)
209
210 first_image = None
211 if ogp_use_first_image:
212 # Use the first image that is defined in the current page
213 first_image = doctree.next_node(nodes.image)
214 if (
215 first_image
216 and Path(first_image.get('uri', '')).suffix[1:].lower() in IMAGE_MIME_TYPES
217 ):
218 image_url = first_image['uri']
219 ogp_image_alt = first_image.get('alt', None)
220 else:
221 first_image = None
222
223 if image_url:
224 # temporarily disable relative image paths with field lists
225 if 'og:image' not in fields:
226 image_url_parsed = urlparse(image_url)
227 if not image_url_parsed.scheme:
228 # Relative image path detected, relative to the source. Make absolute.
229 if first_image: # NoQA: SIM108
230 root = page_url
231 else: # ogp_image is set
232 # ogp_image is defined as being relative to the site root.
233 # This workaround is to keep that functionality from breaking.
234 root = ogp_site_url
235
236 image_url = urljoin(root, image_url_parsed.path)
237 tags['og:image'] = image_url
238
239 # Add image alt text (either provided by config or from site_name)
240 if isinstance(ogp_image_alt, str):
241 tags['og:image:alt'] = ogp_image_alt
242 elif ogp_image_alt is None and site_name:
243 tags['og:image:alt'] = site_name
244 elif ogp_image_alt is None and title:
245 tags['og:image:alt'] = title
246
247 # arbitrary tags and overrides
248 tags.update({k: v for k, v in fields.items() if k.startswith('og:')})
249
250 return (
251 '\n'.join(
252 [make_tag(p, c) for p, c in tags.items()]
253 + [make_tag(p, c, 'name') for p, c in meta_tags.items()]
254 + list(config.ogp_custom_meta_tags)
255 )
256 + '\n'
257 )
258
259
260 def ambient_site_url() -> str:
261 # readthedocs addons sets the READTHEDOCS_CANONICAL_URL variable
262 if rtd_canonical_url := os.getenv('READTHEDOCS_CANONICAL_URL'):
263 parse_result = urlsplit(rtd_canonical_url)
264 else:
265 msg = 'ReadTheDocs did not provide a valid canonical URL!'
266 raise RuntimeError(msg)
267
268 # Grab root url from canonical url
269 return urlunsplit(
270 (parse_result.scheme, parse_result.netloc, parse_result.path, '', '')
271 )
272
273
274 def social_card_for_page(
275 config_social: dict[str, bool | str],
276 site_name: str,
277 title: str,
278 description: str,
279 pagename: str,
280 ogp_site_url: str,
281 ogp_canonical_url: str,
282 *,
283 srcdir: str | Path,
284 outdir: str | Path,
285 config: Config,
286 env: BuildEnvironment,
287 ) -> str:
288 # Description
289 description_max_length = config_social.get(
290 'description_max_length', DEFAULT_DESCRIPTION_LENGTH_SOCIAL_CARDS - 3
291 )
292 if len(description) > description_max_length:
293 description = description[:description_max_length].strip() + '...'
294
295 # Page title
296 pagetitle = title
297 if len(pagetitle) > DEFAULT_PAGE_LENGTH_SOCIAL_CARDS:
298 pagetitle = pagetitle[:DEFAULT_PAGE_LENGTH_SOCIAL_CARDS] + '...'
299
300 # Site URL
301 site_url = config_social.get('site_url', True)
302 if site_url is True:
303 url_text = ogp_canonical_url.split('://')[-1]
304 elif isinstance(site_url, str):
305 url_text = site_url
306
307 # Plot an image with the given metadata to the output path
308 image_path = create_social_card(
309 config_social,
310 site_name,
311 pagetitle,
312 description,
313 url_text,
314 pagename,
315 srcdir=srcdir,
316 outdir=outdir,
317 env=env,
318 html_logo=config.html_logo,
319 )
320
321 # Link the image in our page metadata
322 return posixpath.join(ogp_site_url, image_path.as_posix())
323
324
325 def make_tag(property: str, content: str, type_: str = 'property') -> str:
326 # Parse quotation, so they won't break html tags if smart quotes are disabled
327 content = content.replace('"', '"')
328 return f'<meta {type_}="{property}" content="{content}" />'
329
330
331 def setup(app: Sphinx) -> ExtensionMetadata:
332 # ogp_site_url="" allows relative by default, even though it's not
333 # officially supported by OGP.
334 app.add_config_value('ogp_site_url', '', 'html', types=frozenset({str}))
335 app.add_config_value('ogp_canonical_url', '', 'html', types=frozenset({str}))
336 app.add_config_value(
337 'ogp_description_length',
338 DEFAULT_DESCRIPTION_LENGTH,
339 'html',
340 types=frozenset({int}),
341 )
342 app.add_config_value('ogp_image', None, 'html', types=frozenset({str, NoneType}))
343 app.add_config_value(
344 'ogp_image_alt', None, 'html', types=frozenset({str, bool, NoneType})
345 )
346 app.add_config_value('ogp_use_first_image', False, 'html', types=frozenset({bool}))
347 app.add_config_value('ogp_type', 'website', 'html', types=frozenset({str}))
348 app.add_config_value(
349 'ogp_site_name', None, 'html', types=frozenset({str, bool, NoneType})
350 )
351 app.add_config_value(
352 'ogp_social_cards', None, 'html', types=frozenset({dict, NoneType})
353 )
354 app.add_config_value(
355 'ogp_custom_meta_tags', (), 'html', types=frozenset({list, tuple})
356 )
357 app.add_config_value(
358 'ogp_enable_meta_description', True, 'html', types=frozenset({bool})
359 )
360
361 # Main Sphinx OpenGraph linking
362 app.connect('html-page-context', html_page_context)
363
364 return {
365 'version': __version__,
366 'env_version': 1,
367 'parallel_read_safe': True,
368 'parallel_write_safe': True,
369 }