This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathasset_file_source.cpp
70 lines (56 loc) · 2.1 KB
/
asset_file_source.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <mbgl/storage/asset_file_source.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/string.hpp>
#include <mbgl/util/thread.hpp>
#include <mbgl/util/url.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/io.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace mbgl {
class AssetFileSource::Impl {
public:
Impl(std::string root_)
: root(std::move(root_)) {
}
void request(const std::string& url, FileSource::Callback callback) {
std::string path;
if (url.size() <= 8 || url[8] == '/') {
// This is an empty or absolute path.
path = mbgl::util::percentDecode(url.substr(8));
} else {
// This is a relative path. Prefix with the application root.
path = root + "/" + mbgl::util::percentDecode(url.substr(8));
}
Response response;
struct stat buf;
int result = stat(path.c_str(), &buf);
if (result == 0 && S_ISDIR(buf.st_mode)) {
response.error = std::make_unique<Response::Error>(Response::Error::Reason::NotFound);
} else if (result == -1 && errno == ENOENT) {
response.error = std::make_unique<Response::Error>(Response::Error::Reason::NotFound);
} else {
try {
response.data = std::make_shared<std::string>(util::read_file(path));
} catch (...) {
response.error = std::make_unique<Response::Error>(
Response::Error::Reason::Other,
util::toString(std::current_exception()));
}
}
callback(response);
}
private:
std::string root;
};
AssetFileSource::AssetFileSource(const std::string& root)
: thread(std::make_unique<util::Thread<Impl>>(
util::ThreadContext{"AssetFileSource", util::ThreadPriority::Low},
root)) {
}
AssetFileSource::~AssetFileSource() = default;
std::unique_ptr<AsyncRequest> AssetFileSource::request(const Resource& resource, Callback callback) {
return thread->invokeWithCallback(&Impl::request, resource.url, callback);
}
} // namespace mbgl