-
Notifications
You must be signed in to change notification settings - Fork 7
/
views.py
195 lines (159 loc) · 6.79 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
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mimetypes
import urllib.parse
import botocore
from aiohttp import web
from botocore.config import Config as BotoCoreConfig
ANON_CONFIG = BotoCoreConfig(signature_version=botocore.UNSIGNED)
async def health(request):
return web.Response(status=200)
async def not_found(request):
return web.Response(status=404)
async def redirect(request):
python_version = request.match_info["python_version"]
project_l = request.match_info["project_l"]
project_name = request.match_info["project_name"]
filename = request.match_info["filename"]
# If the letter bucket doesn't match the first letter of the project, then
# there is no point to going any further since it will be a 404 regardless.
if project_l != project_name[0]:
return web.Response(status=404, headers={'Reason': 'Incorrect project bucket'})
# If the filename we're looking for is a signature, then we'll need to turn
# this into the *real* filename and a note that we're looking for the
# signature.
if filename.endswith(".asc"):
filename = filename[:-4]
signature = True
else:
signature = False
json_url = urllib.parse.urljoin(
request.app["settings"]["endpoint"],
"/pypi/{}/json".format(project_name),
)
async with request.app["http.session"].get(json_url) as resp:
if 400 <= resp.status < 500:
return web.Response(status=resp.status)
elif 500 <= resp.status < 600:
return web.Response(status=503)
# It shouldn't be possible to get a status code other than 200 here.
assert resp.status == 200
# Get the JSON data from our request.
data = await resp.json()
# Look at all of the files listed in the JSON response, and see if one
# matches our filename and Python version. If we find one, then return a
# 302 redirect to that URL.
for release in data.get("releases", {}).values():
for file_ in release:
if (file_["filename"] == filename
and file_["python_version"] == python_version):
# If we've found our filename, but we were actually looking for
# the *signature* of that file, then we need to check if it has
# a signature associated with it, and if so redirect to that,
# and if not return a 404.
if signature:
if file_.get("has_sig"):
return web.Response(
status=302,
headers={
"Location": file_["url"] + ".asc",
"Cache-Control": "max-age=604800, public",
},
)
else:
return web.Response(status=404, headers={'Reason': 'missing signature file'})
# If we've found our filename, then we'll redirect to it.
else:
return web.Response(
status=302,
headers={
"Location": file_["url"],
"Cache-Control": "max-age=604800, public",
},
)
# If we've gotten to this point, it means that we couldn't locate an url
# to redirect to so we'll jsut 404.
return web.Response(status=404, headers={'Reason': 'no file found'})
async def fetch_key(s3, request, bucket, key):
resp = await s3.get_object(
Bucket=bucket,
Key=key,
)
return resp
async def index(request):
bucket = request.app["settings"]["docs_bucket"]
session = request.app["boto.session"]()
path = "index.html"
async with session.create_client('s3', config=ANON_CONFIG) as s3:
try:
key = await fetch_key(s3, request, bucket, path)
except botocore.exceptions.ClientError:
return web.Response(status=404)
content_type, content_encoding = mimetypes.guess_type(path)
response = web.StreamResponse(status=200, reason='OK')
response.content_type = content_type
response.content_encoding = content_encoding
body = key['Body']
await response.prepare(request)
while True:
data = await body.read(4096)
await response.write(data)
await response.drain()
if not data:
body.close()
break
return response
async def documentation_top(request):
project_name = request.match_info["project_name"]
return web.HTTPMovedPermanently(location=f"/{project_name}/")
async def documentation(request):
project_name = request.match_info["project_name"]
path = request.match_info.get("path", "")
if project_name in request.app["redirects"]:
location = request.app["redirects"][project_name]["base_uri"]
if request.app["redirects"][project_name]["include_path"]:
location = f"{location}/{path}"
return web.Response(
status=302,
headers={
"Location": location,
}
)
path = f"{project_name}/{path}"
if path.endswith("/"):
path += "index.html"
bucket = request.app["settings"]["docs_bucket"]
session = request.app["boto.session"]()
async with session.create_client('s3', config=ANON_CONFIG) as s3:
try:
key = await fetch_key(s3, request, bucket, path)
except botocore.exceptions.ClientError:
try:
key = await fetch_key(s3, request, bucket, path + "/index.html")
except botocore.exceptions.ClientError:
return web.Response(status=404)
else:
return web.HTTPMovedPermanently(location="/" + path + "/")
content_type, content_encoding = mimetypes.guess_type(path)
response = web.StreamResponse(status=200, reason='OK')
response.content_type = content_type
response.content_encoding = content_encoding
body = key['Body']
await response.prepare(request)
while True:
data = await body.read(4096)
await response.write(data)
await response.drain()
if not data:
body.close()
break
return response