| // Copyright 2026 Google LLC | |
| // | |
| // Licensed under the Apache License, Version 2.0 (the "License"); | |
| // you may not use this file except in compliance with the License. | |
| // You may obtain a copy of the License at | |
| // | |
| // https://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, software | |
| // distributed under the License is distributed on an "AS IS" BASIS, | |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| // See the License for the specific language governing permissions and | |
| // limitations under the License. | |
| // | |
| #include "utils/media_type.h" | |
| #include <string> | |
| #include "absl/base/no_destructor.h" | |
| #include "absl/container/flat_hash_map.h" | |
| #include "absl/status/status.h" | |
| #include "absl/status/statusor.h" | |
| #include "absl/strings/ascii.h" | |
| #include "absl/strings/str_cat.h" | |
| #include "absl/strings/string_view.h" | |
| namespace credentio { | |
| namespace { | |
| // Returns the part of the filename after the final ".", or an empty string if | |
| // the filename does not have a ".". | |
| absl::string_view GetFileExtension(absl::string_view filename) { | |
| auto dot_pos = filename.rfind('.'); | |
| if (dot_pos == absl::string_view::npos) return ""; | |
| return filename.substr(dot_pos + 1); | |
| } | |
| } // namespace | |
| absl::StatusOr<std::string> MediaType(absl::string_view filename) { | |
| static absl::NoDestructor<absl::flat_hash_map<std::string, std::string>> | |
| kExtensionToMediaType({ | |
| {"avif", "image/avif"}, | |
| {"heic", "image/heic"}, | |
| {"heif", "image/heif"}, | |
| {"jpeg", "image/jpeg"}, | |
| {"jpg", "image/jpeg"}, | |
| {"m4a", "audio/mp4"}, | |
| {"mp4", "video/mp4"}, | |
| {"pdf", "application/pdf"}, | |
| {"png", "image/png"}, | |
| {"webp", "image/webp"}, | |
| {"mov", "video/quicktime"}, | |
| {"dng", "image/x-adobe-dng"}, | |
| {"tif", "image/tiff"}, | |
| {"tiff", "image/tiff"}, | |
| {"wav", "audio/wav"}, // Not formally registered. | |
| {"avi", "video/x-msvideo"}, | |
| {"gif", "image/gif"}, | |
| {"mp3", "audio/mpeg"}, | |
| {"flac", "audio/flac"}, | |
| {"pptx", | |
| "application/" | |
| "vnd.openxmlformats-officedocument.presentationml.presentation"}, | |
| {"docx", | |
| "application/" | |
| "vnd.openxmlformats-officedocument.wordprocessingml.document"}, | |
| {"xlsx", | |
| "application/" | |
| "vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, | |
| }); | |
| std::string extension = absl::AsciiStrToLower(GetFileExtension(filename)); | |
| auto it = kExtensionToMediaType->find(extension); | |
| if (it != kExtensionToMediaType->end()) { | |
| return it->second; | |
| } | |
| return absl::InvalidArgumentError( | |
| absl::StrCat("Unsupported file extension: \"", extension, "\"")); | |
| } | |
| } // namespace credentio |