3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2012 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "filecache.h"
22 #include "clientserver.h"
31 bool FileCache::loadByPath(const std::string &name, std::ostream &os,
32 const std::string &path)
34 std::ifstream fis(path.c_str(), std::ios_base::binary);
37 infostream<<"FileCache: File not found in cache: "
38 <<name << " expected it at: "<<path<<std::endl;
46 std::streamsize len = fis.gcount();
56 infostream<<"FileCache: Failed to read file from cache: \""
57 <<path<<"\""<<std::endl;
63 bool FileCache::updateByPath(const std::string &name, const std::string &data,
64 const std::string &path)
66 std::ofstream file(path.c_str(), std::ios_base::binary |
67 std::ios_base::trunc);
71 errorstream<<"FileCache: Can't write to file at "
76 file.write(data.c_str(), data.length());
82 bool FileCache::loadByName(const std::string &name, std::ostream &os)
84 std::string path = m_dir + DIR_DELIM + name;
85 return loadByPath(name, os, path);
89 bool FileCache::updateByName(const std::string &name, const std::string &data)
91 std::string path = m_dir + DIR_DELIM + name;
92 return updateByPath(name, data, path);
95 std::string FileCache::getPathFromChecksum(const std::string &name,
96 const std::string &checksum)
98 std::string checksum_hex = hex_encode(checksum.c_str(), checksum.length());
99 size_t dot = name.find_last_of('.');;
100 std::string ext = (dot == std::string::npos)? "" :
101 name.substr(dot, std::string::npos);
102 return m_dir + DIR_DELIM + checksum_hex + ext;
105 bool FileCache::loadByChecksum(const std::string &name, std::ostream &os,
106 const std::string &checksum)
108 std::string path = getPathFromChecksum(name, checksum);
109 return loadByPath(name, os, path);
112 bool FileCache::updateByChecksum(const std::string &name,
113 const std::string &data, const std::string &checksum)
115 std::string path = getPathFromChecksum(name, checksum);
116 return updateByPath(name, data, path);