-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathmime.ex
More file actions
340 lines (278 loc) · 9.44 KB
/
mime.ex
File metadata and controls
340 lines (278 loc) · 9.44 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
defmodule MIME do
@moduledoc """
Maps MIME types to its file extensions and vice versa.
MIME types can be extended in your application configuration
as follows:
config :mime, :types, %{
"application/vnd.api+json" => ["json-api"]
}
Note that defining a new type will completely override all
previous extensions. You can use `MIME.extensions/1` to get
the existing extension to keep when redefining.
You can also customize the extensions for suffixes. For example,
the mime type "application/custom+gzip" returns the extension
`".gz"` because the suffix "gzip" maps to `["gz"]`:
config :mime, :suffixes, %{
"gzip" => ["gz"]
}
After adding the configuration, MIME needs to be recompiled
if you are using an Elixir version earlier than v1.15. In such
cases, it can be done with:
$ mix deps.clean mime --build
"""
types = %{
"application/atom+xml" => ["atom"],
"application/epub+zip" => ["epub"],
"application/gzip" => ["gz"],
"application/java-archive" => ["jar"],
"application/javascript" => ["js"],
"application/json" => ["json"],
"application/json-patch+json" => ["json-patch"],
"application/ld+json" => ["jsonld"],
"application/manifest+json" => ["webmanifest"],
"application/msword" => ["doc"],
"application/octet-stream" => ["bin"],
"application/ogg" => ["ogx"],
"application/pdf" => ["pdf"],
"application/postscript" => ["ps", "eps", "ai"],
"application/rss+xml" => ["rss"],
"application/rtf" => ["rtf"],
"application/vnd.amazon.ebook" => ["azw"],
"application/vnd.api+json" => ["json-api"],
"application/vnd.apple.installer+xml" => ["mpkg"],
"application/vnd.etsi.asic-e+zip" => ["asice", "sce"],
"application/vnd.etsi.asic-s+zip" => ["asics", "scs"],
"application/vnd.mozilla.xul+xml" => ["xul"],
"application/vnd.ms-excel" => ["xls"],
"application/vnd.ms-fontobject" => ["eot"],
"application/vnd.ms-powerpoint" => ["ppt"],
"application/vnd.oasis.opendocument.presentation" => ["odp"],
"application/vnd.oasis.opendocument.spreadsheet" => ["ods"],
"application/vnd.oasis.opendocument.text" => ["odt"],
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => ["pptx"],
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => ["xlsx"],
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => ["docx"],
"application/vnd.rar" => ["rar"],
"application/vnd.visio" => ["vsd"],
"application/wasm" => ["wasm"],
"application/x-7z-compressed" => ["7z"],
"application/x-abiword" => ["abw"],
"application/x-bzip" => ["bz"],
"application/x-bzip2" => ["bz2"],
"application/x-cdf" => ["cda"],
"application/x-csh" => ["csh"],
"application/x-freearc" => ["arc"],
"application/x-httpd-php" => ["php"],
"application/x-msaccess" => ["mdb"],
"application/x-sh" => ["sh"],
"application/x-shockwave-flash" => ["swf"],
"application/x-tar" => ["tar"],
"application/xhtml+xml" => ["xhtml"],
"application/xml" => ["xml"],
"application/zip" => ["zip"],
"application/zstd" => ["zst"],
"audio/3gpp" => ["3gp"],
"audio/3gpp2" => ["3g2"],
"audio/aac" => ["aac"],
"audio/matroska" => ["mka"],
"audio/midi" => ["mid", "midi"],
"audio/mpeg" => ["mp3"],
"audio/mp4" => ["m4a"],
"audio/ogg" => ["oga"],
"audio/opus" => ["opus"],
"audio/wav" => ["wav"],
"audio/webm" => ["weba"],
"audio/x-matroska" => ["mka"],
"font/otf" => ["otf"],
"font/ttf" => ["ttf"],
"font/woff" => ["woff"],
"font/woff2" => ["woff2"],
"image/apng" => ["apng"],
"image/avif" => ["avif"],
"image/bmp" => ["bmp"],
"image/gif" => ["gif"],
"image/heic" => ["heic"],
"image/heif" => ["heif"],
"image/jp2" => ["jp2"],
"image/jpeg" => ["jpg", "jpeg"],
"image/jxl" => ["jxl"],
"image/png" => ["png"],
"image/svg+xml" => ["svg", "svgz"],
"image/tiff" => ["tiff", "tif"],
"image/vnd.adobe.photoshop" => ["psd"],
"image/vnd.microsoft.icon" => ["ico"],
"image/webp" => ["webp"],
"text/calendar" => ["ics"],
"text/css" => ["css"],
"text/csv" => ["csv"],
"text/html" => ["html", "htm"],
"text/javascript" => ["js", "mjs"],
"text/markdown" => ["md", "markdown"],
"text/plain" => ["txt", "text"],
"text/xml" => ["xml"],
"video/3gpp" => ["3gp"],
"video/3gpp2" => ["3g2"],
"video/matroska" => ["mkv"],
"video/matroska-3d" => ["mk3d"],
"video/mp2t" => ["ts"],
"video/mp4" => ["mp4"],
"video/mpeg" => ["mpeg", "mpg"],
"video/ogg" => ["ogv"],
"video/quicktime" => ["mov"],
"video/webm" => ["webm"],
"video/x-matroska" => ["mkv"],
"video/x-matroska-3d" => ["mk3d"],
"video/x-ms-wmv" => ["wmv"],
"video/x-msvideo" => ["avi"]
}
require Application
custom_types = Application.compile_env(:mime, :types, %{})
to_exts = fn map ->
for {media, exts} <- map, ext <- exts, reduce: %{} do
acc -> Map.update(acc, ext, media, &[media | List.wrap(&1)])
end
end
all_types = Map.merge(types, custom_types)
default_exts = %{
"3g2" => "video/3gpp2",
"3gp" => "video/3gpp",
"js" => "text/javascript",
"mk3d" => "video/matroska-3d",
"mka" => "audio/matroska",
"mkv" => "video/matroska",
"xml" => "text/xml"
}
custom_exts = Application.compile_env(:mime, :extensions, %{})
all_exts = Map.merge(to_exts.(all_types), Map.merge(default_exts, custom_exts))
# https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml
default_suffixes = %{
"gzip" => ["gz"],
"json" => ["json"],
"xml" => ["xml"],
"zip" => ["zip"],
"zstd" => ["zst"]
}
custom_suffixes = Application.compile_env(:mime, :suffixes, %{})
suffixes = Map.merge(default_suffixes, custom_suffixes)
@doc """
Returns the custom types compiled into the MIME module.
"""
def compiled_custom_types do
unquote(Macro.escape(custom_types))
end
@doc """
Returns a mapping of all known types to their extensions,
including custom types compiled into the MIME module.
## Examples
known_types()
#=> %{"application/json" => ["json"], ...}
"""
@doc since: "2.1.0"
@spec known_types() :: %{required(String.t()) => [String.t()]}
def known_types do
unquote(Macro.escape(all_types))
end
@doc """
Returns the extensions associated with a given MIME type.
## Examples
iex> MIME.extensions("text/html")
["html", "htm"]
iex> MIME.extensions("application/json")
["json"]
iex> MIME.extensions("application/vnd.custom+xml")
["xml"]
iex> MIME.extensions("foo/bar")
[]
"""
@spec extensions(String.t()) :: [String.t()]
def extensions(type) do
mime =
type
|> strip_params()
|> downcase("")
mime_to_ext(mime) || suffix(mime) || []
end
defp suffix(type) do
case String.split(type, "+") do
[_type_subtype_without_suffix, suffix] -> suffix_to_ext(suffix)
_ -> nil
end
end
@default_type "application/octet-stream"
@doc """
Returns the MIME type associated with a file extension.
If no MIME type is known for `file_extension`,
`#{inspect(@default_type)}` is returned.
## Examples
iex> MIME.type("html")
"text/html"
iex> MIME.type("foobarbaz")
#{inspect(@default_type)}
"""
@spec type(String.t()) :: String.t()
def type(file_extension) do
ext_to_mime(file_extension) || @default_type
end
@doc """
Returns whether an extension has a MIME type registered.
## Examples
iex> MIME.has_type?("html")
true
iex> MIME.has_type?("foobarbaz")
false
"""
@spec has_type?(String.t()) :: boolean
def has_type?(file_extension) do
is_binary(ext_to_mime(file_extension))
end
@doc """
Guesses the MIME type based on the path's extension. See `type/1`.
## Examples
iex> MIME.from_path("index.html")
"text/html"
"""
@spec from_path(Path.t()) :: String.t()
def from_path(path) do
case Path.extname(path) do
"." <> ext -> type(downcase(ext, ""))
_ -> @default_type
end
end
defp strip_params(string) do
string |> :binary.split(";") |> hd()
end
defp downcase(<<h, t::binary>>, acc) when h in ?A..?Z,
do: downcase(t, <<acc::binary, h + 32>>)
defp downcase(<<h, t::binary>>, acc), do: downcase(t, <<acc::binary, h>>)
defp downcase(<<>>, acc), do: acc
@spec ext_to_mime(String.t()) :: String.t() | nil
defp ext_to_mime(type)
for {ext, mimes} <- all_exts do
case mimes do
[first | _] ->
raise """
extension .#{ext} currently maps to different mime-types: #{inspect(mimes)}
You must tell us which mime-type is preferred by defining the :extensions \
configuration. For example:
config :mime, :extensions, %{
#{inspect(ext)} => #{inspect(first)}
}
"""
mime ->
defp ext_to_mime(unquote(ext)), do: unquote(mime)
end
end
defp ext_to_mime(_ext), do: nil
@spec mime_to_ext(String.t()) :: list(String.t()) | nil
defp mime_to_ext(type)
for {type, exts} <- all_types do
defp mime_to_ext(unquote(type)), do: unquote(List.wrap(exts))
end
defp mime_to_ext(_type), do: nil
@spec suffix_to_ext(String.t()) :: list(String.t()) | nil
defp suffix_to_ext(suffix)
for {suffix, exts} <- suffixes do
defp suffix_to_ext(unquote(suffix)), do: unquote(List.wrap(exts))
end
defp suffix_to_ext(_suffix), do: nil
end