aboutsummaryrefslogtreecommitdiff
path: root/src/Cache.cpp
blob: 84bee977bfe8229324d8f6f9ffbb2e4f2dab8e23 (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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#include "../include/dchat/Cache.hpp"
#include "../include/env.hpp"
#include "../include/dchat/FileUtil.hpp"
#include "../include/dchat/Gif.hpp"
#include <boost/filesystem/convenience.hpp>
#include <process.hpp>
#include <odhtdb/Hash.hpp>
#include <sibs/SafeSerializer.hpp>
#include <sibs/SafeDeserializer.hpp>
#include <libpreview.h>
#include <gd.h>

#if OS_FAMILY == OS_FAMILY_POSIX
#include <pwd.h>
#define toNativeString(str) str
#else
#include <string>
#include <userenv.h>
#include <locale>
#include <codecvt>

static std::wstring toNativeString(const std::string &str)
{
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    return converter.from_bytes(str);
}
#endif

using namespace std;
using namespace TinyProcessLib;

namespace dchat
{
    const i64 CONTENT_NOT_VISIBLE_AGE_MS = 30000; // Delete content from cache after a specified amount of time if the content is not visible on the screen
    
    static 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))
            throw std::runtime_error("Failed to open process token");

        if (!GetUserProfileDirectory(hToken, &homeDir[0], &homeDirLen))
        {
            CloseHandle(hToken);
            throw std::runtime_error("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;
    }
    
    boost::filesystem::path Cache::getImagesDir()
    {
        boost::filesystem::path imagesDir = getDchatDir() / "images";
        boost::filesystem::create_directories(imagesDir);
        return imagesDir;
    }
    
    void Cache::loadBindsFromFile(LoadBindsCallbackFunc callbackFunc)
    {
        assert(callbackFunc);
        StringView fileContent;
        try
        {
            fileContent = getFileContent(getDchatDir() / "binds");
            sibs::SafeDeserializer deserializer((const u8*)fileContent.data, fileContent.size);
            
            while(!deserializer.empty())
            {
                u8 keySize = deserializer.extract<u8>();
                string key;
                key.resize(keySize);
                deserializer.extract((u8*)&key[0], keySize);
                
                u8 valueSize = deserializer.extract<u8>();
                string value;
                value.resize(valueSize);
                deserializer.extract((u8*)&value[0], valueSize);
                
                callbackFunc(key, value);
            }
        }
        catch(FileException &e)
        {
            fprintf(stderr, "Failed to read binds from file, reason: %s\n", e.what());
        }
        
        delete[] fileContent.data;
    }
    
    void Cache::replaceBindsInFile(const unordered_map<string, string> &binds)
    {
        sibs::SafeSerializer serializer;
        for(auto &it : binds)
        {
            serializer.add((u8)it.first.size());
            serializer.add((const u8*)it.first.data(), it.first.size());
            
            serializer.add((u8)it.second.size());
            serializer.add((const u8*)it.second.data(), it.second.size());
        }
        fileReplace(getDchatDir() / "binds", StringView((const char*)serializer.getBuffer().data(), serializer.getBuffer().size()));
    }

    static bool downscaleImage(const boost::filesystem::path &filepath, void *data, const int size, const int newWidth, const int newHeight)
    {
        gdImagePtr imgPtr = gdImageCreateFromPngPtr(size, data);
        if(!imgPtr)
            return false;

        int width = gdImageSX(imgPtr);
        if(width < newWidth)
        {
            gdImageDestroy(imgPtr);
            return false;
        }

        int height = gdImageSX(imgPtr);
        if(height < newHeight)
        {
            gdImageDestroy(imgPtr);
            return false;
        }

        gdImageSetInterpolationMethod(imgPtr, GD_BILINEAR_FIXED);
        gdImagePtr newImgPtr = gdImageScale(imgPtr, newWidth, newHeight);
        if(!newImgPtr)
        {
            gdImageDestroy(imgPtr);
            return false;
        }

        bool success = (gdImageFile(newImgPtr, filepath.string().c_str()) == 0);
        gdImageDestroy(imgPtr);
        gdImageDestroy(newImgPtr);
        return success;
    }
    
    static ContentByUrlResult loadImageFromFile(const boost::filesystem::path &filepath, bool loadFromCache, CreateGifFunc createGifFunc, CreateStaticImageFunc createStaticImageFunc)
    {
        StringView fileContent;
        try
        {
            fileContent = getFileContent(filepath);
            
            std::string webPageTitle;
            std::string webPageDescription;
            bool foundHtmlContent = false;
            preview_state state;
            preview_init(&state);
            size_t offset = 0;
            do
            {
                // TODO: Get file content before doing this, the file might be in utf-16 encoding. That can happen for example if file contains html.
                // Content type can be retrieved from HTTP response header when downloading content
                offset += preview_step(&state, fileContent.data + offset, fileContent.size - offset);
                if(state.step_result == PREVIEW_FOUND_IMAGE)
                {
                    if(Gif::isDataGif(fileContent))
                    {
                        Gif *gif = createGifFunc(fileContent);
                        return { gif, ContentByUrlResult::Type::CACHED };
                    }
                    else
                    {
                        /*
                        if(!loadFromCache)
                        {
                            if(!downscaleImage(filepath, (void*)fileContent.data, fileContent.size, 100, 100))
                            {
                                fprintf(stderr, "Failed to resize image: %s, using original file\n", filepath.c_str());
                            }
                        }
                        */
                        StaticImage *image = createStaticImageFunc(filepath);
                        delete[] fileContent.data;
                        fileContent.data = nullptr;
                        return { image, ContentByUrlResult::Type::CACHED };
                    }
                }
                else if(state.step_result == PREVIEW_FOUND_TITLE)
                {
                    foundHtmlContent = true;
                    webPageTitle = std::string(state.meta_content, state.meta_content + state.meta_content_length);
                }
                else if(state.step_result == PREVIEW_FOUND_DESCRIPTION)
                {
                    foundHtmlContent = true;
                    webPageDescription = std::string(state.meta_content, state.meta_content + state.meta_content_length);
                }
            } while(offset < fileContent.size);
            
            delete[] fileContent.data;
            fileContent.data = nullptr;
            
            if(foundHtmlContent)
            {
                WebPagePreview *webPagePreview = new WebPagePreview { webPageTitle, webPageDescription };
                return { webPagePreview, ContentByUrlResult::Type::CACHED };
            }
        }
        catch(std::exception &e)
        {
            fprintf(stderr, "Failed to load image %s, reason: %s\n", filepath.string().c_str(), e.what());
        }
        return { (StaticImage*)nullptr, ContentByUrlResult::Type::FAILED_DOWNLOAD };
    }
    
    Cache::Cache(CreateGifFunc _createGifFunc, CreateStaticImageFunc _createStaticImageFunc) : 
        alive(true),
        createGifFunc(_createGifFunc),
        createStaticImageFunc(_createStaticImageFunc)
    {
        assert(createGifFunc);
        assert(createStaticImageFunc);
        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))
                    {
                        boost::filesystem::path filepath = getImagesDir();
                        odhtdb::Hash urlHash(it->url.data(), it->url.size());
                        filepath /= urlHash.toString();
                            
                        ContentByUrlResult contentByUrlResult;
                        bool failed = exitStatus != 0;
                        if(failed)
                        {
                            contentByUrlResult = { (StaticImage*)nullptr, ContentByUrlResult::Type::FAILED_DOWNLOAD };
                        }
                        else
                        {
                            contentByUrlResult = loadImageFromFile(filepath, false, createGifFunc, createStaticImageFunc);
                            contentByUrlResult.lastAccessed = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count();
                            if(contentByUrlResult.type == ContentByUrlResult::Type::CACHED)
                            {
                                printf("Download content from url: %s\n", it->url.c_str());
                            }
                        }
                        
                        imageDownloadMutex.lock();
                        contentUrlCache[it->url] = contentByUrlResult;
                        boost::filesystem::path downloadingFilepath = filepath;
                        downloadingFilepath += ".downloading";
                        // Intentionally ignore failure, program should not crash if we fail to remove these files...
                        boost::system::error_code err;
                        boost::filesystem::remove(downloadingFilepath, err);
                        imageDownloadMutex.unlock();
                        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));
            }
        });
        
        checkContentAccessTimeThread = thread([this]
        {
            // TODO: Add this back
            #if 0
            while(alive)
            {
                this_thread::sleep_for(chrono::milliseconds(500));
                lock_guard<mutex> lock(imageDownloadMutex);
                
                i64 now = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count();
                for(unordered_map<string, ContentByUrlResult>::iterator it = contentUrlCache.begin(); it != contentUrlCache.end();)
                {
                    if(it->second.type == ContentByUrlResult::Type::CACHED && now - it->second.lastAccessed > CONTENT_NOT_VISIBLE_AGE_MS)
                    {
                        switch(it->second.cachedType)
                        {
                            case ContentByUrlResult::CachedType::TEXTURE_FILEPATH:
                            {
                                delete it->second.textureFilePath;
                                break;
                            }
                            case ContentByUrlResult::CachedType::GIF:
                            {
                                delete it->second.gif;
                                break;
                            }
                            case ContentByUrlResult::CachedType::WEB_PAGE_PREVIEW:
                            {
                                delete it->second.webPagePreview;
                                break;
                            }
                            default:
                                ++it;
                                continue;
                        }
                        it = contentUrlCache.erase(it);
                    }
                    else
                        ++it;
                }
            }
            #endif
        });
    }
    
    Cache::~Cache()
    {
        alive = false;
        downloadWaitThread.join();
        checkContentAccessTimeThread.join();
        // TODO: Add this back
        #if 0
        for(auto &it : contentUrlCache)
        {
            if(!it.second.textureFilePath)
                continue;

            switch(it.second.cachedType)
            {
                case ContentByUrlResult::CachedType::NONE:
                    break;
                case ContentByUrlResult::CachedType::TEXTURE_FILEPATH:
                {
                    delete it.second.textureFilePath;
                    break;
                }
                case ContentByUrlResult::CachedType::GIF:
                {
                    delete it.second.gif;
                    break;
                }
                case ContentByUrlResult::CachedType::WEB_PAGE_PREVIEW:
                {
                    delete it.second.webPagePreview;
                    break;
                }
                default:
                    // Did we forget to implement cleanup for a new cache content type?
                    assert(false);
                    break;
            }
        }
        #endif
    }
    
    static void createFileIgnoreError(const boost::filesystem::path &path)
    {
        try
        {
            fileReplace(path, StringView("", 0));
        }
        catch(FileException &e)
        {
            fprintf(stderr, "Failed to create empty file: %s, reason: %s\n", path.string().c_str(), e.what());
        }
    }
    
    const ContentByUrlResult Cache::getContentByUrl(const string &url, int downloadLimitBytes)
    {
        lock_guard<mutex> lock(imageDownloadMutex);
        auto it = contentUrlCache.find(url);
        if(it != contentUrlCache.end())
        {
            it->second.lastAccessed = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count();
            return it->second;
        }
        
        // TODO: Verify hashed url is not too long for filepath on windows
        boost::filesystem::path filepath = getImagesDir();
        odhtdb::Hash urlHash(url.data(), url.size());
        filepath /= urlHash.toString();
        
        boost::filesystem::path downloadingFilepath = filepath;
        downloadingFilepath += ".downloading";
        if(boost::filesystem::exists(downloadingFilepath))
        {
            // Intentionally ignore failure, program should not crash if we fail to remove these files...
            boost::system::error_code err;
            boost::filesystem::remove(filepath, err);
            boost::filesystem::remove(downloadingFilepath, err);
        }
        
        // TODO: Do not load content in this thread. Return LOADING status and load it in another thread, because with a lot of images, chat can freeze
        ContentByUrlResult contentByUrlResult = loadImageFromFile(filepath, true, createGifFunc, createStaticImageFunc);
        if(contentByUrlResult.type == ContentByUrlResult::Type::CACHED)
        {
            contentByUrlResult.lastAccessed = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count();
            contentUrlCache[url] = contentByUrlResult;
            printf("Loaded content from file cache: %s\n", url.c_str());
            return contentByUrlResult;
        }
        else if(contentByUrlResult.type == ContentByUrlResult::Type::FAILED_DOWNLOAD && boost::filesystem::exists(filepath))
        {
            contentUrlCache[url] = contentByUrlResult;
            return contentByUrlResult;
        }
        
        createFileIgnoreError(downloadingFilepath);
        ContentByUrlResult result((StaticImage*)nullptr, ContentByUrlResult::Type::DOWNLOADING);
        contentUrlCache[url] = result;
        
        string downloadLimitBytesStr = to_string(downloadLimitBytes);
        
        std::string cmdUtf8 = "curl -L --silent -o '";
        cmdUtf8 += filepath.string();
        cmdUtf8 += "' --max-filesize " + downloadLimitBytesStr + " --range 0-" + downloadLimitBytesStr + " --url '" + url + "'";
        Process::string_type cmd = toNativeString(cmdUtf8);
        // 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, toNativeString(""), nullptr, nullptr, false);
        ImageDownloadInfo imageDownloadInfo { process, url };
        imageDownloadProcessesQueue.emplace_back(imageDownloadInfo);
        return result;
    }
}