~aleteoryx/muditaos

ref: sign_test muditaos/module-db/Tables/MultimediaFilesTable.cpp -rw-r--r-- 15.7 KiB
a217eeb3 — Dawid Wojtas [BH-2024] Fix lack of alarm directory after updating software 1 year, 5 months 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
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
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "MultimediaFilesTable.hpp"
#include "Common/Types.hpp"
#include <Database/QueryResult.hpp>
#include <Utils.hpp>
#include <magic_enum.hpp>
#include <inttypes.h>

namespace
{
    std::string getSorting(db::multimedia_files::SortingBy sorting)
    {
        switch (sorting) {
        case db::multimedia_files::SortingBy::TrackIdAscending:
            return "track ASC";
        case db::multimedia_files::SortingBy::TitleAscending:
        default:
            return "title ASC";
        }
    }
} // namespace

namespace db::multimedia_files
{
    TableRow CreateTableRow(const QueryResult &result)
    {
        if (result.getFieldCount() != magic_enum::enum_count<TableFields>() + 1) {
            return TableRow{};
        }

        return TableRow{
            result[0].getUInt32(),    // ID
            {result[1].getString(),   // path
             result[2].getString(),   // mediaType
             result[3].getUInt32()},  // size
            {result[4].getString(),   // title
             {result[5].getString(),  // artist
              result[6].getString()}, // album title
             result[7].getString(),   // comment
             result[8].getString(),   // genre
             result[9].getUInt32(),   // year
             result[10].getUInt32()}, // track
            {result[11].getUInt32(),  // songLength
             result[12].getUInt32(),  // bitrate
             result[13].getUInt32(),  // sample rate
             result[14].getUInt32()}, // channels
        };
    }

    auto TableRow::isValid() const -> bool
    {
        return (!fileInfo.path.empty() && Record::isValid());
    }

    auto constructMatchPattern = [](const std::vector<std::string> &paths) -> std::string {
        std::string ret;
        for (auto e = paths.begin(); e != paths.end(); e++) {
            ret += "path LIKE '" + *e + "%%'";
            if (std::next(e) != paths.end()) {
                ret += " or ";
            }
        }
        return ret;
    };

    MultimediaFilesTable::MultimediaFilesTable(Database *db) : Table(db)
    {
        createTableRow = CreateTableRow;
    }

    bool MultimediaFilesTable::create()
    {
        return true;
    }

    bool MultimediaFilesTable::add(TableRow entry)
    {
        return db->execute("INSERT INTO files (path, media_type, size, title, artist, album, "
                           "comment, genre, year, track, song_length, bitrate, sample_rate, channels) "
                           "VALUES(" str_c str_c u32_c str_c str_c str_c str_c str_c u32_c u32_c u32_c u32_c u32_c u32_
                           ") "
                           "ON CONFLICT(path) DO UPDATE SET "
                           "path = excluded.path, "
                           "media_type = excluded.media_type, "
                           "size = excluded.size, "
                           "title = excluded.title, "
                           "artist = excluded.artist, "
                           "album = excluded.album, "
                           "comment = excluded.comment, "
                           "genre = excluded.genre, "
                           "year = excluded.year, "
                           "track = excluded.track, "
                           "song_length = excluded.song_length, "
                           "bitrate = excluded.bitrate, "
                           "sample_rate = excluded.sample_rate, "
                           "channels = excluded.channels;",
                           entry.fileInfo.path.c_str(),
                           entry.fileInfo.mediaType.c_str(),
                           entry.fileInfo.size,
                           entry.tags.title.c_str(),
                           entry.tags.album.artist.c_str(),
                           entry.tags.album.title.c_str(),
                           entry.tags.comment.c_str(),
                           entry.tags.genre.c_str(),
                           entry.tags.year,
                           entry.tags.track,
                           entry.audioProperties.songLength,
                           entry.audioProperties.bitrate,
                           entry.audioProperties.sampleRate,
                           entry.audioProperties.channels);
    }

    bool MultimediaFilesTable::removeById(uint32_t id)
    {
        return db->execute("DELETE FROM files WHERE _id=" u32_ ";", id);
    }

    bool MultimediaFilesTable::removeByField(TableFields field, const char *str)
    {
        const auto &fieldName = getFieldName(field);

        if (fieldName.empty()) {
            return false;
        }

        return db->execute("DELETE FROM files WHERE %q=" str_ ";", fieldName.c_str(), str);
    }

    bool MultimediaFilesTable::removeAll()
    {
        return db->execute("DELETE FROM files;");
    }

