• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 #include <string>
8 
9 #include "base/strings/utf_string_conversions.h"
10 #include "base/win/registry.h"
11 
12 namespace net {
13 
GetPlatformMimeTypeFromExtension(const base::FilePath::StringType & ext,std::string * result) const14 bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension(
15     const base::FilePath::StringType& ext, std::string* result) const {
16   // check windows registry for file extension's mime type (registry key
17   // names are not case-sensitive).
18   std::wstring value, key = L"." + ext;
19   base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).ReadValue(
20       L"Content Type", &value);
21   if (!value.empty()) {
22     *result = WideToUTF8(value);
23     return true;
24   }
25   return false;
26 }
27 
GetPreferredExtensionForMimeType(const std::string & mime_type,base::FilePath::StringType * ext) const28 bool PlatformMimeUtil::GetPreferredExtensionForMimeType(
29     const std::string& mime_type, base::FilePath::StringType* ext) const {
30   std::wstring key(L"MIME\\Database\\Content Type\\" + UTF8ToWide(mime_type));
31   if (base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ).ReadValue(
32           L"Extension", ext) != ERROR_SUCCESS) {
33     return false;
34   }
35   // Strip off the leading dot, this should always be the case.
36   if (!ext->empty() && ext->at(0) == L'.')
37     ext->erase(ext->begin());
38 
39   return true;
40 }
41 
GetPlatformExtensionsForMimeType(const std::string & mime_type,base::hash_set<base::FilePath::StringType> * extensions) const42 void PlatformMimeUtil::GetPlatformExtensionsForMimeType(
43     const std::string& mime_type,
44     base::hash_set<base::FilePath::StringType>* extensions) const {
45   // Multiple extensions could have the given mime type specified as their types
46   // in their 'HKCR\.<extension>\Content Type' keys. Iterating all the HKCR
47   // entries, though, is wildly impractical. Cheat by returning just the
48   // preferred extension.
49   base::FilePath::StringType ext;
50   if (GetPreferredExtensionForMimeType(mime_type, &ext))
51     extensions->insert(ext);
52 }
53 
54 }  // namespace net
55