]> git.openstreetmap.org Git - chef.git/blob - cookbooks/tile/templates/default/export.erb
Add copyright/attribution message to downloaded map images
[chef.git] / cookbooks / tile / templates / default / export.erb
1 #!/usr/bin/python3 -u
2 # -*- coding: utf-8 -*-
3
4 import cairo
5 import cgi
6 import http.cookies
7 import mapnik
8 import io
9 import os
10 import pyotp
11 import pyproj
12 import resource
13 import shutil
14 import signal
15 import sys
16 import tempfile
17 from PIL import Image
18
19 # Limit maximum CPU time
20 # The Postscript output format can sometimes take hours
21 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
22
23 # Limit memory usage
24 # Some odd requests can cause extreme memory usage
25 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
26
27 # Routine to output HTTP headers
28 def output_headers(content_type, filename = "", length = 0):
29   print("Content-Type: %s" % content_type)
30   if filename:
31     print("Content-Disposition: attachment; filename=\"%s\"" % filename)
32   if length:
33     print("Content-Length: %d" % length)
34   print("")
35
36 # Routine to output the contents of a file
37 def output_file(file):
38   file.seek(0)
39   shutil.copyfileobj(file, sys.stdout.buffer)
40
41 # Routine to get the size of a file
42 def file_size(file):
43   return os.fstat(file.fileno()).st_size
44
45 # Routine to retrieve BytesIO payload length
46 def bytesio_size(bio):
47   return bio.getbuffer().nbytes
48
49 # Routine to report an error
50 def output_error(message, status = "400 Bad Request"):
51   print("Status: %s" % status)
52   output_headers("text/html")
53   print("<html>")
54   print("<head>")
55   print("<title>Error</title>")
56   print("</head>")
57   print("<body>")
58   print("<h1>Error</h1>")
59   print("<p>%s</p>" % message)
60   print("</body>")
61   print("</html>")
62
63 # Add a copyright notice for raster formats (PNG, JPEG, WEBP)
64 def add_copyright_notice_raster(image, map_width, map_height, format):
65   # Convert the Mapnik image to PNG and store it in a BytesIO object
66   png = image.tostring("png")
67   png_io = io.BytesIO(png)
68
69   # Load the PNG data from the BytesIO object into a Cairo ImageSurface
70   surface = cairo.ImageSurface.create_from_png(png_io)
71
72   add_copyright_notice_vector(surface, map_width, map_height)
73
74   # Convert the Cairo surface to PNG in a BytesIO object
75   output_io = io.BytesIO()
76   surface.write_to_png(output_io)
77
78   if format == "png":
79     return output_io
80   else:
81     # Open the output PNG image for conversion to other formats
82     img = Image.open(output_io)
83     img_io = io.BytesIO()
84     img.save(img_io, format=format)
85     return img_io
86
87 # Add a copyright notice for vector formats (SVG, PDF, PS)
88 def add_copyright_notice_vector(surface, map_width, map_height):
89   context = cairo.Context(surface)
90
91   # Set the font for the copyright notice
92   context.set_font_face(cairo.ToyFontFace("DejaVu"))
93   context.set_font_size(14)
94
95   # Define the copyright text
96   text = "© OpenStreetMap contributors"
97
98   text_extents = context.text_extents(text)
99   text_width = text_extents.width
100   text_height = text_extents.height
101
102   x_margin = 10
103   y_margin = 10
104
105   # Position the text at the bottom-right corner
106   x_position = map_width - text_width - x_margin
107   y_position = map_height - text_height - y_margin
108
109   # Draw a white box just large enough to fit the text
110   context.set_source_rgba(1, 1, 1, 0.5)
111   context.rectangle(x_position - x_margin, y_position - y_margin,
112                     text_width + 2 * x_margin, text_height + 2 * y_margin)
113   context.fill_preserve()
114
115   context.set_source_rgb(0, 0, 0)  # Black color for the text
116   context.move_to(x_position - x_margin / 2, y_position + y_margin)
117   context.show_text(text)
118
119 # Render and output map for raster formats (PNG, JPEG, WEBP)
120 def render_and_output_image(map, format):
121   image = mapnik.Image(map.width, map.height)
122   mapnik.render(map, image)
123
124   bytes_io = add_copyright_notice_raster(image, map.width, map.height, format)
125
126   if format == "png":
127     output_headers("image/png", "map.png", bytesio_size(bytes_io))
128   elif format == "jpeg":
129     output_headers("image/jpeg", "map.jpg", bytesio_size(bytes_io))
130   elif format == "webp":
131     output_headers("image/webp", "map.webp", bytesio_size(bytes_io))
132
133   output_file(bytes_io)
134
135 # Render and output map for vector formats (SVG, PDF, PS)
136 def render_and_output_vector(map, format):
137   with tempfile.NamedTemporaryFile(prefix="export") as file:
138     if format == "svg":
139       surface = cairo.SVGSurface(file.name, map.width, map.height)
140       surface.restrict_to_version(cairo.SVG_VERSION_1_2)
141     elif format == "pdf":
142       surface = cairo.PDFSurface(file.name, map.width, map.height)
143     elif format == "ps":
144       surface = cairo.PSSurface(file.name, map.width, map.height)
145
146     mapnik.render(map, surface)
147
148     add_copyright_notice_vector(surface, map.width, map.height)
149
150     surface.finish()
151
152     if format == "svg":
153       output_headers("image/svg+xml", "map.svg", file_size(file))
154     elif format == "pdf":
155       output_headers("application/pdf", "map.pdf", file_size(file))
156     elif format == "ps":
157       output_headers("application/postscript", "map.ps", file_size(file))
158
159     output_file(file)
160
161
162 # Create TOTP token validator
163 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
164
165 # Parse CGI parameters
166 form = cgi.FieldStorage()
167
168 # Import cookies
169 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
170
171 # Make sure we have a user agent
172 if 'HTTP_USER_AGENT' not in os.environ:
173   os.environ['HTTP_USER_AGENT'] = 'NONE'
174
175 # Make sure we have a referer
176 if 'HTTP_REFERER' not in os.environ:
177   os.environ['HTTP_REFERER'] = 'NONE'
178
179 # Look for TOTP token
180 if '_osm_totp_token' in cookies:
181   token = cookies['_osm_totp_token'].value
182 else:
183   token = None
184
185 # Get the load average
186 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
187 idletime = cputimes[3] / sum(cputimes)
188
189 # Process the request
190 if not totp.verify(token, valid_window = 1):
191   # Abort if the request didn't have a valid TOTP token
192   output_error("Missing or invalid token")
193 elif idletime < 0.2:
194   # Abort if the CPU idle time on the machine is too low
195   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
196 <% @blocks["user_agents"].each do |user_agent| -%>
197 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
198   # Block scraper
199   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
200 <% end -%>
201 <% @blocks["referers"].each do |referer| -%>
202 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
203   # Block scraper
204   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
205 <% end -%>
206 elif "bbox" not in form:
207   # No bounding box specified
208   output_error("No bounding box specified")
209 elif "scale" not in form:
210   # No scale specified
211   output_error("No scale specified")
212 elif "format" not in form:
213   # No format specified
214   output_error("No format specified")
215 else:
216   # Create projection object
217   transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
218
219   # Get the bounds of the area to render
220   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
221
222   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
223     # Bogus bounding box
224     output_error("Invalid bounding box")
225   else:
226     # Project the bounds to the map projection
227     bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
228                         *transformer.transform(bbox[2], bbox[3]))
229
230     # Get the style to use
231     style = form.getvalue("style", "default")
232
233     # Calculate the size of the final rendered image
234     scale = float(form.getvalue("scale"))
235     width = int(bbox.width() / scale / 0.00028)
236     height = int(bbox.height() / scale / 0.00028)
237
238     # Limit the size of map we are prepared to produce
239     if width * height > 4000000:
240       # Map is too large (limit is approximately A2 size)
241       output_error("Map too large")
242     else:
243       # Create map
244       map = mapnik.Map(width, height)
245
246       # Load map configuration
247       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
248
249       # Zoom the map to the bounding box
250       map.zoom_to_box(bbox)
251
252       # Fork so that we can handle crashes rendering the map
253       pid = os.fork()
254
255       # Render the map
256       if pid == 0:
257         format = form.getvalue("format")
258         if format in ["png", "jpeg", "webp"]:
259           render_and_output_image(map, format)
260         elif format in ["svg", "pdf", "ps"]:
261           render_and_output_vector(map, format)
262         else:
263           output_error("Unknown format")
264       else:
265         pid, status = os.waitpid(pid, 0)
266         if status & 0xff == signal.SIGXCPU:
267           output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
268         elif status & 0xff == signal.SIGSEGV:
269           output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
270         elif status != 0:
271           output_error("Internal server error", "500 Internal Server Error")