    bool MultimediaFilesTable::update(TableRow entry)
    {
        return db->execute("UPDATE files SET path=" str_c "media_type=" str_c "size=" u32_c "title=" str_c
                           "artist=" str_c "album=" str_c "comment=" str_c "genre=" str_c "year=" u32_c "track=" u32_c
                           "song_length=" u32_c "bitrate=" u32_c "sample_rate=" u32_c "channels=" u32_
                           " WHERE _id=" u32_ ";",
                           entry.fileInfo.path.c_str(),
                           entry.fileInfo.mediaType.c_str(),
                           entry.fileInfo.size,
                           entry.tags.title.c_str(),
                           entry.tags.album.artist.c_str(),
                           entry.tags.album.title.c_str(),
                           entry.tags.comment.c_str(),
                           entry.tags.genre.c_str(),
                           entry.tags.year,
                           entry.tags.track,
                           entry.audioProperties.songLength,
                           entry.audioProperties.bitrate,
                           entry.audioProperties.sampleRate,
                           entry.audioProperties.channels,
                           entry.ID);
    }

    bool MultimediaFilesTable::addOrUpdate(TableRow entry, std::string oldPath)
    {
        auto path = oldPath.empty() ? entry.fileInfo.path : oldPath;

        return db->execute("BEGIN TRANSACTION; "
                           "INSERT OR IGNORE INTO files (path) VALUES (" str_ "); "
                           "UPDATE files SET path=" str_c "media_type=" str_c "size=" u32_c "title=" str_c
                           "artist=" str_c "album=" str_c "comment=" str_c "genre=" str_c "year=" u32_c "track=" u32_c
                           "song_length=" u32_c "bitrate=" u32_c "sample_rate=" u32_c "channels=" u32_
                           " WHERE path=" str_ "; "
                           "COMMIT;",
                           path.c_str(),
                           entry.fileInfo.path.c_str(),
                           entry.fileInfo.mediaType.c_str(),
                           entry.fileInfo.size,
                           entry.tags.title.c_str(),
                           entry.tags.album.artist.c_str(),
                           entry.tags.album.title.c_str(),
                           entry.tags.comment.c_str(),
                           entry.tags.genre.c_str(),
                           entry.tags.year,
                           entry.tags.track,
                           entry.audioProperties.songLength,
                           entry.audioProperties.bitrate,
                           entry.audioProperties.sampleRate,
                           entry.audioProperties.channels,
                           path.c_str());
    }

    TableRow MultimediaFilesTable::getById(uint32_t id)
    {
        auto retQuery = db->query("SELECT * FROM files WHERE _id=" u32_ ";", id);

        if ((retQuery == nullptr) || (retQuery->getRowCount() == 0)) {
            return TableRow();
        }

        return CreateTableRow(*retQuery);
    }

    TableRow MultimediaFilesTable::getByPath(std::string path)
    {
        auto retQuery = db->query("SELECT * FROM files WHERE path=" str_ ";", path.c_str());

        if ((retQuery == nullptr) || (retQuery->getRowCount() == 0)) {
            return TableRow();
        }

        return CreateTableRow(*retQuery);
    }

    std::vector<TableRow> MultimediaFilesTable::getLimitOffset(uint32_t offset, uint32_t limit)
    {
        auto retQuery =
            db->query("SELECT * from files ORDER BY title ASC LIMIT " u32_ " OFFSET " u32_ ";", limit, offset);

        return retQueryUnpack(std::move(retQuery));
    }

    auto MultimediaFilesTable::getArtistsLimitOffset(uint32_t offset, uint32_t limit) -> std::vector<Artist>
    {
        auto retQuery = db->query(
            "SELECT DISTINCT artist from files ORDER BY artist ASC LIMIT " u32_ " OFFSET " u32_ ";", limit, offset);

        if ((retQuery == nullptr) || (retQuery->getRowCount() == 0)) {
            return {};
        }

        std::vector<Artist> outVector;

        do {
            outVector.push_back((*retQuery)[0].getString()); // artist
        } while (retQuery->nextRow());
        return outVector;
    }

    std::vector<TableRow> MultimediaFilesTable::getLimitOffsetByField(uint32_t offset,
                                                                      uint32_t limit,
                                                                      TableFields field,
                                                                      const char *str)
    {
        std::unique_ptr<QueryResult> retQuery = nullptr;
        const auto &fieldName                 = getFieldName(field);

        if (fieldName.empty() || str == nullptr) {
            return {};
        }

        retQuery = db->query("SELECT * FROM files WHERE %q=" str_ " ORDER BY title ASC LIMIT " u32_ " OFFSET " u32_ ";",
                             fieldName.c_str(),
                             str,
                             limit,
                             offset);

        return retQueryUnpack(std::move(retQuery));
    }

