~aleteoryx/muditaos

ref: 65f30a0df267b73d985840af30e31b44c0235dcd muditaos/module-services/service-fileindexer/InotifyHandler.cpp -rw-r--r-- 6.2 KiB
65f30a0d — Pawel Olejniczak [CP-1448] Add storage info to device info endpoint 3 years ago
                                                                                
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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include <service-fileindexer/InotifyHandler.hpp>

#include "Common.hpp"

#include <filesystem>
#include <log/log.hpp>
#include <module-db/queries/multimedia_files/QueryMultimediaFilesAdd.hpp>
#include <module-db/queries/multimedia_files/QueryMultimediaFilesRemove.hpp>
#include <purefs/fs/inotify_message.hpp>
#include <purefs/fs/inotify.hpp>
#include <service-db/DBServiceAPI.hpp>
#include <tags_fetcher/TagsFetcher.hpp>

namespace service::detail
{
    InotifyHandler::~InotifyHandler()
    {
        for (const auto &path : monitoredPaths) {
            const auto err = mfsNotifier->rm_watch(path);
            if (err) {
                LOG_ERROR("Unable to remove watch errno: %i", err);
            }
        }
    }

    bool InotifyHandler::init(std::shared_ptr<sys::Service> service)
    {
        svc         = service;
        mfsNotifier = purefs::fs::inotify_create(svc);
        if (!mfsNotifier) {
            LOG_ERROR("Unable to create inotify object");
            return false;
        }
        registerMessageHandlers();
        return true;
    }

    void InotifyHandler::registerMessageHandlers()
    {
        if (svc == nullptr) {
            LOG_ERROR("svc is nullptr");
            return;
        }
        svc->connect(typeid(purefs::fs::message::inotify), [&](sys::Message *request) -> sys::MessagePointer {
            return handleInotifyMessage(static_cast<purefs::fs::message::inotify *>(request));
        });
    }

    bool InotifyHandler::addWatch(std::string_view monitoredPath)
    {
        if (mfsNotifier == nullptr) {
            LOG_ERROR("mfsNotifier is nullptr");
            return false;
        }
        // Wait for close, delete move to or from location
        const auto err =
            mfsNotifier->add_watch(monitoredPath,
                                   purefs::fs::inotify_flags::close_write | purefs::fs::inotify_flags::del |
                                       purefs::fs::inotify_flags::move_dst | purefs::fs::inotify_flags::move_src);
        if (err) {
            LOG_ERROR("Unable to create inotify watch errno: %i", err);
            return false;
        }
        monitoredPaths.emplace_back(monitoredPath);
        return true;
    }

    sys::MessagePointer InotifyHandler::handleInotifyMessage(purefs::fs::message::inotify *inotify)
    {
        if (inotify == nullptr)
            return sys::msgNotHandled();

        if (inotify->flags && (purefs::fs::inotify_flags::close_write | purefs::fs::inotify_flags::move_dst)) {
            onUpdateOrCreate(inotify->name);
        }
        else if (inotify->flags && (purefs::fs::inotify_flags::del | purefs::fs::inotify_flags::move_src)) {
            onRemove(inotify->name);
        }

        return sys::msgHandled();
    }

    namespace fs = std::filesystem;
    namespace
    {
        std::string getMimeType(const fs::path &path)
        {
            auto extension = path.extension();

            if (extension == ".mp3") {
                return "audio/mpeg";
            }
            if (extension == ".wav") {
                return "audio/wav";
            }
            if (extension == ".flac") {
                return "audio/flac";
            }
            return {};
        }

        std::optional<db::multimedia_files::MultimediaFilesRecord> CreateMultimediaFilesRecord(const fs::path &path)
        {
            std::error_code errorCode;
            auto fileSize = fs::file_size(path, errorCode);
            if (errorCode) {
                LOG_WARN("Can't get file size");
                return {};
            }
            auto mimeType = getMimeType(path);
            auto tags     = tags::fetcher::fetchTags(path);

            db::multimedia_files::MultimediaFilesRecord record{
                Record(DB_ID_NONE),
                .fileInfo = {.path = std::string(path), .mediaType = mimeType, .size = static_cast<size_t>(fileSize)},
                .tags =
                    {
                        .title = tags.title,
                        .album =
                            {
                                .artist = tags.artist,
                                .title  = tags.album,
                            },
                        .comment = tags.comment,
                        .genre   = tags.genre,
                        .year    = tags.year,
                        .track   = tags.track,
                    },
                .audioProperties = {.songLength = tags.total_duration_s,
                                    .bitrate    = tags.bitrate,
                                    .sampleRate = tags.sample_rate,
                                    .channels   = tags.num_channel}};

            return record;
        }
    } // namespace

    // On update or create content
    void InotifyHandler::onUpdateOrCreate(std::string_view path)
    {
        LOG_DEBUG("onUpdateOrCreate: %s", std::string(path).c_str());
        if (svc == nullptr) {
            LOG_ERROR("svc is nullptr");
            return;
        }

        auto ext = fs::path(path).extension();
        if (!isExtSupported(ext)) {
            LOG_WARN("Not supported ext - %s", ext.c_str());
            return;
        }

        auto record = CreateMultimediaFilesRecord(path);
        if (record.has_value()) {
            auto query = std::make_unique<db::multimedia_files::query::Add>(record.value());
            DBServiceAPI::GetQuery(svc.get(), db::Interface::Name::MultimediaFiles, std::move(query));
        }
        else {
            LOG_INFO("onUpdateOrCreate: skipped file");
        }
    }

    // On remove content
    void InotifyHandler::onRemove(std::string_view path)
    {
        LOG_DEBUG("onRemove path: %s", std::string(path).c_str());
        if (svc == nullptr) {
            LOG_ERROR("svc is nullptr");
            return;
        }

        auto ext = fs::path(path).extension();
        if (!isExtSupported(ext)) {
            LOG_WARN("Not supported ext - %s", ext.c_str());
            return;
        }

        auto query = std::make_unique<db::multimedia_files::query::RemoveByPath>(std::string(path));
        DBServiceAPI::GetQuery(svc.get(), db::Interface::Name::MultimediaFiles, std::move(query));
    }

} // namespace service::detail