aboutsummaryrefslogtreecommitdiff
path: root/src/Cache.cpp
blob: d402d366c4c4911f0abda7c9fd38adcb34c8f958 (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#include "../include/Cache.hpp"
#include "../include/env.hpp"
#include "../include/ResourceCache.hpp"
#include "../include/FileUtil.hpp"
#include "../include/Gif.hpp"
#include <boost/filesystem/convenience.hpp>
#include <unordered_map>
#include <process.hpp>
#include <odhtdb/Hash.hpp>

#if OS_FAMILY == OS_FAMILY_POSIX
#include <pwd.h>
#else
#include <string>
#endif

using namespace std;
using namespace TinyProcessLib;

namespace dchat
{
    unordered_map<string, ImageByUrlResult> imageUrlCache;
    
    boost::filesystem::path getHomeDir()
    {
    #if OS_FAMILY == OS_FAMILY_POSIX
        const char *homeDir = getenv("HOME");
        if(!homeDir)
        {
            passwd *pw = getpwuid(getuid());
            homeDir = pw->pw_dir;
        }
        return boost::filesystem::path(homeDir);
    #elif OS_FAMILY == OS_FAMILY_WINDOWS
        BOOL ret;
        HANDLE hToken;
        std::wstring homeDir;
        DWORD homeDirLen = MAX_PATH;
        homeDir.resize(homeDirLen);

        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken))
            return Result<FileString>::Err("Failed to open process token");

        if (!GetUserProfileDirectory(hToken, &homeDir[0], &homeDirLen))
        {
            CloseHandle(hToken);
            return Result<FileString>::Err("Failed to get home directory");
        }

        CloseHandle(hToken);
        homeDir.resize(wcslen(homeDir.c_str()));
        return boost::filesystem::path(homeDir);
    #endif
    }
    
    boost::filesystem::path Cache::getDchatDir()
    {
        boost::filesystem::path dchatHomeDir = getHomeDir() / ".local" / "share" / "dchat";
        boost::filesystem::create_directories(dchatHomeDir);
        return dchatHomeDir;
    }
    
    ImageByUrlResult loadImageFromFile(const boost::filesystem::path &filepath)
    {
        try
        {
            StringView fileContent = getFileContent(filepath);
            if(Gif::isDataGif(fileContent))
            {
                Gif *gif = new Gif(move(fileContent));
                return { gif, ImageByUrlResult::Type::CACHED };
            }
            else
            {
                sf::Texture *texture = new sf::Texture();
                if(texture->loadFromMemory(fileContent.data, fileContent.size))
                {
                    delete fileContent.data;
                    texture->setSmooth(true);
                    texture->generateMipmap();
                    return { texture, ImageByUrlResult::Type::CACHED };
                }
                delete texture;
                delete fileContent.data;
            }
        }
        catch(FileException &e)
        {
            
        }
        catch(FailedToLoadResourceException &e)
        {
            
        }
        return { (sf::Texture*)nullptr, ImageByUrlResult::Type::FAILED_DOWNLOAD };
    }
    
    Cache::Cache() : 
        alive(true)
    {
        downloadWaitThread = thread([this]
        {
            while(alive)
            {
                for(vector<ImageDownloadInfo>::iterator it = imageDownloadProcesses.begin(); it != imageDownloadProcesses.end();)
                {
                    int exitStatus;
                    if(it->process->try_get_exit_status(exitStatus))
                    {
                        bool failed = exitStatus != 0;
                        if(!failed)
                        {
                            boost::filesystem::path filepath = getDchatDir();
                            odhtdb::Hash urlHash(it->url.data(), it->url.size());
                            filepath /= urlHash.toString();
                            
                            ImageByUrlResult imageByUrlResult = loadImageFromFile(filepath);
                            imageDownloadMutex.lock();
                            imageUrlCache[it->url] = imageByUrlResult;
                            imageDownloadMutex.unlock();
                            switch(imageByUrlResult.type)
                            {
                                case ImageByUrlResult::Type::CACHED:
                                    printf("Downloaded image from url: %s\n", it->url.c_str());
                                    break;
                                case ImageByUrlResult::Type::FAILED_DOWNLOAD:
                                    printf("Failed to download and load image from url: %s\n", it->url.c_str());
                                    break;
                            }
                        }
                        it = imageDownloadProcesses.erase(it);
                    }
                    else
                        ++it;
                }
                
                while(alive && imageDownloadProcesses.empty() && imageDownloadProcessesQueue.empty())
                    this_thread::sleep_for(chrono::milliseconds(20));
                
                if(!imageDownloadProcessesQueue.empty())
                {
                    imageDownloadMutex.lock();
                    for(auto imageDownloadInfo : imageDownloadProcessesQueue)
                    {
                        imageDownloadProcesses.push_back(imageDownloadInfo);
                    }
                    imageDownloadProcessesQueue.clear();
                    imageDownloadMutex.unlock();
                }
                
                this_thread::sleep_for(chrono::milliseconds(20));
            }
        });
    }
    
    Cache::~Cache()
    {
        alive = false;
        downloadWaitThread.join();
    }
    
    const ImageByUrlResult Cache::getImageByUrl(const string &url, int downloadLimitBytes)
    {
        lock_guard<mutex> lock(imageDownloadMutex);
        auto it = imageUrlCache.find(url);
        if(it != imageUrlCache.end())
            return it->second;
        
        // TODO: Verify hashed url is not too long for filepath on windows
        boost::filesystem::path filepath = getDchatDir();
        odhtdb::Hash urlHash(url.data(), url.size());
        filepath /= urlHash.toString();
        
        ImageByUrlResult imageByUrlResult = loadImageFromFile(filepath);
        if(imageByUrlResult.type == ImageByUrlResult::Type::CACHED)
        {
            imageUrlCache[url] = imageByUrlResult;
            printf("Loaded image from file cache: %s, is gif: %s\n", url.c_str(), imageByUrlResult.isGif ? "yes" : "no");
            return imageByUrlResult;
        }
        
        ImageByUrlResult result((sf::Texture*)nullptr, ImageByUrlResult::Type::DOWNLOADING);
        imageUrlCache[url] = result;
        
        string downloadLimitBytesStr = to_string(downloadLimitBytes);
        
        Process::string_type cmd = "curl -L --silent -o '";
        cmd += filepath.native();
        cmd += "' --max-filesize " + downloadLimitBytesStr + " --range 0-" + downloadLimitBytesStr + " --url '" + url + "'";
        // TODO: Use this instead of curl on windows: certutil.exe -urlcache -split -f "https://url/to/file" path/and/name/to/save/as/file
        Process *process = new Process(cmd, "", nullptr, nullptr, false);
        ImageDownloadInfo imageDownloadInfo { process, url };
        imageDownloadProcessesQueue.emplace_back(imageDownloadInfo);
        return result;
    }
}