Debian Codegraph @

media/mediaType.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package media contains Media Type (MIME type) related types and functions.
15 package media
16
17 import (
18 "encoding/json"
19 "fmt"
20 "net/http"
21 "strings"
22 )
23
24 var zero Type
25
26 const (
27 DefaultDelimiter = "."
28 )
29
30 // MediaType (also known as MIME type and content type) is a two-part identifier for
31 // file formats and format contents transmitted on the Internet.
32 // For Hugo's use case, we use the top-level type name / subtype name + suffix.
33 // One example would be application/svg+xml
34 // If suffix is not provided, the sub type will be used.
35 // <docsmeta>{ "name": "MediaType" }</docsmeta>
36 type Type struct {
37 // The full MIME type string, e.g. "application/rss+xml".
38 Type string `json:"-"`
39
40 // The top-level type name, e.g. "application".
41 MainType string `json:"mainType"`
42 // The subtype name, e.g. "rss".
43 SubType string `json:"subType"`
44 // The delimiter before the suffix, e.g. ".".
45 Delimiter string `json:"delimiter"`
46
47 // FirstSuffix holds the first suffix defined for this MediaType.
48 FirstSuffix SuffixInfo `json:"-"`
49
50 // This is the optional suffix after the "+" in the MIME type,
51 // e.g. "xml" in "application/rss+xml".
52 mimeSuffix string
53
54 // E.g. "jpg,jpeg"
55 // Stored as a string to make Type comparable.
56 // For internal use only.
57 SuffixesCSV string `json:"-"`
58 }
59
60 // SuffixInfo holds information about a Media Type's suffix.
61 type SuffixInfo struct {
62 // Suffix is the suffix without the delimiter, e.g. "xml".
63 Suffix string `json:"suffix"`
64
65 // FullSuffix is the suffix with the delimiter, e.g. ".xml".
66 FullSuffix string `json:"fullSuffix"`
67 }
68
69 // FromContent resolve the Type primarily using http.DetectContentType.
70 // If http.DetectContentType resolves to application/octet-stream, a zero Type is returned.
71 // If http.DetectContentType resolves to text/plain or application/xml, we try to get more specific using types and ext.
72 func FromContent(types Types, extensionHints []string, content []byte) Type {
73 t, _, _ := strings.Cut(http.DetectContentType(content), ";")
74 if t == "application/octet-stream" {
75 return zero
76 }
77
78 var found bool
79 m, found := types.GetByType(t)
80 if !found {
81 if t == "text/xml" {
82 // This is how it's configured in Hugo by default.
83 m, found = types.GetByType("application/xml")
84 }
85 }
86
87 if !found {
88 return zero
89 }
90
91 var mm Type
92
93 for _, extension := range extensionHints {
94 extension = strings.TrimPrefix(extension, ".")
95 mm, _, found = types.GetFirstBySuffix(extension)
96 if found {
97 break
98 }
99 }
100
101 if found {
102 if m == mm {
103 return m
104 }
105
106 if m.IsText() && mm.IsText() {
107 // http.DetectContentType isn't brilliant when it comes to common text formats, so we need to do better.
108 // For now we say that if it's detected to be a text format and the extension/content type in header reports
109 // it to be a text format, then we use that.
110 return mm
111 }
112
113 // E.g. an image with a *.js extension.
114 return zero
115 }
116
117 return m
118 }
119
120 // FromStringAndExt creates a Type from a MIME string and a given extensions
121 func FromStringAndExt(t string, ext ...string) (Type, error) {
122 tp, err := FromString(t)
123 if err != nil {
124 return tp, err
125 }
126 for i, e := range ext {
127 ext[i] = strings.TrimPrefix(e, ".")
128 }
129 tp.SuffixesCSV = strings.Join(ext, ",")
130 tp.Delimiter = DefaultDelimiter
131 tp.init()
132 return tp, nil
133 }
134
135 // FromString creates a new Type given a type string on the form MainType/SubType and
136 // an optional suffix, e.g. "text/html" or "text/html+html".
137 func FromString(t string) (Type, error) {
138 t = strings.ToLower(t)
139 parts := strings.Split(t, "/")
140 if len(parts) != 2 {
141 return Type{}, fmt.Errorf("cannot parse %q as a media type", t)
142 }
143 mainType := parts[0]
144 subParts := strings.Split(parts[1], "+")
145
146 subType, _, _ := strings.Cut(subParts[0], ";")
147
148 var suffix string
149
150 if len(subParts) > 1 {
151 suffix = subParts[1]
152 }
153
154 var typ string
155 if suffix != "" {
156 typ = mainType + "/" + subType + "+" + suffix
157 } else {
158 typ = mainType + "/" + subType
159 }
160
161 return Type{Type: typ, MainType: mainType, SubType: subType, mimeSuffix: suffix}, nil
162 }
163
164 // For internal use.
165 func (m Type) String() string {
166 return m.Type
167 }
168
169 // Suffixes returns all valid file suffixes for this type.
170 func (m Type) Suffixes() []string {
171 if m.SuffixesCSV == "" {
172 return nil
173 }
174
175 return strings.Split(m.SuffixesCSV, ",")
176 }
177
178 // IsText returns whether this Type is a text format.
179 // Note that this may currently return false negatives.
180 // TODO(bep) improve
181 // For internal use.
182 func (m Type) IsText() bool {
183 if m.MainType == "text" {
184 return true
185 }
186 switch m.SubType {
187 case "javascript", "json", "rss", "xml", "svg", "toml", "yml", "yaml":
188 return true
189 }
190 return false
191 }
192
193 // For internal use.
194 func (m Type) IsHTML() bool {
195 return m.SubType == Builtin.HTMLType.SubType
196 }
197
198 // For internal use.
199 func (m Type) IsMarkdown() bool {
200 return m.SubType == Builtin.MarkdownType.SubType
201 }
202
203 func InitMediaType(m *Type) {
204 m.init()
205 }
206
207 func (m *Type) init() {
208 m.FirstSuffix.FullSuffix = ""
209 m.FirstSuffix.Suffix = ""
210 if suffixes := m.Suffixes(); suffixes != nil {
211 m.FirstSuffix.Suffix = suffixes[0]
212 m.FirstSuffix.FullSuffix = m.Delimiter + m.FirstSuffix.Suffix
213 }
214 }
215
216 func newMediaType(main, sub string, suffixes []string) Type {
217 t := Type{MainType: main, SubType: sub, SuffixesCSV: strings.Join(suffixes, ","), Delimiter: DefaultDelimiter}
218 t.init()
219 return t
220 }
221
222 func newMediaTypeWithMimeSuffix(main, sub, mimeSuffix string, suffixes []string) Type {
223 mt := newMediaType(main, sub, suffixes)
224 mt.mimeSuffix = mimeSuffix
225 mt.init()
226 return mt
227 }
228
229 // Types is a slice of media types.
230 // <docsmeta>{ "name": "MediaTypes" }</docsmeta>
231 type Types []Type
232
233 func (t Types) Len() int { return len(t) }
234 func (t Types) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
235 func (t Types) Less(i, j int) bool { return t[i].Type < t[j].Type }
236
237 // GetBestMatch returns the best match for the given media type string.
238 func (t Types) GetBestMatch(s string) (Type, bool) {
239 // First try an exact match.
240 if mt, found := t.GetByType(s); found {
241 return mt, true
242 }
243
244 // Try main type.
245 if mt, found := t.GetBySubType(s); found {
246 return mt, true
247 }
248
249 // Try extension.
250 if mt, _, found := t.GetFirstBySuffix(s); found {
251 return mt, true
252 }
253
254 return Type{}, false
255 }
256
257 // GetByType returns a media type for tp.
258 func (t Types) GetByType(tp string) (Type, bool) {
259 for _, tt := range t {
260 if strings.EqualFold(tt.Type, tp) {
261 return tt, true
262 }
263 }
264
265 if !strings.Contains(tp, "+") {
266 // Try with the main and sub type
267 parts := strings.Split(tp, "/")
268 if len(parts) == 2 {
269 return t.GetByMainSubType(parts[0], parts[1])
270 }
271 }
272
273 return Type{}, false
274 }
275
276 func (t Types) normalizeSuffix(s string) string {
277 return strings.ToLower(strings.TrimPrefix(s, "."))
278 }
279
280 // BySuffix will return all media types matching a suffix.
281 func (t Types) BySuffix(suffix string) []Type {
282 suffix = t.normalizeSuffix(suffix)
283 var types []Type
284 for _, tt := range t {
285 if tt.HasSuffix(suffix) {
286 types = append(types, tt)
287 }
288 }
289 return types
290 }
291
292 // GetFirstBySuffix will return the first type matching the given suffix.
293 func (t Types) GetFirstBySuffix(suffix string) (Type, SuffixInfo, bool) {
294 suffix = t.normalizeSuffix(suffix)
295 for _, tt := range t {
296 if tt.HasSuffix(suffix) {
297 return tt, SuffixInfo{
298 FullSuffix: tt.Delimiter + suffix,
299 Suffix: suffix,
300 }, true
301 }
302 }
303 return Type{}, SuffixInfo{}, false
304 }
305
306 // GetBySuffix gets a media type given as suffix, e.g. "html".
307 // It will return false if no format could be found, or if the suffix given
308 // is ambiguous.
309 // The lookup is case insensitive.
310 func (t Types) GetBySuffix(suffix string) (tp Type, si SuffixInfo, found bool) {
311 suffix = t.normalizeSuffix(suffix)
312 for _, tt := range t {
313 if tt.HasSuffix(suffix) {
314 if found {
315 // ambiguous
316 found = false
317 return
318 }
319 tp = tt
320 si = SuffixInfo{
321 FullSuffix: tt.Delimiter + suffix,
322 Suffix: suffix,
323 }
324 found = true
325 }
326 }
327 return
328 }
329
330 func (t Types) IsTextSuffix(suffix string) bool {
331 suffix = t.normalizeSuffix(suffix)
332 for _, tt := range t {
333 if tt.HasSuffix(suffix) {
334 return tt.IsText()
335 }
336 }
337 return false
338 }
339
340 func (m Type) HasSuffix(suffix string) bool {
341 return strings.Contains(","+m.SuffixesCSV+",", ","+suffix+",")
342 }
343
344 // GetByMainSubType gets a media type given a main and a sub type e.g. "text" and "plain".
345 // It will return false if no format could be found, or if the combination given
346 // is ambiguous.
347 // The lookup is case insensitive.
348 func (t Types) GetByMainSubType(mainType, subType string) (tp Type, found bool) {
349 for _, tt := range t {
350 if strings.EqualFold(mainType, tt.MainType) && strings.EqualFold(subType, tt.SubType) {
351 if found {
352 // ambiguous
353 found = false
354 return
355 }
356
357 tp = tt
358 found = true
359 }
360 }
361 return
362 }
363
364 // GetBySubType gets a media type given a sub type e.g. "plain".
365 func (t Types) GetBySubType(subType string) (tp Type, found bool) {
366 for _, tt := range t {
367 if strings.EqualFold(subType, tt.SubType) {
368 if found {
369 // ambiguous
370 found = false
371 return
372 }
373 tp = tt
374 found = true
375 }
376 }
377 return
378 }
379
380 // IsZero reports whether this Type represents a zero value.
381 // For internal use.
382 func (m Type) IsZero() bool {
383 return m.SubType == ""
384 }
385
386 // MarshalJSON returns the JSON encoding of m.
387 // For internal use.
388 func (m Type) MarshalJSON() ([]byte, error) {
389 type Alias Type
390 return json.Marshal(&struct {
391 Alias
392 Type string `json:"type"`
393 String string `json:"string"`
394 Suffixes []string `json:"suffixes"`
395 }{
396 Alias: (Alias)(m),
397 Type: m.Type,
398 String: m.String(),
399 Suffixes: strings.Split(m.SuffixesCSV, ","),
400 })
401 }