    uint32_t MultimediaFilesTable::count()
    {
        auto queryRet = db->query("SELECT COUNT(*) FROM files;");
        if (!queryRet || queryRet->getRowCount() == 0) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    uint32_t MultimediaFilesTable::countArtists()
    {
        auto queryRet = db->query("SELECT COUNT (DISTINCT artist) FROM files;");
        if (!queryRet || queryRet->getRowCount() == 0) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    auto MultimediaFilesTable::getAlbumsLimitOffset(uint32_t offset, uint32_t limit) -> std::vector<Album>
    {
        auto retQuery =
            db->query("SELECT DISTINCT artist,album from files ORDER BY album ASC LIMIT " u32_ " OFFSET " u32_ ";",
                      limit,
                      offset);

        if ((retQuery == nullptr) || (retQuery->getRowCount() < 2)) {
            return {};
        }

        std::vector<Album> outVector;

        do {
            outVector.push_back({.artist = (*retQuery)[0].getString(), .title = (*retQuery)[1].getString()});
        } while (retQuery->nextRow());
        return outVector;
    }

    uint32_t MultimediaFilesTable::countAlbums()
    {
        auto queryRet = db->query("SELECT COUNT(*) FROM"
                                  "(SELECT DISTINCT artist,album from files);");
        if (!queryRet || queryRet->getRowCount() == 0) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    uint32_t MultimediaFilesTable::countByFieldId(const char *field, uint32_t id)
    {
        if (field == nullptr) {
            return 0;
        }

        auto queryRet = db->query("SELECT COUNT(*) FROM files WHERE " str_ "=" u32_ ";", field, id);
        if ((queryRet == nullptr) || (queryRet->getRowCount() == 0)) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    std::string MultimediaFilesTable::getFieldName(TableFields field)
    {
        return utils::enumToString(field);
    }

    auto MultimediaFilesTable::getLimitOffset(const Artist &artist, uint32_t offset, uint32_t limit)
        -> std::vector<TableRow>
    {
        return getLimitOffsetByField(offset, limit, TableFields::artist, artist.c_str());
    }

    auto MultimediaFilesTable::count(const Artist &artist) -> uint32_t
    {
        auto queryRet = db->query("SELECT COUNT(*) FROM files WHERE artist=" str_ " ;", artist.c_str());
        if ((queryRet == nullptr) || (queryRet->getRowCount() == 0)) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    auto MultimediaFilesTable::getLimitOffset(const Album &album, uint32_t offset, uint32_t limit)
        -> std::vector<TableRow>
    {
        std::unique_ptr<QueryResult> retQuery = db->query("SELECT * FROM files WHERE artist=" str_ " AND album=" str_
                                                          " ORDER BY title ASC LIMIT " u32_ " OFFSET " u32_ ";",
                                                          album.artist.c_str(),
                                                          album.title.c_str(),
                                                          limit,
                                                          offset);

        return retQueryUnpack(std::move(retQuery));
    }

    auto MultimediaFilesTable::count(const Album &album) -> uint32_t
    {
        auto queryRet = db->query("SELECT COUNT(*) FROM files WHERE artist=" str_ " AND album=" str_ ";",
                                  album.artist.c_str(),
                                  album.title.c_str());
        if ((queryRet == nullptr) || (queryRet->getRowCount() == 0)) {
            return 0;
        }

        return (*queryRet)[0].getUInt32();
    }

    auto MultimediaFilesTable::getLimitOffsetByPaths(const std::vector<std::string> &paths,
                                                     std::uint32_t offset,
                                                     std::uint32_t limit,
                                                     SortingBy sorting) -> std::vector<TableRow>
    {
        const std::string query = "SELECT * FROM files WHERE " + constructMatchPattern(paths) + " ORDER BY " +
                                  getSorting(sorting) + " LIMIT " + std::to_string(limit) + " OFFSET " +
                                  std::to_string(offset) + ";";
        std::unique_ptr<QueryResult> retQuery = db->query(query.c_str());
        return retQueryUnpack(std::move(retQuery));
    }

    auto MultimediaFilesTable::count(const std::vector<std::string> &paths) -> uint32_t
    {
        const std::string query = "SELECT COUNT(*) FROM files WHERE " + constructMatchPattern(paths) + ";";
        const auto retQuery     = db->query(query.c_str());

        if ((retQuery == nullptr) || (retQuery->getRowCount() == 0)) {
            return 0;
        }

        return (*retQuery)[0].getUInt32();
    }

    auto MultimediaFilesTable::getOffsetOfSortedRecordByPath(const std::string &folderPath,
                                                             const std::string &recordPath,
                                                             SortingBy sorting) -> SortedRecord
    {
        std::unique_ptr<QueryResult> retQuery =
            db->query("SELECT * FROM ( SELECT ROW_NUMBER () OVER ( ORDER BY %q ) offset, "
                      " path FROM files WHERE path LIKE '%q%%' ) WHERE path='%q'",
                      getSorting(sorting).c_str(),
                      folderPath.c_str(),
                      recordPath.c_str());
        if ((retQuery == nullptr) || (retQuery->getRowCount() == 0)) {
            return SortedRecord{.path = recordPath, .offset = 0};
        }
        return SortedRecord{.path = (*retQuery)[1].getString(), .offset = (*retQuery)[0].getUInt32()};
    }
} // namespace db::multimedia_files