summaryrefslogtreecommitdiff
path: root/src/tangara/database/index.cpp
blob: 7f594700395063b7527c7f603da86a3030878560 (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
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "database/index.hpp"
#include <sys/_stdint.h>

#include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <variant>
#include <vector>

#include "collation.hpp"
#include "cppbor.h"
#include "esp_log.h"
#include "komihash.h"
#include "leveldb/write_batch.h"

#include "database/records.hpp"
#include "database/track.hpp"

namespace database {

[[maybe_unused]] static const char* kTag = "index";

const IndexInfo kAlbumsByArtist{
    .id = 1,
    .type = MediaType::kMusic,
    .name = "Albums by Artist",
    .components = {Tag::kAlbumArtist, Tag::kAlbum, Tag::kAlbumOrder},
};

const IndexInfo kTracksByGenre{
    .id = 2,
    .type = MediaType::kMusic,
    .name = "Tracks by Genre",
    .components = {Tag::kGenres, Tag::kTitle},
};

const IndexInfo kAllTracks{
    .id = 3,
    .type = MediaType::kMusic,
    .name = "All Tracks",
    .components = {Tag::kTitle},
};

const IndexInfo kAllAlbums{
    .id = 4,
    .type = MediaType::kMusic,
    .name = "All Albums",
    .components = {Tag::kAlbum, Tag::kAlbumOrder},
};

const IndexInfo kAllArtists{
    .id = 5,
    .type = MediaType::kMusic,
    .name = "All Artists",
    .components = {Tag::kAllArtists, Tag::kTitle},
};

const IndexInfo kPodcasts{
    .id = 6,
    .type = MediaType::kPodcast,
    .name = "Podcasts",
    .components = {Tag::kAlbum, Tag::kTitle},
};

const IndexInfo kAudiobooks{
    .id = 7,
    .type = MediaType::kAudiobook,
    .name = "Audiobooks",
    .components = {Tag::kAlbum, Tag::kAlbumOrder},
};

static auto titleOrFilename(const TrackData& data,
                            const TrackTags& tags) -> std::pmr::string {
  auto title = tags.title();
  if (title) {
    return *title;
  }
  auto start = data.filepath.find_last_of('/');
  if (start == std::pmr::string::npos) {
    return data.filepath;
  }
  return data.filepath.substr(start + 1);
}

class Indexer {
 public:
  Indexer(locale::ICollator& collator,
          const IndexInfo& idx,
          const TrackData& data,
          const TrackTags& tags)
      : collator_(collator),
        index_(idx),
        track_data_(data),
        track_tags_(tags) {}

  auto index() -> std::vector<std::pair<IndexKey, std::string>>;

 private:
  auto handleLevel(const IndexKey::Header& header,
                   std::span<const Tag> components) -> void;

  auto handleItem(const IndexKey::Header& header,
                  std::variant<std::pmr::string, uint32_t> item,
                  std::span<const Tag> components) -> void;

  auto missing_value(Tag tag) -> TagValue {
    switch (tag) {
      case Tag::kTitle:
        return titleOrFilename(track_data_, track_tags_);
      case Tag::kArtist:
      case Tag::kAlbumArtist:
        return "Unknown Artist";
      case Tag::kAlbum:
        return "Unknown Album";
      case Tag::kAllArtists:
        return std::pmr::vector<std::pmr::string>{};
      case Tag::kGenres:
        return std::pmr::vector<std::pmr::string>{};
      case Tag::kDisc:
        return 0u;
      case Tag::kTrack:
        return 0u;
      case Tag::kAlbumOrder:
        return 0u;
    }
    return std::monostate{};
  }

  locale::ICollator& collator_;
  const IndexInfo index_;
  const TrackData& track_data_;
  const TrackTags& track_tags_;

  std::vector<std::pair<IndexKey, std::string>> out_;
};

auto Indexer::index() -> std::vector<std::pair<IndexKey, std::string>> {
  out_.clear();

  IndexKey::Header root_header{
      .id = index_.id,
      .components_hash = {},
  };
  handleLevel(root_header, index_.components);

  return out_;
}

auto Indexer::handleLevel(const IndexKey::Header& header,
                          std::span<const Tag> components) -> void {
  Tag component = components.front();
  TagValue value = track_tags_.get(component);
  if (std::holds_alternative<std::monostate>(value)) {
    value = missing_value(component);
  }

  std::visit(
      [&](auto&& arg) {
        using T = std::decay_t<decltype(arg)>;
        if constexpr (std::is_same_v<T, std::monostate>) {
          ESP_LOGW(kTag, "dropping component without value: %s",
                   tagName(components.front()).c_str());
        } else if constexpr (std::is_same_v<T, std::pmr::string>) {
          handleItem(header, arg, components);
        } else if constexpr (std::is_same_v<T, uint32_t>) {
          handleItem(header, arg, components);
        } else if constexpr (std::is_same_v<
                                 T, std::span<const std::pmr::string>>) {
          for (const auto& i : arg) {
            handleItem(header, i, components);
          }
        }
      },
      value);
}

auto Indexer::handleItem(const IndexKey::Header& header,
                         std::variant<std::pmr::string, uint32_t> item,
                         std::span<const Tag> components) -> void {
  IndexKey key{
      .header = header,
      .item = {},
      .track = {},
  };
  std::string value;

  std::string item_text;
  std::visit(
      [&](auto&& arg) {
        using T = std::decay_t<decltype(arg)>;
        if constexpr (std::is_same_v<T, std::pmr::string>) {
          value = {arg.data(), arg.size()};
          auto xfrm = collator_.Transform(value);
          key.item = {xfrm.data(), xfrm.size()};
        } else if constexpr (std::is_same_v<T, uint32_t>) {
          // CBOR's varint encoding actually works great for lexicographical
          // sorting.
          key.item = cppbor::Uint{arg}.toString();
        }
      },
      item);

  std::optional<IndexKey::Header> next_level;
  if (components.size() == 1) {
    value = titleOrFilename(track_data_, track_tags_);
    key.track = track_data_.id;
  } else {
    next_level = ExpandHeader(key.header, key.item);
  }

  out_.emplace_back(key, value);

  if (next_level) {
    handleLevel(*next_level, components.subspan(1));
  }
}

auto Index(locale::ICollator& collator,
           const IndexInfo& index,
           const TrackData& data,
           const TrackTags& tags)
    -> std::vector<std::pair<IndexKey, std::string>> {
  if (index.type != data.type) {
    return {};
  }
  Indexer indexer{collator, index, data, tags};
  return indexer.index();
}

auto ExpandHeader(const IndexKey::Header& header,
                  const std::pmr::string& component) -> IndexKey::Header {
  IndexKey::Header ret{header};
  ret.components_hash.push_back(
      komihash(component.data(), component.size(), 0));
  return ret;
}

}  // namespace database