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