Fixed a few problems, added a debugging configuration variable
[theodwalha.git] / source / temporary.cpp
blob1d84311110a846eae08ea663bd9f487cc676e8a9
1 #include <ail/file.hpp>
2 #include <ail/random.hpp>
3 #include <ail/types.hpp>
4 #include <ail/time.hpp>
5 #include <ail/types.hpp>
6 #include <boost/foreach.hpp>
7 #include <theodwalha/temporary.hpp>
8 #include <theodwalha/configuration.hpp>
10 temporary_file_entry::temporary_file_entry(std::string const & name):
11 name(name),
12 timestamp(ail::time())
16 bool temporary_file_entry::operator<(temporary_file_entry const & other) const
18 return name < other.name;
21 bool temporary_file_entry::operator==(temporary_file_entry const & other) const
23 return name == other.name;
26 temporary_file_manager::temporary_file_manager(std::string const & directory):
27 directory(directory)
31 bool temporary_file_manager::initialise()
33 ail::create_directory(directory);
34 return clean_all();
37 char get_random_character(char initial_value, uword maximum)
39 return static_cast<char>(initial_value + ail::random_integer<uword>(0, maximum - 1));
42 std::string temporary_file_manager::generate_name()
44 while(true)
46 std::string name;
47 for(std::size_t i = 0; i < temporary_file_name_length; i++)
49 if(ail::random_integer<uword>(0, 1) == 0)
50 name.push_back(get_random_character('0', 10));
51 else
52 name.push_back(get_random_character('a', 26));
54 std::string path = ail::join_paths(directory, name);
55 if(!ail::file_exists(name))
57 boost::mutex::scoped_lock scoped_lock(mutex);
58 files.insert(temporary_file_entry(name));
59 return path;
64 void temporary_file_manager::release(std::string const & path)
66 boost::mutex::scoped_lock scoped_lock(mutex);
68 if(ail::remove_file(path))
69 files.erase(path);
72 bool temporary_file_manager::clean()
74 boost::mutex::scoped_lock scoped_lock(mutex);
76 ulong current_time = ail::time();
77 string_vector removed_strings;
78 BOOST_FOREACH(temporary_file_entry const & file_entry, files)
80 if(current_time - file_entry.timestamp < temporary_file_expiration)
81 continue;
83 if(ail::remove_file(file_entry.name))
84 removed_strings.push_back(file_entry.name);
87 BOOST_FOREACH(std::string const & path, removed_strings)
88 files.erase(path);
90 return true;
93 bool temporary_file_manager::clean_all()
95 boost::mutex::scoped_lock scoped_lock(mutex);
97 string_vector
98 files,
99 directories;
101 if(!ail::read_directory(directory, files, directories))
102 return false;
104 BOOST_FOREACH(std::string const & file, files)
106 std::string path = ail::join_paths(directory, file);
107 //std::cout << "Deleting " << path << std::endl;
108 ail::remove_file(path);
111 return true;