1 // Copyright 2015 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "webservd/temp_file_manager.h"
16 
17 #include <base/format_macros.h>
18 #include <base/files/file_util.h>
19 #include <base/strings/stringprintf.h>
20 
21 namespace webservd {
22 
TempFileManager(const base::FilePath & temp_dir_path,FileDeleterInterface * file_deleter)23 TempFileManager::TempFileManager(const base::FilePath& temp_dir_path,
24                                  FileDeleterInterface* file_deleter)
25     : temp_dir_path_{temp_dir_path}, file_deleter_{file_deleter} {
26 }
27 
~TempFileManager()28 TempFileManager::~TempFileManager() {
29   for (const auto& pair : request_files_)
30     DeleteFiles(pair.second);
31 }
32 
CreateTempFileName(const std::string & request_id)33 base::FilePath TempFileManager::CreateTempFileName(
34     const std::string& request_id) {
35   std::vector<base::FilePath>& file_list_ref = request_files_[request_id];
36   std::string name = base::StringPrintf("%s-%" PRIuS, request_id.c_str(),
37                                         file_list_ref.size() + 1);
38   base::FilePath file_name = temp_dir_path_.AppendASCII(name);
39   file_list_ref.push_back(file_name);
40   return file_name;
41 }
42 
DeleteRequestTempFiles(const std::string & request_id)43 void TempFileManager::DeleteRequestTempFiles(const std::string& request_id) {
44   auto iter = request_files_.find(request_id);
45   if (iter == request_files_.end())
46     return;
47   DeleteFiles(iter->second);
48   request_files_.erase(iter);
49 }
50 
DeleteFiles(const std::vector<base::FilePath> & files)51 void TempFileManager::DeleteFiles(const std::vector<base::FilePath>& files) {
52   for (const base::FilePath& file : files)
53     CHECK(file_deleter_->DeleteFile(file));
54 }
55 
DeleteFile(const base::FilePath & path)56 bool FileDeleter::DeleteFile(const base::FilePath& path) {
57   return base::DeleteFile(path, false);
58 }
59 
60 }  // namespace webservd
61