View Javadoc
1   /*
2    * Copyright (C) 2026 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.service;
7   
8   import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
9   import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
10  import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
11  
12  import jakarta.servlet.http.HttpServletRequest;
13  import java.time.temporal.ChronoField;
14  import java.util.UUID;
15  import java.util.regex.Pattern;
16  import org.springframework.http.CacheControl;
17  import org.springframework.http.ContentDisposition;
18  import org.springframework.http.ResponseEntity;
19  import org.springframework.stereotype.Service;
20  import org.tailormap.api.controller.LayerAttachedUploadsController;
21  import org.tailormap.api.controller.UploadsController;
22  import org.tailormap.api.persistence.Application;
23  import org.tailormap.api.persistence.Upload;
24  import org.tailormap.api.persistence.UploadCategory;
25  import org.tailormap.api.repository.UploadRepository;
26  
27  @Service
28  public class UploadsService {
29    private final UploadRepository uploadRepository;
30    public static final String DESCRIPTION_HEADER_NAME = "TM-Description";
31    /** The scheme used in Markdown files to reference an upload. For example, {@code upload://<upload-id>}. */
32    public static final String UPLOAD_MARKDOWN_SCHEME = "upload://";
33  
34    private static final Pattern UPLOAD_REPLACE_PATTERN =
35        Pattern.compile("upload://([a-f0-9]{8}(?:-[a-f0-9]{4}){4}[a-f0-9]{8})");
36  
37    public UploadsService(UploadRepository uploadRepository) {
38      this.uploadRepository = uploadRepository;
39    }
40  
41    /**
42     * Get the value of the If-Modified-Since header of a request.
43     *
44     * @param request the request
45     * @return the date in milliseconds, or -1 if the header is missing or can't be parsed (a client error that should
46     *     not cause a server error)
47     */
48    public static long getIfModifiedSince(HttpServletRequest request) {
49      try {
50        return request.getDateHeader("If-Modified-Since");
51      } catch (IllegalArgumentException e) {
52        return -1;
53      }
54    }
55  
56    /**
57     * Checks if the upload with the given ID has been modified since the provided timestamp.
58     *
59     * @param id the UUID of the upload
60     * @param ifModifiedSince the timestamp to compare against (in milliseconds)
61     * @return true if the upload has been modified since the provided timestamp or when the upload does not exist,
62     *     false otherwise
63     */
64    public boolean checkIfModifiedSince(UUID id, long ifModifiedSince) {
65      if (ifModifiedSince == -1) {
66        return true;
67      }
68  
69      return uploadRepository
70          .findLastModifiedById(id)
71          .map(uploadLastModified -> ifModifiedSince
72              < uploadLastModified
73                  .with(ChronoField.MILLI_OF_SECOND, 0)
74                  .toInstant()
75                  .toEpochMilli())
76          .orElse(true);
77    }
78  
79    public String getUrlForImage(String imageId, UploadCategory category) {
80      if (imageId == null) {
81        return null;
82      }
83      try {
84        UUID uuid = UUID.fromString(imageId);
85        return getUrlForImage(uuid, category);
86      } catch (IllegalArgumentException e) {
87        // Illegal UUID, return null
88        return null;
89      }
90    }
91  
92    public String getUrlForImage(UUID imageId, UploadCategory category) {
93      if (imageId == null) {
94        return null;
95      }
96      if (category.isRestricted()) {
97        throw new IllegalArgumentException(
98            "Access to restricted category is not allowed without application and layer context");
99      }
100     return uploadRepository
101         .findByIdAndCategory(imageId, category)
102         .map(upload -> linkTo(UploadsController.class)
103             .slash("api")
104             .slash("uploads")
105             .slash(category)
106             .slash(imageId.toString())
107             .slash(upload.getFilename())
108             .toString())
109         .orElse(null);
110   }
111 
112   /**
113    * Returns the URL for a layer-attached image e.g. a legend image, or null if the imageId is null or not found.
114    *
115    * @param imageId the id of the image
116    * @param category the category of the image, e.g. LEGEND
117    * @param application the application the image is attached to
118    * @param layerId the id of the layer the image is attached to
119    * @return the URL for the layer-attached image or null
120    */
121   public String getUrlForLayerAttachedImage(
122       UUID imageId, UploadCategory category, Application application, String layerId) {
123     if (imageId == null) {
124       return null;
125     }
126     if (category.isRestricted()) {
127       return uploadRepository
128           .findByIdAndCategory(imageId, category)
129           .map(upload -> linkTo(LayerAttachedUploadsController.class)
130               .slash("api")
131               .slash("app")
132               .slash(application.getName())
133               .slash("layer")
134               .slash(layerId)
135               .slash("uploads")
136               .slash(category)
137               .slash(imageId.toString())
138               .slash(upload.getFilename())
139               .toString())
140           .orElse(null);
141     } else {
142       return getUrlForImage(imageId, category);
143     }
144   }
145 
146   public String replaceUploadLinks(Application application, String appLayerId, String description) {
147     if (description == null) {
148       return null;
149     }
150 
151     return UPLOAD_REPLACE_PATTERN.matcher(description).replaceAll(matchResult -> {
152       try {
153         UUID uploadId = UUID.fromString(matchResult.group(1));
154         Upload upload = uploadRepository.findById(uploadId).orElse(null);
155         if (upload == null) {
156           return "";
157         }
158         return linkTo(LayerAttachedUploadsController.class)
159             .slash("api")
160             .slash("app")
161             .slash(application.getName())
162             .slash("layer")
163             .slash(appLayerId)
164             .slash("uploads")
165             .slash(upload.getCategory().toString())
166             .slash(uploadId.toString())
167             .slash(upload.getFilename())
168             .toString();
169       } catch (Exception _ignored) {
170         return "";
171       }
172     });
173   }
174 
175   /**
176    * Creates a response builder for serving an upload, with the upload's content type, description, last modified
177    * time, content length and cache control headers.
178    *
179    * <p>Uploads are served inline with the MIME type given when uploading, so an uploaded HTML or SVG file could run
180    * script on the Tailormap origin when opened directly, using the session of whoever opens it. Only admins can
181    * upload, but there is a single admin role. {@code Content-Security-Policy: sandbox} forces an opaque origin and
182    * disables scripts, {@code X-Content-Type-Options: nosniff} disables MIME sniffing. Images loaded with
183    * {@code <img>} and JSON loaded with fetch are not affected, browsers ignore CSP on subresources. See HTM-2451 and
184    * HTM-2438 for attachments.
185    *
186    * @param upload the upload to serve
187    * @return the response builder, call {@code body(upload.getContent())} to finish it
188    */
189   public static ResponseEntity.BodyBuilder uploadResponseBuilder(Upload upload) {
190     return ResponseEntity.ok()
191         .header(CONTENT_TYPE, upload.getMimeType())
192         .header(DESCRIPTION_HEADER_NAME, upload.getDescription())
193         .header("Content-Security-Policy", "sandbox")
194         .header("X-Content-Type-Options", "nosniff")
195         .lastModified(upload.getLastModified().toInstant())
196         .contentLength(upload.getContentLength())
197         .cacheControl(CacheControl.noCache().cachePublic());
198   }
199 
200   public static ResponseEntity<byte[]> createUploadResponseEntity(Upload upload) {
201     return uploadResponseBuilder(upload)
202         .header(
203             CONTENT_DISPOSITION,
204             ContentDisposition.inline()
205                 .filename(upload.getFilename())
206                 .build()
207                 .toString())
208         .body(upload.getContent());
209   }
210 }