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

#include "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 "records.hpp"
#include "track.hpp"

namespace database {

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

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

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

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

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

class Indexer {
 public:
  Indexer(locale::ICollator& collator, const Track& t, const IndexInfo& idx)
      : collator_(collator), track_(t), index_(idx) {}

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

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

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

  auto missing_value(Tag tag) -> TagValue {
    switch (tag) {
      case Tag::kTitle:
        return track_.TitleOrFilename();
      case Tag::kArtist:
        return "Unknown Artist";
      case Tag::kAlbum:
        return "Unknown Album";
      case Tag::kAlbumArtist:
        return track_.tags().artist().value_or("Unknown Artist");
        return "Unknown Album";
      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 Track& track_;
  const IndexInfo index_;

  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,
      .depth = 0,
      .components_hash = 0,
  };
  handleLevel(root_header, index_.components);

  return out_;
}

auto Indexer::handleLevel(const IndexKey::Header& header,
                          cpp::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, cpp::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,
                         cpp::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>) {
          value = std::to_string(arg);
          // FIXME: this sucks lol. we should just write the number directly,
          // LSB-first, but then we need to be able to parse it back properly.
          std::ostringstream str;
          str << std::setw(8) << std::setfill('0') << arg;
          std::string encoded = str.str();
          key.item = {encoded.data(), encoded.size()};
        }
      },
      item);

  std::optional<IndexKey::Header> next_level;
  if (components.size() == 1) {
    value = track_.TitleOrFilename();
    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& c, const IndexInfo& i, const Track& t)
    -> std::vector<std::pair<IndexKey, std::string>> {
  Indexer indexer{c, t, i};
  return indexer.index();
}

auto ExpandHeader(const IndexKey::Header& header,
                  const std::optional<std::pmr::string>& component)
    -> IndexKey::Header {
  IndexKey::Header ret{header};
  ret.depth++;
  if (component) {
    ret.components_hash =
        komihash(component->data(), component->size(), ret.components_hash);
  } else {
    ret.components_hash = komihash(NULL, 0, ret.components_hash);
  }
  return ret;
}

}  // namespace database