1// Copyright 2012 The Chromium Authors 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "net/base/platform_mime_util.h" 6 7#import <Foundation/Foundation.h> 8#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h> 9 10#include <string> 11 12#include "base/apple/bridging.h" 13#include "base/apple/foundation_util.h" 14#include "base/apple/scoped_cftyperef.h" 15#include "base/notreached.h" 16#include "base/strings/sys_string_conversions.h" 17#include "build/build_config.h" 18 19#if BUILDFLAG(IS_IOS) 20#include <MobileCoreServices/MobileCoreServices.h> 21#else 22#include <CoreServices/CoreServices.h> 23#endif // BUILDFLAG(IS_IOS) 24 25namespace net { 26 27bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension( 28 const base::FilePath::StringType& ext, 29 std::string* result) const { 30 std::string ext_nodot = ext; 31 if (ext_nodot.length() >= 1 && ext_nodot[0] == L'.') { 32 ext_nodot.erase(ext_nodot.begin()); 33 } 34 35 UTType* uttype = 36 [UTType typeWithFilenameExtension:base::SysUTF8ToNSString(ext_nodot)]; 37 // Dynamic UTTypes are made by the system in the event that there's a 38 // non-identifiable mime type. For now, we should treat dynamic UTTypes as a 39 // nonstandard format. 40 if (uttype.dynamic || uttype.preferredMIMEType == nil) { 41 return false; 42 } 43 *result = base::SysNSStringToUTF8(uttype.preferredMIMEType); 44 return true; 45} 46 47bool PlatformMimeUtil::GetPlatformPreferredExtensionForMimeType( 48 std::string_view mime_type, 49 base::FilePath::StringType* ext) const { 50 UTType* uttype = [UTType typeWithMIMEType:base::SysUTF8ToNSString(mime_type)]; 51 if (uttype.dynamic || uttype.preferredFilenameExtension == nil) { 52 return false; 53 } 54 *ext = base::SysNSStringToUTF8(uttype.preferredFilenameExtension); 55 return true; 56} 57 58void PlatformMimeUtil::GetPlatformExtensionsForMimeType( 59 std::string_view mime_type, 60 std::unordered_set<base::FilePath::StringType>* extensions) const { 61 NSArray<UTType*>* types = 62 [UTType typesWithTag:base::SysUTF8ToNSString(mime_type) 63 tagClass:UTTagClassMIMEType 64 conformingToType:nil]; 65 bool extensions_found = false; 66 if (types) { 67 for (UTType* type in types) { 68 if (!type || type.preferredFilenameExtension == nil) { 69 continue; 70 } 71 extensions_found = true; 72 NSArray<NSString*>* extensions_list = 73 type.tags[UTTagClassFilenameExtension]; 74 for (NSString* extension in extensions_list) { 75 extensions->insert(base::SysNSStringToUTF8(extension)); 76 } 77 } 78 } 79 80 if (extensions_found) { 81 return; 82 } 83 84 base::FilePath::StringType ext; 85 if (GetPlatformPreferredExtensionForMimeType(mime_type, &ext)) { 86 extensions->insert(ext); 87 } 88} 89 90} // namespace net 91