-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathviews.py
303 lines (251 loc) · 9.14 KB
/
views.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
"""Views for the embed app."""
import json
import re
import structlog
from django.template.defaultfilters import slugify
from docutils.nodes import make_id
from pyquery import PyQuery as PQ # noqa
from rest_framework import status
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from readthedocs.api.mixins import CDNCacheTagsMixin, EmbedAPIMixin
from readthedocs.api.v2.permissions import IsAuthorizedToViewVersion
from readthedocs.api.v3.permissions import HasEmbedAPIAccess
from readthedocs.builds.constants import EXTERNAL
from readthedocs.core.resolver import resolve
from readthedocs.embed.utils import clean_references, recurse_while_none
from readthedocs.storage import build_media_storage
log = structlog.get_logger(__name__)
def escape_selector(selector):
"""Escape special characters from the section id."""
regex = re.compile(r'(!|"|#|\$|%|\'|\(|\)|\*|\+|\,|\.|\/|\:|\;|\?|@)')
ret = re.sub(regex, r'\\\1', selector)
return ret
class EmbedAPI(EmbedAPIMixin, CDNCacheTagsMixin, APIView):
# pylint: disable=line-too-long
"""
Embed a section of content from any Read the Docs page.
Returns headers and content that matches the queried section.
### Arguments
We support two different ways to query the API:
* project (required)
* version (required)
* doc or path (required)
* section
or:
* url (with fragment) (required)
### Example
- GET https://readthedocs.org/api/v2/embed/?project=requestsF&version=latest&doc=index§ion=User%20Guide&path=/index.html
- GET https://readthedocs.org/api/v2/embed/?url=https://docs.readthedocs.io/en/latest/features.html%23github-bitbucket-and-gitlab-integration
# Current Request
""" # noqa
permission_classes = [HasEmbedAPIAccess, IsAuthorizedToViewVersion]
renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
@property
def external(self):
# Always return False because APIv2 does not support external domains
return False
def get(self, request):
"""Handle the get request."""
project = self._get_project()
version = self._get_version()
url = request.GET.get('url')
path = request.GET.get('path', '')
doc = request.GET.get('doc')
section = request.GET.get('section')
if url:
unresolved = self.unresolved_url
path = unresolved.filename
section = unresolved.parsed_url.fragment
elif not path and not doc:
return Response(
{
'error': (
'Invalid Arguments. '
'Please provide "url" or "section" and "path" GET arguments.'
)
},
status=status.HTTP_400_BAD_REQUEST
)
# Generate the docname from path
# by removing the ``.html`` extension and trailing ``/``.
if path:
doc = re.sub(r'(.+)\.html$', r'\1', path.strip('/'))
response = do_embed(
project=project,
version=version,
doc=doc,
section=section,
path=path,
url=url,
)
if not response:
return Response(
{
'error': (
"Can't find content for section: "
f"doc={doc} path={path} section={section}"
)
},
status=status.HTTP_404_NOT_FOUND
)
log.info(
'EmbedAPI successful response.',
project_slug=project.slug,
version_slug=version.slug,
doc=doc,
section=section,
path=path,
url=url,
referer=request.headers.get("Referer"),
hoverxref_version=request.headers.get("X-Hoverxref-Version"),
)
return Response(response)
def do_embed(*, project, version, doc=None, path=None, section=None, url=None):
"""Get the embed response from a document section."""
if not url:
external = version.type == EXTERNAL
url = resolve(
project=project,
version_slug=version.slug,
filename=path or doc,
external=external,
)
content = None
headers = None
# Embed API v2 supports Sphinx only.
if version.is_sphinx_type:
file_content = _get_doc_content(
project=project,
version=version,
doc=doc,
)
if not file_content:
return None
content, headers, section = parse_sphinx(
content=file_content,
section=section,
url=url,
)
else:
log.info("Using EmbedAPIv2 for a non Sphinx project.")
return None
if content is None:
return None
return {
'content': content,
'headers': headers,
'url': url,
'meta': {
'project': project.slug,
'version': version.slug,
'doc': doc,
'section': section,
},
}
def _get_doc_content(project, version, doc):
storage_path = project.get_storage_path(
'json',
version_slug=version.slug,
include_file=False,
version_type=version.type,
)
file_path = build_media_storage.join(
storage_path,
f'{doc}.fjson'.lstrip('/'),
)
try:
with build_media_storage.open(file_path) as file:
return json.load(file)
except Exception: # noqa
log.warning('Unable to read file.', file_path=file_path)
return None
def parse_sphinx(content, section, url):
"""Get the embed content for the section."""
body = content.get('body')
toc = content.get('toc')
if not content or not body or not toc:
return (None, None, section)
headers = [
recurse_while_none(element)
for element in PQ(toc)('a')
]
if not section and headers:
# If no section is sent, return the content of the first one
# TODO: This will always be the full page content,
# lets do something smarter here
section = list(headers[0].keys())[0].lower()
if not section:
return [], headers, None
body_obj = PQ(body)
escaped_section = escape_selector(section)
elements_id = [
escaped_section,
slugify(escaped_section),
make_id(escaped_section),
f'module-{escaped_section}',
]
query_result = []
for element_id in elements_id:
if not element_id:
continue
try:
query_result = body_obj(f'#{element_id}')
if query_result:
break
except Exception: # noqa
log.info(
'Failed to query section.',
url=url,
element_id=element_id,
)
if not query_result:
selector = f':header:contains("{escaped_section}")'
query_result = body_obj(selector).parent()
# Handle ``dt`` special cases
if len(query_result) == 1 and query_result[0].tag == 'dt':
parent = query_result.parent()
if 'glossary' in parent.attr('class'):
# Sphinx HTML structure for term glossary puts the ``id`` in the
# ``dt`` element with the title of the term. In this case, we
# need to return the next sibling which contains the definition
# of the term itself.
# Structure:
# <dl class="glossary docutils">
# <dt id="term-definition">definition</dt>
# <dd>Text definition for the term</dd>
# ...
# </dl>
query_result = query_result.next()
elif 'citation' in parent.attr('class'):
# Sphinx HTML structure for sphinxcontrib-bibtex puts the ``id`` in the
# ``dt`` element with the title of the cite. In this case, we
# need to return the next sibling which contains the cite itself.
# Structure:
# <dl class="citation">
# <dt id="cite-id"><span><a>Title of the cite</a></span></dt>
# <dd>Content of the cite</dd>
# ...
# </dl>
query_result = query_result.next()
else:
# Sphinx HTML structure for definition list puts the ``id``
# the ``dt`` element, instead of the ``dl``. This makes
# the backend to return just the title of the definition. If we
# detect this case, we return the parent (the whole ``dl``)
# Structure:
# <dl class="confval">
# <dt id="confval-config">
# <code class="descname">config</code>
# <a class="headerlink" href="#confval-config">¶</a></dt>
# <dd><p>Text with a description</p></dd>
# </dl>
query_result = parent
def dump(obj):
"""Handle API-based doc HTML."""
if obj[0].tag in ['span', 'h2']:
return obj.parent().outerHtml()
return obj.outerHtml()
ret = [dump(clean_references(obj, url)) for obj in query_result]
return ret, headers, section