summaryrefslogtreecommitdiffstats
path: root/media/mediaType.go
blob: 07ba410fba328de2519d6203fa825583105ae247 (plain)
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
// Copyright 2017-present The Hugo Authors. All rights reserved.
//
// 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.

package media

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"

	"github.com/mitchellh/mapstructure"
)

const (
	defaultDelimiter = "."
)

// Type (also known as MIME type and content type) is a two-part identifier for
// file formats and format contents transmitted on the Internet.
// For Hugo's use case, we use the top-level type name / subtype name + suffix.
// One example would be image/jpeg+jpg
// If suffix is not provided, the sub type will be used.
// See // https://en.wikipedia.org/wiki/Media_type
type Type struct {
	MainType  string `json:"mainType"`  // i.e. text
	SubType   string `json:"subType"`   // i.e. html
	Suffix    string `json:"suffix"`    // i.e html
	Delimiter string `json:"delimiter"` // defaults to "."
}

// FromString creates a new Type given a type sring on the form MainType/SubType and
// an optional suffix, e.g. "text/html" or "text/html+html".
func FromString(t string) (Type, error) {
	t = strings.ToLower(t)
	parts := strings.Split(t, "/")
	if len(parts) != 2 {
		return Type{}, fmt.Errorf("cannot parse %q as a media type", t)
	}
	mainType := parts[0]
	subParts := strings.Split(parts[1], "+")

	subType := strings.Split(subParts[0], ";")[0]

	var suffix string

	if len(subParts) == 1 {
		suffix = subType
	} else {
		suffix = subParts[1]
	}

	return Type{MainType: mainType, SubType: subType, Suffix: suffix, Delimiter: defaultDelimiter}, nil
}

// Type returns a string representing the main- and sub-type of a media type, i.e. "text/css".
// Hugo will register a set of default media types.
// These can be overridden by the user in the configuration,
// by defining a media type with the same Type.
func (m Type) Type() string {
	return fmt.Sprintf("%s/%s", m.MainType, m.SubType)
}

func (m Type) String() string {
	if m.Suffix != "" {
		return fmt.Sprintf("%s/%s+%s", m.MainType, m.SubType, m.Suffix)
	}
	return fmt.Sprintf("%s/%s", m.MainType, m.SubType)
}

// FullSuffix returns the file suffix with any delimiter prepended.
func (m Type) FullSuffix() string {
	return m.Delimiter + m.Suffix
}

var (
	CalendarType   = Type{"text", "calendar", "ics", defaultDelimiter}
	CSSType        = Type{"text", "css", "css", defaultDelimiter}
	SCSSType       = Type{"text", "x-scss", "scss", defaultDelimiter}
	SASSType       = Type{"text", "x-sass", "sass", defaultDelimiter}
	CSVType        = Type{"text", "csv", "csv", defaultDelimiter}
	HTMLType       = Type{"text", "html", "html", defaultDelimiter}
	JavascriptType = Type{"application", "javascript", "js", defaultDelimiter}
	JSONType       = Type{"application", "json", "json", defaultDelimiter}
	RSSType        = Type{"application", "rss", "xml", defaultDelimiter}
	XMLType        = Type{"application", "xml", "xml", defaultDelimiter}
	// The official MIME type of SVG is image/svg+xml. We currently only support one extension
	// per mime type. The workaround in projects is to create multiple media type definitions,
	// but we need to improve this to take other known suffixes into account.
	// But until then, svg has an svg extension, which is very common. TODO(bep)
	SVGType  = Type{"image", "svg", "svg", defaultDelimiter}
	TextType = Type{"text", "plain", "txt", defaultDelimiter}

	OctetType = Type{"application", "octet-stream", "", ""}
)

var DefaultTypes = Types{
	CalendarType,
	CSSType,
	CSVType,
	SCSSType,
	SASSType,
	HTMLType,
	JavascriptType,
	JSONType,
	RSSType,
	XMLType,
	SVGType,
	TextType,
	OctetType,
}

func init() {
	sort.Sort(DefaultTypes)
}

type Types []Type

func (t Types) Len() int           { return len(t) }
func (t Types) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
func (t Types) Less(i, j int) bool { return t[i].Type() < t[j].Type() }

func (t Types) GetByType(tp string) (Type, bool) {
	for _, tt := range t {
		if strings.EqualFold(tt.Type(), tp) {
			return tt, true
		}
	}
	return Type{}, false
}

// GetFirstBySuffix will return the first media type matching the given suffix.
func (t Types) GetFirstBySuffix(suffix string) (Type, bool) {
	for _, tt := range t {
		if strings.EqualFold(suffix, tt.Suffix) {
			return tt, true
		}
	}
	return Type{}, false
}

// GetBySuffix gets a media type given as suffix, e.g. "html".
// It will return false if no format could be found, or if the suffix given
// is ambiguous.
// The lookup is case insensitive.
func (t Types) GetBySuffix(suffix string) (tp Type, found bool) {
	for _, tt := range t {
		if strings.EqualFold(suffix, tt.Suffix) {
			if found {
				// ambiguous
				found = false
				return
			}
			tp = tt
			found = true
		}
	}
	return
}

// DecodeTypes takes a list of media type configurations and merges those,
// in the order given, with the Hugo defaults as the last resort.
func DecodeTypes(maps ...map[string]interface{}) (Types, error) {
	m := make(Types, len(DefaultTypes))
	copy(m, DefaultTypes)

	for _, mm := range maps {
		for k, v := range mm {
			// It may be tempting to put the full media type in the key, e.g.
			//  "text/css+css", but that will break the logic below.
			if strings.Contains(k, "+") {
				return Types{}, fmt.Errorf("media type keys cannot contain any '+' chars. Valid example is %q", "text/css")
			}

			found := false
			for i, vv := range m {
				// Match by type, i.e. "text/css"
				if strings.EqualFold(k, vv.Type()) {
					// Merge it with the existing
					if err := mapstructure.WeakDecode(v, &m[i]); err != nil {
						return m, err
					}
					found = true
				}
			}
			if !found {
				mediaType, err := FromString(k)
				if err != nil {
					return m, err
				}

				if err := mapstructure.WeakDecode(v, &mediaType); err != nil {
					return m, err
				}

				m = append(m, mediaType)
			}
		}
	}

	sort.Sort(m)

	return m, nil
}

func (m Type) MarshalJSON() ([]byte, error) {
	type Alias Type
	return json.Marshal(