MimeUtils.java

  1/*
  2 * Copyright (C) 2010 The Android Open Source Project
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 *      http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 */
 16package eu.siacs.conversations.utils;
 17import android.content.Context;
 18import android.net.Uri;
 19
 20import java.io.File;
 21import java.io.FileInputStream;
 22import java.io.IOException;
 23import java.io.InputStream;
 24import java.util.HashMap;
 25import java.util.Map;
 26import java.util.Properties;
 27/**
 28 * Utilities for dealing with MIME types.
 29 * Used to implement java.net.URLConnection and android.webkit.MimeTypeMap.
 30 */
 31public final class MimeUtils {
 32    private static final Map<String, String> mimeTypeToExtensionMap = new HashMap<String, String>();
 33    private static final Map<String, String> extensionToMimeTypeMap = new HashMap<String, String>();
 34    static {
 35        // The following table is based on /etc/mime.types data minus
 36        // chemical/* MIME types and MIME types that don't map to any
 37        // file extensions. We also exclude top-level domain names to
 38        // deal with cases like:
 39        //
 40        // mail.google.com/a/google.com
 41        //
 42        // and "active" MIME types (due to potential security issues).
 43        // Note that this list is _not_ in alphabetical order and must not be sorted.
 44        // The "most popular" extension must come first, so that it's the one returned
 45        // by guessExtensionFromMimeType.
 46        add("application/andrew-inset", "ez");
 47        add("application/dsptype", "tsp");
 48        add("application/hta", "hta");
 49        add("application/mac-binhex40", "hqx");
 50        add("application/mathematica", "nb");
 51        add("application/msaccess", "mdb");
 52        add("application/oda", "oda");
 53        add("application/ogg", "ogg");
 54        add("application/ogg", "oga");
 55        add("application/pdf", "pdf");
 56        add("application/pgp-keys", "key");
 57        add("application/pgp-signature", "pgp");
 58        add("application/pics-rules", "prf");
 59        add("application/pkix-cert", "cer");
 60        add("application/rar", "rar");
 61        add("application/rdf+xml", "rdf");
 62        add("application/rss+xml", "rss");
 63        add("application/zip", "zip");
 64        add("application/vnd.android.package-archive", "apk");
 65        add("application/vnd.cinderella", "cdy");
 66        add("application/vnd.ms-pki.stl", "stl");
 67        add("application/vnd.oasis.opendocument.database", "odb");
 68        add("application/vnd.oasis.opendocument.formula", "odf");
 69        add("application/vnd.oasis.opendocument.graphics", "odg");
 70        add("application/vnd.oasis.opendocument.graphics-template", "otg");
 71        add("application/vnd.oasis.opendocument.image", "odi");
 72        add("application/vnd.oasis.opendocument.spreadsheet", "ods");
 73        add("application/vnd.oasis.opendocument.spreadsheet-template", "ots");
 74        add("application/vnd.oasis.opendocument.text", "odt");
 75        add("application/vnd.oasis.opendocument.text-master", "odm");
 76        add("application/vnd.oasis.opendocument.text-template", "ott");
 77        add("application/vnd.oasis.opendocument.text-web", "oth");
 78        add("application/vnd.google-earth.kml+xml", "kml");
 79        add("application/vnd.google-earth.kmz", "kmz");
 80        add("application/msword", "doc");
 81        add("application/msword", "dot");
 82        add("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
 83        add("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx");
 84        add("application/vnd.ms-excel", "xls");
 85        add("application/vnd.ms-excel", "xlt");
 86        add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
 87        add("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx");
 88        add("application/vnd.ms-powerpoint", "ppt");
 89        add("application/vnd.ms-powerpoint", "pot");
 90        add("application/vnd.ms-powerpoint", "pps");
 91        add("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
 92        add("application/vnd.openxmlformats-officedocument.presentationml.template", "potx");
 93        add("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx");
 94        add("application/vnd.rim.cod", "cod");
 95        add("application/vnd.smaf", "mmf");
 96        add("application/vnd.stardivision.calc", "sdc");
 97        add("application/vnd.stardivision.draw", "sda");
 98        add("application/vnd.stardivision.impress", "sdd");
 99        add("application/vnd.stardivision.impress", "sdp");
100        add("application/vnd.stardivision.math", "smf");
101        add("application/vnd.stardivision.writer", "sdw");
102        add("application/vnd.stardivision.writer", "vor");
103        add("application/vnd.stardivision.writer-global", "sgl");
104        add("application/vnd.sun.xml.calc", "sxc");
105        add("application/vnd.sun.xml.calc.template", "stc");
106        add("application/vnd.sun.xml.draw", "sxd");
107        add("application/vnd.sun.xml.draw.template", "std");
108        add("application/vnd.sun.xml.impress", "sxi");
109        add("application/vnd.sun.xml.impress.template", "sti");
110        add("application/vnd.sun.xml.math", "sxm");
111        add("application/vnd.sun.xml.writer", "sxw");
112        add("application/vnd.sun.xml.writer.global", "sxg");
113        add("application/vnd.sun.xml.writer.template", "stw");
114        add("application/vnd.visio", "vsd");
115        add("application/x-abiword", "abw");
116        add("application/x-apple-diskimage", "dmg");
117        add("application/x-bcpio", "bcpio");
118        add("application/x-bittorrent", "torrent");
119        add("application/x-cdf", "cdf");
120        add("application/x-cdlink", "vcd");
121        add("application/x-chess-pgn", "pgn");
122        add("application/x-cpio", "cpio");
123        add("application/x-debian-package", "deb");
124        add("application/x-debian-package", "udeb");
125        add("application/x-director", "dcr");
126        add("application/x-director", "dir");
127        add("application/x-director", "dxr");
128        add("application/x-dms", "dms");
129        add("application/x-doom", "wad");
130        add("application/x-dvi", "dvi");
131        add("application/x-font", "pfa");
132        add("application/x-font", "pfb");
133        add("application/x-font", "gsf");
134        add("application/x-font", "pcf");
135        add("application/x-font", "pcf.Z");
136        add("application/x-freemind", "mm");
137        // application/futuresplash isn't IANA, so application/x-futuresplash should come first.
138        add("application/x-futuresplash", "spl");
139        add("application/futuresplash", "spl");
140        add("application/x-gnumeric", "gnumeric");
141        add("application/x-go-sgf", "sgf");
142        add("application/x-graphing-calculator", "gcf");
143        add("application/x-gtar", "tgz");
144        add("application/x-gtar", "gtar");
145        add("application/x-gtar", "taz");
146        add("application/x-hdf", "hdf");
147        add("application/x-ica", "ica");
148        add("application/x-internet-signup", "ins");
149        add("application/x-internet-signup", "isp");
150        add("application/x-iphone", "iii");
151        add("application/x-iso9660-image", "iso");
152        add("application/x-jmol", "jmz");
153        add("application/x-kchart", "chrt");
154        add("application/x-killustrator", "kil");
155        add("application/x-koan", "skp");
156        add("application/x-koan", "skd");
157        add("application/x-koan", "skt");
158        add("application/x-koan", "skm");
159        add("application/x-kpresenter", "kpr");
160        add("application/x-kpresenter", "kpt");
161        add("application/x-kspread", "ksp");
162        add("application/x-kword", "kwd");
163        add("application/x-kword", "kwt");
164        add("application/x-latex", "latex");
165        add("application/x-lha", "lha");
166        add("application/x-lzh", "lzh");
167        add("application/x-lzx", "lzx");
168        add("application/x-maker", "frm");
169        add("application/x-maker", "maker");
170        add("application/x-maker", "frame");
171        add("application/x-maker", "fb");
172        add("application/x-maker", "book");
173        add("application/x-maker", "fbdoc");
174        add("application/x-mif", "mif");
175        add("application/x-ms-wmd", "wmd");
176        add("application/x-ms-wmz", "wmz");
177        add("application/x-msi", "msi");
178        add("application/x-ns-proxy-autoconfig", "pac");
179        add("application/x-nwc", "nwc");
180        add("application/x-object", "o");
181        add("application/x-oz-application", "oza");
182        add("application/x-pem-file", "pem");
183        add("application/x-pkcs12", "p12");
184        add("application/x-pkcs12", "pfx");
185        add("application/x-pkcs7-certreqresp", "p7r");
186        add("application/x-pkcs7-crl", "crl");
187        add("application/x-quicktimeplayer", "qtl");
188        add("application/x-shar", "shar");
189        add("application/x-shockwave-flash", "swf");
190        add("application/x-stuffit", "sit");
191        add("application/x-sv4cpio", "sv4cpio");
192        add("application/x-sv4crc", "sv4crc");
193        add("application/x-tar", "tar");
194        add("application/x-texinfo", "texinfo");
195        add("application/x-texinfo", "texi");
196        add("application/x-troff", "t");
197        add("application/x-troff", "roff");
198        add("application/x-troff-man", "man");
199        add("application/x-ustar", "ustar");
200        add("application/x-wais-source", "src");
201        add("application/x-wingz", "wz");
202        add("application/x-webarchive", "webarchive");
203        add("application/x-webarchive-xml", "webarchivexml");
204        add("application/x-x509-ca-cert", "crt");
205        add("application/x-x509-user-cert", "crt");
206        add("application/x-x509-server-cert", "crt");
207        add("application/x-xcf", "xcf");
208        add("application/x-xfig", "fig");
209        add("application/xhtml+xml", "xhtml");
210        add("audio/3gpp", "3gpp");
211        add("audio/aac", "aac");
212        add("audio/aac-adts", "aac");
213        add("audio/amr", "amr");
214        add("audio/amr-wb", "awb");
215        add("audio/basic", "snd");
216        add("audio/flac", "flac");
217        add("application/x-flac", "flac");
218        add("audio/imelody", "imy");
219        add("audio/midi", "mid");
220        add("audio/midi", "midi");
221        add("audio/midi", "ota");
222        add("audio/midi", "kar");
223        add("audio/midi", "rtttl");
224        add("audio/midi", "xmf");
225        add("audio/mobile-xmf", "mxmf");
226        // add ".mp3" first so it will be the default for guessExtensionFromMimeType
227        add("audio/mpeg", "mp3");
228        add("audio/mpeg", "mpga");
229        add("audio/mpeg", "mpega");
230        add("audio/mpeg", "mp2");
231        add("audio/mpeg", "m4a");
232        add("audio/mpegurl", "m3u");
233        add("audio/prs.sid", "sid");
234        add("audio/x-aiff", "aif");
235        add("audio/x-aiff", "aiff");
236        add("audio/x-aiff", "aifc");
237        add("audio/x-gsm", "gsm");
238        add("audio/x-matroska", "mka");
239        add("audio/x-mpegurl", "m3u");
240        add("audio/x-ms-wma", "wma");
241        add("audio/x-ms-wax", "wax");
242        add("audio/x-pn-realaudio", "ra");
243        add("audio/x-pn-realaudio", "rm");
244        add("audio/x-pn-realaudio", "ram");
245        add("audio/x-realaudio", "ra");
246        add("audio/x-scpls", "pls");
247        add("audio/x-sd2", "sd2");
248        add("audio/x-wav", "wav");
249        // image/bmp isn't IANA, so image/x-ms-bmp should come first.
250        add("image/x-ms-bmp", "bmp");
251        add("image/bmp", "bmp");
252        add("image/gif", "gif");
253        // image/ico isn't IANA, so image/x-icon should come first.
254        add("image/x-icon", "ico");
255        add("image/ico", "cur");
256        add("image/ico", "ico");
257        add("image/ief", "ief");
258        // add ".jpg" first so it will be the default for guessExtensionFromMimeType
259        add("image/jpeg", "jpg");
260        add("image/jpeg", "jpeg");
261        add("image/jpeg", "jpe");
262        add("image/pcx", "pcx");
263        add("image/png", "png");
264        add("image/svg+xml", "svg");
265        add("image/svg+xml", "svgz");
266        add("image/tiff", "tiff");
267        add("image/tiff", "tif");
268        add("image/vnd.djvu", "djvu");
269        add("image/vnd.djvu", "djv");
270        add("image/vnd.wap.wbmp", "wbmp");
271        add("image/webp", "webp");
272        add("image/x-cmu-raster", "ras");
273        add("image/x-coreldraw", "cdr");
274        add("image/x-coreldrawpattern", "pat");
275        add("image/x-coreldrawtemplate", "cdt");
276        add("image/x-corelphotopaint", "cpt");
277        add("image/x-jg", "art");
278        add("image/x-jng", "jng");
279        add("image/x-photoshop", "psd");
280        add("image/x-portable-anymap", "pnm");
281        add("image/x-portable-bitmap", "pbm");
282        add("image/x-portable-graymap", "pgm");
283        add("image/x-portable-pixmap", "ppm");
284        add("image/x-rgb", "rgb");
285        add("image/x-xbitmap", "xbm");
286        add("image/x-xpixmap", "xpm");
287        add("image/x-xwindowdump", "xwd");
288        add("model/iges", "igs");
289        add("model/iges", "iges");
290        add("model/mesh", "msh");
291        add("model/mesh", "mesh");
292        add("model/mesh", "silo");
293        add("text/calendar", "ics");
294        add("text/calendar", "icz");
295        add("text/comma-separated-values", "csv");
296        add("text/css", "css");
297        add("text/html", "htm");
298        add("text/html", "html");
299        add("text/h323", "323");
300        add("text/iuls", "uls");
301        add("text/mathml", "mml");
302        // add ".txt" first so it will be the default for guessExtensionFromMimeType
303        add("text/plain", "txt");
304        add("text/plain", "asc");
305        add("text/plain", "text");
306        add("text/plain", "diff");
307        add("text/plain", "po");     // reserve "pot" for vnd.ms-powerpoint
308        add("text/richtext", "rtx");
309        add("text/rtf", "rtf");
310        add("text/text", "phps");
311        add("text/tab-separated-values", "tsv");
312        add("text/xml", "xml");
313        add("text/x-bibtex", "bib");
314        add("text/x-boo", "boo");
315        add("text/x-c++hdr", "hpp");
316        add("text/x-c++hdr", "h++");
317        add("text/x-c++hdr", "hxx");
318        add("text/x-c++hdr", "hh");
319        add("text/x-c++src", "cpp");
320        add("text/x-c++src", "c++");
321        add("text/x-c++src", "cc");
322        add("text/x-c++src", "cxx");
323        add("text/x-chdr", "h");
324        add("text/x-component", "htc");
325        add("text/x-csh", "csh");
326        add("text/x-csrc", "c");
327        add("text/x-dsrc", "d");
328        add("text/x-haskell", "hs");
329        add("text/x-java", "java");
330        add("text/x-literate-haskell", "lhs");
331        add("text/x-moc", "moc");
332        add("text/x-pascal", "p");
333        add("text/x-pascal", "pas");
334        add("text/x-pcs-gcd", "gcd");
335        add("text/x-setext", "etx");
336        add("text/x-tcl", "tcl");
337        add("text/x-tex", "tex");
338        add("text/x-tex", "ltx");
339        add("text/x-tex", "sty");
340        add("text/x-tex", "cls");
341        add("text/x-vcalendar", "vcs");
342        add("text/x-vcard", "vcf");
343        add("video/3gpp", "3gpp");
344        add("video/3gpp", "3gp");
345        add("video/3gpp2", "3gpp2");
346        add("video/3gpp2", "3g2");
347        add("video/avi", "avi");
348        add("video/dl", "dl");
349        add("video/dv", "dif");
350        add("video/dv", "dv");
351        add("video/fli", "fli");
352        add("video/m4v", "m4v");
353        add("video/mp2ts", "ts");
354        add("video/mpeg", "mpeg");
355        add("video/mpeg", "mpg");
356        add("video/mpeg", "mpe");
357        add("video/mp4", "mp4");
358        add("video/mpeg", "VOB");
359        add("video/quicktime", "qt");
360        add("video/quicktime", "mov");
361        add("video/vnd.mpegurl", "mxu");
362        add("video/webm", "webm");
363        add("video/x-la-asf", "lsf");
364        add("video/x-la-asf", "lsx");
365        add("video/x-matroska", "mkv");
366        add("video/x-mng", "mng");
367        add("video/x-ms-asf", "asf");
368        add("video/x-ms-asf", "asx");
369        add("video/x-ms-wm", "wm");
370        add("video/x-ms-wmv", "wmv");
371        add("video/x-ms-wmx", "wmx");
372        add("video/x-ms-wvx", "wvx");
373        add("video/x-sgi-movie", "movie");
374        add("video/x-webex", "wrf");
375        add("x-conference/x-cooltalk", "ice");
376        add("x-epoc/x-sisx-app", "sisx");
377        applyOverrides();
378    }
379    private static void add(String mimeType, String extension) {
380        // If we have an existing x -> y mapping, we do not want to
381        // override it with another mapping x -> y2.
382        // If a mime type maps to several extensions
383        // the first extension added is considered the most popular
384        // so we do not want to overwrite it later.
385        if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
386            mimeTypeToExtensionMap.put(mimeType, extension);
387        }
388        if (!extensionToMimeTypeMap.containsKey(extension)) {
389            extensionToMimeTypeMap.put(extension, mimeType);
390        }
391    }
392    private static InputStream getContentTypesPropertiesStream() {
393        // User override?
394        String userTable = System.getProperty("content.types.user.table");
395        if (userTable != null) {
396            File f = new File(userTable);
397            if (f.exists()) {
398                try {
399                    return new FileInputStream(f);
400                } catch (IOException ignored) {
401                }
402            }
403        }
404        // Standard location?
405        File f = new File(System.getProperty("java.home"), "lib" + File.separator + "content-types.properties");
406        if (f.exists()) {
407            try {
408                return new FileInputStream(f);
409            } catch (IOException ignored) {
410            }
411        }
412        return null;
413    }
414    /**
415     * This isn't what the RI does. The RI doesn't have hard-coded defaults, so supplying your
416     * own "content.types.user.table" means you don't get any of the built-ins, and the built-ins
417     * come from "$JAVA_HOME/lib/content-types.properties".
418     */
419    private static void applyOverrides() {
420        // Get the appropriate InputStream to read overrides from, if any.
421        InputStream stream = getContentTypesPropertiesStream();
422        if (stream == null) {
423            return;
424        }
425        try {
426            try {
427                // Read the properties file...
428                Properties overrides = new Properties();
429                overrides.load(stream);
430                // And translate its mapping to ours...
431                for (Map.Entry<Object, Object> entry : overrides.entrySet()) {
432                    String extension = (String) entry.getKey();
433                    String mimeType = (String) entry.getValue();
434                    add(mimeType, extension);
435                }
436            } finally {
437                stream.close();
438            }
439        } catch (IOException ignored) {
440        }
441    }
442    private MimeUtils() {
443    }
444    /**
445     * Returns true if the given MIME type has an entry in the map.
446     * @param mimeType A MIME type (i.e. text/plain)
447     * @return True iff there is a mimeType entry in the map.
448     */
449    public static boolean hasMimeType(String mimeType) {
450        if (mimeType == null || mimeType.isEmpty()) {
451            return false;
452        }
453        return mimeTypeToExtensionMap.containsKey(mimeType);
454    }
455    /**
456     * Returns the MIME type for the given extension.
457     * @param extension A file extension without the leading '.'
458     * @return The MIME type for the given extension or null iff there is none.
459     */
460    public static String guessMimeTypeFromExtension(String extension) {
461        if (extension == null || extension.isEmpty()) {
462            return null;
463        }
464        return extensionToMimeTypeMap.get(extension.toLowerCase());
465    }
466    /**
467     * Returns true if the given extension has a registered MIME type.
468     * @param extension A file extension without the leading '.'
469     * @return True iff there is an extension entry in the map.
470     */
471    public static boolean hasExtension(String extension) {
472        if (extension == null || extension.isEmpty()) {
473            return false;
474        }
475        return extensionToMimeTypeMap.containsKey(extension);
476    }
477    /**
478     * Returns the registered extension for the given MIME type. Note that some
479     * MIME types map to multiple extensions. This call will return the most
480     * common extension for the given MIME type.
481     * @param mimeType A MIME type (i.e. text/plain)
482     * @return The extension for the given MIME type or null iff there is none.
483     */
484    public static String guessExtensionFromMimeType(String mimeType) {
485        if (mimeType == null || mimeType.isEmpty()) {
486            return null;
487        }
488        return mimeTypeToExtensionMap.get(mimeType);
489    }
490
491    public static String guessMimeTypeFromUri(Context context, Uri uri) {
492        // try the content resolver
493        String mimeType;
494        try {
495            mimeType = context.getContentResolver().getType(uri);
496        } catch (Throwable throwable) {
497            mimeType = null;
498        }
499        // try the extension
500        if (mimeType == null && uri.getPath() != null) {
501            String path = uri.getPath();
502            int start = path.lastIndexOf('.') + 1;
503            if (start < path.length()) {
504                mimeType = MimeUtils.guessMimeTypeFromExtension(path.substring(start));
505            }
506        }
507        // sometimes this works (as with the commit content api)
508        if (mimeType == null) {
509            mimeType = uri.getQueryParameter("mimeType");
510        }
511        return mimeType;
512    }
513}