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/mpeg", "m4a");
265        add("audio/mpegurl", "m3u");
266        add("audio/ogg", "oga");
267        add("audio/opus", "opus");
268        add("audio/prs.sid", "sid");
269        add("audio/x-aiff", "aif");
270        add("audio/x-aiff", "aiff");
271        add("audio/x-aiff", "aifc");
272        add("audio/x-gsm", "gsm");
273        add("audio/x-matroska", "mka");
274        add("audio/x-mpegurl", "m3u");
275        add("audio/x-ms-wma", "wma");
276        add("audio/x-ms-wax", "wax");
277        add("audio/x-pn-realaudio", "ra");
278        add("audio/x-pn-realaudio", "rm");
279        add("audio/x-pn-realaudio", "ram");
280        add("audio/x-realaudio", "ra");
281        add("audio/x-scpls", "pls");
282        add("audio/x-sd2", "sd2");
283        add("audio/x-wav", "wav");
284        // image/bmp isn't IANA, so image/x-ms-bmp should come first.
285        add("image/x-ms-bmp", "bmp");
286        add("image/bmp", "bmp");
287        add("image/gif", "gif");
288        // image/ico isn't IANA, so image/x-icon should come first.
289        add("image/x-icon", "ico");
290        add("image/ico", "cur");
291        add("image/ico", "ico");
292        add("image/ief", "ief");
293        add("image/heic", "heic");
294        add("image/heif", "heif");
295        add("image/avif", "avif");
296        // add ".jpg" first so it will be the default for guessExtensionFromMimeType
297        add("image/jpeg", "jpg");
298        add("image/jpeg", "jpeg");
299        add("image/jpeg", "jpe");
300        add("image/jpeg", "jfif");
301        add("image/jpeg", "jif");
302        add("image/pcx", "pcx");
303        add("image/png", "png");
304        add("image/svg+xml", "svg");
305        add("image/svg+xml", "svgz");
306        add("image/tiff", "tiff");
307        add("image/tiff", "tif");
308        add("image/vnd.djvu", "djvu");
309        add("image/vnd.djvu", "djv");
310        add("image/vnd.wap.wbmp", "wbmp");
311        add("image/webp", "webp");
312        add("image/x-cmu-raster", "ras");
313        add("image/x-coreldraw", "cdr");
314        add("image/x-coreldrawpattern", "pat");
315        add("image/x-coreldrawtemplate", "cdt");
316        add("image/x-corelphotopaint", "cpt");
317        add("image/x-jg", "art");
318        add("image/x-jng", "jng");
319        add("image/x-photoshop", "psd");
320        add("image/x-portable-anymap", "pnm");
321        add("image/x-portable-bitmap", "pbm");
322        add("image/x-portable-graymap", "pgm");
323        add("image/x-portable-pixmap", "ppm");
324        add("image/x-rgb", "rgb");
325        add("image/x-xbitmap", "xbm");
326        add("image/x-xpixmap", "xpm");
327        add("image/x-xwindowdump", "xwd");
328        add("model/iges", "igs");
329        add("model/iges", "iges");
330        add("model/mesh", "msh");
331        add("model/mesh", "mesh");
332        add("model/mesh", "silo");
333        add("text/calendar", "ics");
334        add("text/calendar", "icz");
335        add("text/comma-separated-values", "csv");
336        add("text/css", "css");
337        add("text/html", "htm");
338        add("text/html", "html");
339        add("text/h323", "323");
340        add("text/iuls", "uls");
341        add("text/javascript", "js");
342        add("text/mathml", "mml");
343        // add ".txt" first so it will be the default for guessExtensionFromMimeType
344        add("text/plain", "txt");
345        add("text/plain", "asc");
346        add("text/plain", "text");
347        add("text/plain", "diff");
348        add("text/plain", "po");     // reserve "pot" for vnd.ms-powerpoint
349        add("text/richtext", "rtx");
350        add("text/rtf", "rtf");
351        add("text/text", "phps");
352        add("text/tab-separated-values", "tsv");
353        add("text/xml", "xml");
354        add("text/x-bibtex", "bib");
355        add("text/x-boo", "boo");
356        add("text/x-c++hdr", "hpp");
357        add("text/x-c++hdr", "h++");
358        add("text/x-c++hdr", "hxx");
359        add("text/x-c++hdr", "hh");
360        add("text/x-c++src", "cpp");
361        add("text/x-c++src", "c++");
362        add("text/x-c++src", "cc");
363        add("text/x-c++src", "cxx");
364        add("text/x-chdr", "h");
365        add("text/x-component", "htc");
366        add("text/x-csh", "csh");
367        add("text/x-csrc", "c");
368        add("text/x-dsrc", "d");
369        add("text/x-haskell", "hs");
370        add("text/x-java", "java");
371        add("text/x-literate-haskell", "lhs");
372        add("text/x-moc", "moc");
373        add("text/x-pascal", "p");
374        add("text/x-pascal", "pas");
375        add("text/x-pcs-gcd", "gcd");
376        add("text/x-setext", "etx");
377        add("text/x-tcl", "tcl");
378        add("text/x-tex", "tex");
379        add("text/x-tex", "ltx");
380        add("text/x-tex", "sty");
381        add("text/x-tex", "cls");
382        add("text/x-vcalendar", "vcs");
383        add("text/x-vcard", "vcf");
384        add("video/avi", "avi");
385        add("video/dl", "dl");
386        add("video/dv", "dif");
387        add("video/dv", "dv");
388        add("video/fli", "fli");
389        add("video/m4v", "m4v");
390        add("video/mp2ts", "ts");
391        add("video/ogg", "ogv");
392        add("video/mpeg", "mpeg");
393        add("video/mpeg", "mpg");
394        add("video/mpeg", "mpe");
395        add("video/mp4", "mp4");
396        add("video/mpeg", "VOB");
397        add("video/quicktime", "qt");
398        add("video/quicktime", "mov");
399        add("video/vnd.mpegurl", "mxu");
400        add("video/webm", "webm");
401        add("video/x-la-asf", "lsf");
402        add("video/x-la-asf", "lsx");
403        add("video/x-matroska", "mkv");
404        add("video/x-mng", "mng");
405        add("video/x-ms-asf", "asf");
406        add("video/x-ms-asf", "asx");
407        add("video/x-ms-wm", "wm");
408        add("video/x-ms-wmv", "wmv");
409        add("video/x-ms-wmx", "wmx");
410        add("video/x-ms-wvx", "wvx");
411        add("video/x-sgi-movie", "movie");
412        add("video/x-webex", "wrf");
413        add("x-conference/x-cooltalk", "ice");
414        add("x-epoc/x-sisx-app", "sisx");
415        applyOverrides();
416    }
417
418    private static void add(String mimeType, String extension) {
419        // If we have an existing x -> y mapping, we do not want to
420        // override it with another mapping x -> y2.
421        // If a mime type maps to several extensions
422        // the first extension added is considered the most popular
423        // so we do not want to overwrite it later.
424        if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
425            mimeTypeToExtensionMap.put(mimeType, extension);
426        }
427        if (!extensionToMimeTypeMap.containsKey(extension)) {
428            extensionToMimeTypeMap.put(extension, mimeType);
429        }
430    }
431
432    private static InputStream getContentTypesPropertiesStream() {
433        // User override?
434        String userTable = System.getProperty("content.types.user.table");
435        if (userTable != null) {
436            File f = new File(userTable);
437            if (f.exists()) {
438                try {
439                    return new FileInputStream(f);
440                } catch (IOException ignored) {
441                }
442            }
443        }
444        // Standard location?
445        File f = new File(System.getProperty("java.home"), "lib" + File.separator + "content-types.properties");
446        if (f.exists()) {
447            try {
448                return new FileInputStream(f);
449            } catch (IOException ignored) {
450            }
451        }
452        return null;
453    }
454
455    /**
456     * This isn't what the RI does. The RI doesn't have hard-coded defaults, so supplying your
457     * own "content.types.user.table" means you don't get any of the built-ins, and the built-ins
458     * come from "$JAVA_HOME/lib/content-types.properties".
459     */
460    private static void applyOverrides() {
461        // Get the appropriate InputStream to read overrides from, if any.
462        InputStream stream = getContentTypesPropertiesStream();
463        if (stream == null) {
464            return;
465        }
466        try {
467            try {
468                // Read the properties file...
469                Properties overrides = new Properties();
470                overrides.load(stream);
471                // And translate its mapping to ours...
472                for (Map.Entry<Object, Object> entry : overrides.entrySet()) {
473                    String extension = (String) entry.getKey();
474                    String mimeType = (String) entry.getValue();
475                    add(mimeType, extension);
476                }
477            } finally {
478                stream.close();
479            }
480        } catch (IOException ignored) {
481        }
482    }
483
484    private MimeUtils() {
485    }
486
487    /**
488     * Returns true if the given MIME type has an entry in the map.
489     *
490     * @param mimeType A MIME type (i.e. text/plain)
491     * @return True iff there is a mimeType entry in the map.
492     */
493    public static boolean hasMimeType(String mimeType) {
494        if (mimeType == null || mimeType.isEmpty()) {
495            return false;
496        }
497        return mimeTypeToExtensionMap.containsKey(mimeType);
498    }
499
500    /**
501     * Returns the MIME type for the given extension.
502     *
503     * @param extension A file extension without the leading '.'
504     * @return The MIME type for the given extension or null iff there is none.
505     */
506    public static String guessMimeTypeFromExtension(String extension) {
507        if (extension == null || extension.isEmpty()) {
508            return null;
509        }
510        return extensionToMimeTypeMap.get(extension.toLowerCase());
511    }
512
513    /**
514     * Returns true if the given extension has a registered MIME type.
515     *
516     * @param extension A file extension without the leading '.'
517     * @return True iff there is an extension entry in the map.
518     */
519    public static boolean hasExtension(String extension) {
520        if (extension == null || extension.isEmpty()) {
521            return false;
522        }
523        return extensionToMimeTypeMap.containsKey(extension);
524    }
525
526    /**
527     * Returns the registered extension for the given MIME type. Note that some
528     * MIME types map to multiple extensions. This call will return the most
529     * common extension for the given MIME type.
530     *
531     * @param mimeType A MIME type (i.e. text/plain)
532     * @return The extension for the given MIME type or null iff there is none.
533     */
534    public static String guessExtensionFromMimeType(String mimeType) {
535        if (mimeType == null || mimeType.isEmpty()) {
536            return null;
537        }
538        return mimeTypeToExtensionMap.get(mimeType.split(";")[0]);
539    }
540
541    public static String guessMimeTypeFromUriAndMime(final Context context, final Uri uri, final String mime) {
542        Log.d(Config.LOGTAG, "guessMimeTypeFromUriAndMime " + uri + " and mime=" + mime);
543        final String guess = guessMimeTypeFromUri(context, uri);
544        if (guess != null) {
545            return guess;
546        } else {
547            return mime;
548        }
549    }
550
551    public static String guessMimeTypeFromUri(Context context, Uri uri) {
552        // try the content resolver
553        String mimeType;
554        try {
555            mimeType = context.getContentResolver().getType(uri);
556        } catch (final Throwable throwable) {
557            mimeType = null;
558        }
559        // try the extension
560        if (mimeType == null || mimeType.equals("application/octet-stream")) {
561            final String path = uri.getPath();
562            if (path != null) {
563                mimeType = guessFromPath(path);
564            }
565        }
566        if (mimeType == null && "content".equals(uri.getScheme())) {
567            final String name = getDisplayName(context, uri);
568            if (name != null) {
569                mimeType = guessFromPath(name);
570            }
571        }
572        // sometimes this works (as with the commit content api)
573        if (mimeType == null) {
574            mimeType = uri.getQueryParameter("mimeType");
575        }
576        return mimeType;
577    }
578
579    private static String getDisplayName(final Context context, final Uri uri) {
580        try (final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
581            if (cursor != null && cursor.moveToFirst()) {
582                final int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
583                if (index == -1) {
584                    return null;
585                }
586                return cursor.getString(index);
587            }
588        } catch (final Exception e) {
589            return null;
590        }
591        return null;
592    }
593
594    public static String guessFromPath(final String path) {
595        final int start = path.lastIndexOf('.') + 1;
596        if (start < path.length()) {
597            return MimeUtils.guessMimeTypeFromExtension(path.substring(start));
598        }
599        return null;
600    }
601
602    public static String extractRelevantExtension(final String path) {
603        return extractRelevantExtension(path, false);
604    }
605
606    public static String extractRelevantExtension(final String path, final boolean ignoreCryptoExtension) {
607        if (Strings.isNullOrEmpty(path)) {
608            return null;
609        }
610
611        final String filenameQueryAnchor = path.substring(path.lastIndexOf('/') + 1);
612        final String filenameQuery = cutBefore(filenameQueryAnchor, '#');
613        final String filename = cutBefore(filenameQuery, '?');
614        final int dotPosition = filename.lastIndexOf('.');
615
616        if (dotPosition == -1) {
617            return null;
618        }
619        final String extension = filename.substring(dotPosition + 1);
620        // we want the real file extension, not the crypto one
621        if (ignoreCryptoExtension && Transferable.VALID_CRYPTO_EXTENSIONS.contains(extension)) {
622            return extractRelevantExtension(filename.substring(0, dotPosition));
623        } else {
624            return extension;
625        }
626    }
627
628    private static String cutBefore(final String input, final char c) {
629        final int position = input.indexOf(c);
630        if (position > 0) {
631            return input.substring(0, position);
632        } else {
633            return input;
634        }
635    }
636}