aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/FileManager.cpp
blob: fc6205c8380bba0878f85c811fec78e6baf48092 (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
#include "../../plugins/FileManager.hpp"
#include "../../include/ImageUtils.hpp"
#include <filesystem>

namespace QuickMedia {
    FileManager::FileManager() : Plugin("file-manager"), current_dir("/") {
        
    }

    // Returns empty string if no extension
    static const char* get_ext(const std::filesystem::path &path) {
        const char *path_c = path.c_str();
        int len = strlen(path_c);
        for(int i = len - 1; i >= 0; --i) {
            if(path_c[i] == '.')
                return path_c + i;
        }
        return "";
    }

    PluginResult FileManager::get_files_in_directory(BodyItems &result_items) {
        try {
            for(auto &p : std::filesystem::directory_iterator(current_dir)) {
                auto body_item = std::make_unique<BodyItem>(p.path().filename().string());
                if(p.is_regular_file()) {
                    if(is_image_ext(get_ext(p.path()))) {
                        body_item->thumbnail_is_local = true;
                        body_item->thumbnail_url = p.path().string();
                    }
                }
                result_items.push_back(std::move(body_item));
            }
            return PluginResult::OK;
        } catch(const std::filesystem::filesystem_error &err) {
            fprintf(stderr, "Failed to list files in directory %s, error: %s\n", current_dir.c_str(), err.what());
            return PluginResult::ERR;
        }
    }

    bool FileManager::set_current_directory(const std::string &path) {
        if(!std::filesystem::is_directory(path))
            return false;
        current_dir = path;
        return true;
    }

    bool FileManager::set_child_directory(const std::string &filename) {
        std::filesystem::path new_path = current_dir / filename;
        if(std::filesystem::is_directory(new_path)) {
            current_dir = std::move(new_path);
            return true;
        }
        return false;
    }

    const std::filesystem::path& FileManager::get_current_dir() const {
        return current_dir;
    }
}