aboutsummaryrefslogtreecommitdiff
path: root/src/Cache.cpp
blob: ba57d4c01f31da2151d1b76cc649c985754de82c (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
#include "../include/Cache.hpp"
#include "../include/env.hpp"
#include "../include/ResourceCache.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() / ".dchat";
        boost::filesystem::create_directories(dchatHomeDir);
        return dchatHomeDir;
    }
    
    Cache::Cache()
    {
        downloadWaitThread = thread([this]
        {
            while(true)
            {
                imageDownloadMutex.lock();
                for(vector<ImageDownloadInfo>::iterator it = imageDownloadProcesses.begin(); it != imageDownloadProcesses.end();)
                {
                    int exitStatus;
                    if(it->process->try_get_exit_status(exitStatus))
                    {
                        bool failed = exitStatus != 0;
                        ImageByUrlResult &imageByUrlResult = imageUrlCache[it->url];
                        
                        if(!failed)
                        {
                            boost::filesystem::path filepath = getDchatDir();
                            odhtdb::Hash urlHash(it->url.data(), it->url.size());
                            filepath /= urlHash.toString();
                                
                            try
                            {
                                sf::Texture *texture = ResourceCache::getTexture(filepath.string());
                                imageByUrlResult.texture = texture;
                                imageByUrlResult.type = ImageByUrlResult::Type::CACHED;
                                printf("Image downloaded from url: %s, texture: %u\n", it->url.c_str(), texture);
                            }
                            catch(FailedToLoadResourceException &e)
                            {
                                fprintf(stderr, "%s\n", e.what());
                                failed = true;
                            }
                        }
                        
                        if(failed)
                        {
                            imageByUrlResult.type = ImageByUrlResult::Type::FAILED_DOWNLOAD;
                            fprintf(stderr, "Image download failed for url: %s\n", it->url.c_str());
                        }
                            
                        it = imageDownloadProcesses.erase(it);
                    }
                    else
                        ++it;
                }
                imageDownloadMutex.unlock();
                
                while(imageDownloadProcesses.empty())
                    this_thread::sleep_for(chrono::milliseconds(20));
                
                this_thread::sleep_for(chrono::milliseconds(20));
            }
        });
        downloadWaitThread.detach();
    }
    
    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();
        
        // Check if file exists because we dont want sfml spam with "Failed to load image""...
        if(boost::filesystem::exists(filepath))
        {
            try
            {
                sf::Texture *texture = ResourceCache::getTexture(filepath.string());
                ImageByUrlResult result { texture, ImageByUrlResult::Type::CACHED };
                imageUrlCache[url] = result;
                printf("Loading image from file cache: %s\n", url.c_str());
                return result;
            }
            catch(FailedToLoadResourceException &e)
            {
                
            }
        }
        
        ImageByUrlResult result { 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 + "'";
        // 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 };
        imageDownloadProcesses.emplace_back(imageDownloadInfo);
        return result;
    }
}