Repository navigation
Expand file tree
/
Copy patheansearch.cpp
More file actions
348 lines (314 loc) · 10.3 KB
/
Copy patheansearch.cpp
File metadata and controls
348 lines (314 loc) · 10.3 KB
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
/*
* A C++ class for EAN and ISBN name lookup and validation using the API on ean-search.org
* https://www.ean-search.org/ean-database-api.html
*
* (c) 2025-2026 Relaxed Communications GmBH, <info@relaxedcommunications.com>
*
* License: MIT https://opensource.org/license/mit
*/
#include "eansearch.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include <charconv>
#include <memory>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/json/src.hpp>
#include <boost/json.hpp>
using namespace std;
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace json = boost::json; // from <boost/json.hpp>
namespace ssl = net::ssl; // from <boost/asio/ssl.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
void DeleteProductList(ProductList * pl) {
if (pl) {
for (auto p : *pl) {
delete p;
}
delete pl;
}
}
/// First element of a JSON array response as an object, or nullptr.
static const json::object * FirstObject(const json::value & v) {
auto * arr = v.if_array();
if (!arr || arr->empty())
return nullptr;
return (*arr)[0].if_object();
}
/// String field of a JSON object, or "" if missing or not a string.
static string GetString(const json::object & o, json::string_view key) {
if (auto * v = o.if_contains(key))
if (auto * s = v->if_string())
return string(s->data(), s->size());
return "";
}
/// Integer field (JSON number or numeric string) of a JSON object, or def.
static int GetInt(const json::object & o, json::string_view key, int def = 0) {
auto * v = o.if_contains(key);
if (!v)
return def;
if (auto * i = v->if_int64())
return static_cast<int>(*i);
if (auto * s = v->if_string()) {
int n;
if (auto [ptr, ec] = from_chars(s->data(), s->data() + s->size(), n); ec == errc())
return n;
}
return def;
}
/// Parse an API response and return a string field of its first element, or "" on any error.
static string FirstField(const string & result, json::string_view key) {
boost::system::error_code ec;
auto v = json::parse(result, ec);
if (ec)
return "";
auto * o = FirstObject(v);
return o ? GetString(*o, key) : "";
}
/**
* Build a Product from a JSON object. Returns nullptr if the object is not a product
* (e.g. an error entry). With full = true a ProductFull is always returned.
*/
static Product * ProductFromJSON(const json::object & o, bool full = false) {
if (!o.if_contains("ean") || !o.if_contains("name"))
return nullptr;
unique_ptr<Product> p;
if (full || o.if_contains("googleCategoryId")) {
auto pf = make_unique<ProductFull>();
pf->googleCategoryId = GetInt(o, "googleCategoryId");
p = move(pf);
} else {
p = make_unique<Product>();
}
p->ean = GetString(o, "ean");
p->name = GetString(o, "name");
p->categoryId = GetInt(o, "categoryId");
p->categoryName = GetString(o, "categoryName");
p->issuingCountry = GetString(o, "issuingCountry");
return p.release();
}
/// Parse a single-product API response, or nullptr on any error.
static ProductFull * ParseProductFull(const string & result) {
boost::system::error_code ec;
auto v = json::parse(result, ec);
if (ec)
return nullptr;
auto * o = FirstObject(v);
// full = true guarantees a ProductFull
return o ? static_cast<ProductFull *>(ProductFromJSON(*o, true)) : nullptr;
}
EANSearch::EANSearch(const string & token) : token(token) {
}
ProductFull * EANSearch::BarcodeLookup(const string & ean, int language)
{
string result;
if (!APICall("op=barcode-lookup&ean=" + urlencode(ean) + "&language=" + to_string(language), result))
return nullptr;
return ParseProductFull(result);
}
ProductFull * EANSearch::IsbnLookup(const string & isbn)
{
string result;
if (!APICall("op=barcode-lookup&isbn=" + urlencode(isbn), result))
return nullptr;
return ParseProductFull(result);
}
string EANSearch::FindAsinForEan(const string & ean)
{
string result;
if (!APICall("op=asin-for-ean-lookup&ean=" + urlencode(ean), result))
return "";
return FirstField(result, "asin");
}
string EANSearch::FindEanForAsin(const string & asin)
{
string result;
if (!APICall("op=ean-for-asin-lookup&asin=" + urlencode(asin), result))
return "";
return FirstField(result, "ean");
}
string EANSearch::FindLccnForEan(const string & ean)
{
string result;
if (!APICall("op=lccn-for-ean-lookup&ean=" + urlencode(ean), result))
return "";
return FirstField(result, "lccn");
}
string EANSearch::FindEanForLccn(const string & lccn)
{
string result;
if (!APICall("op=ean-for-lccn-lookup&lccn=" + urlencode(lccn), result))
return "";
return FirstField(result, "ean");
}
bool EANSearch::VerifyChecksum(const string & ean)
{
string result;
if (!APICall("op=verify-checksum&ean=" + urlencode(ean), result))
return false;
return FirstField(result, "valid") == "1";
}
ProductList * EANSearch::ProductSearch(const string & name, int only_language, int page)
{
string result;
if (APICall("op=product-search&name=" + urlencode(name) + "&language=" + to_string(only_language) + "&page=" + to_string(page), result)) {
return ParseProductList(result);
}
return nullptr;
}
ProductList * EANSearch::SimilarProductSearch(const string & name, int only_language, int page)
{
string result;
if (APICall("op=similar-product-search&name=" + urlencode(name) + "&language=" + to_string(only_language) + "&page=" + to_string(page), result)) {
return ParseProductList(result);
}
return nullptr;
}
ProductList * EANSearch::CategorySearch(int category, const string & name, int only_language, int page)
{
string result;
if (APICall("op=category-search&category=" + to_string(category) + "&name=" + urlencode(name)
+ "&language=" + to_string(only_language) + "&page=" + to_string(page), result)) {
return ParseProductList(result);
}
return nullptr;
}
ProductList * EANSearch::BarcodePrefixSearch(const string & prefix, int language, int page)
{
string result;
if (APICall("op=barcode-prefix-search&prefix=" + urlencode(prefix)
+ "&language=" + to_string(language) + "&page=" + to_string(page), result)) {
return ParseProductList(result);
}
return nullptr;
}
string EANSearch::IssuingCountryLookup(const string & ean)
{
string result;
if (!APICall("op=issuing-country&ean=" + urlencode(ean), result))
return "";
return FirstField(result, "issuingCountry");
}
string EANSearch::BarcodeImage(const string & ean, int width, int height)
{
string result;
if (!APICall("op=barcode-image&ean=" + urlencode(ean) + "&width=" + to_string(width) + "&height=" + to_string(height), result))
return "";
return FirstField(result, "barcode");
}
int EANSearch::CreditsRemaining()
{
string result;
if (remaining < 0) {
if (!APICall("op=account-status", result)) {
return -1;
}
}
return remaining;
}
/**
* @brief Perform a synchronous HTTPS GET request to the API.
* @param params Query parameters (without token/format).
* @param result Output parameter that receives the raw JSON response body.
* @return true on success, false on network/SSL/parse error.
*/
bool EANSearch::APICall(const string & params, string & output, int tries)
{
auto const host = "api.ean-search.org";
auto const port = "443";
auto const version = 11;
string target = "/api?" + params + "&token=" + urlencode(this->token) + "&format=json";
try {
net::io_context ioc;
ssl::context ctx(ssl::context::tlsv12_client);
tcp::resolver resolver(ioc);
ssl::stream<beast::tcp_stream> stream(ioc, ctx);
if (!SSL_set_tlsext_host_name(stream.native_handle(), host)) { // set SNI
boost::system::error_code ec{static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};
throw boost::system::system_error{ec};
}
stream.set_verify_callback(ssl::host_name_verification(host));
auto const results = resolver.resolve(host, port);
beast::get_lowest_layer(stream).connect(results);
stream.handshake(ssl::stream_base::client);
http::request<http::string_body> req{http::verb::get, target, version};
req.set(http::field::host, host);
req.set(http::field::user_agent, "cpp-eansearch/1.0");
http::write(stream, req);
beast::flat_buffer buffer;
http::response<http::string_body> res;
http::read(stream, buffer, res);
output = res.body();
// The response is already complete; a failed TLS shutdown (e.g. stream_truncated
// from servers that skip close_notify) must not discard it.
beast::error_code ec;
stream.shutdown(ec);
if (res.result_int() == 429 && tries < MAX_API_TRIES) {
this_thread::sleep_for(chrono::milliseconds(1000));
return APICall(params, output, tries+1);
}
if (res.result_int() != 200) {
return false;
}
if (auto it = res.find("X-Credits-Remaining"); it != res.end()) {
auto v = it->value();
int n;
if (auto [ptr, fc] = from_chars(v.data(), v.data() + v.size(), n); fc == errc())
remaining = n;
}
}
catch(std::exception const & e) {
cerr << "Error: " << e.what() << std::endl;
return false;
}
return true;
}
/**
* @brief Percent-encode a string for use in URL query components (RFC 3986).
* @param str Input string to encode.
* @return Encoded string where non-unreserved characters are percent-encoded.
*/
string EANSearch::urlencode(const string & str) {
// RFC 3986 percent-encoding for query components: unreserved characters remain unencoded
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
static const char * hex = "0123456789ABCDEF";
string out;
out.reserve(str.size() * 3);
for (unsigned char c : str) {
if ( (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.' || c == '~' ) {
out.push_back(static_cast<char>(c));
} else {
out.push_back('%');
out.push_back(hex[(c >> 4) & 0xF]);
out.push_back(hex[c & 0xF]);
}
}
return out;
}
ProductList * EANSearch::ParseProductList(const string & str) {
boost::system::error_code ec;
auto api_result = json::parse(str, ec);
const json::array * arr = nullptr;
if (!ec)
if (auto * obj = api_result.if_object())
if (auto * v = obj->if_contains("productlist"))
arr = v->if_array();
if (!arr)
return nullptr;
auto * pl = new ProductList();
for (const auto & item : *arr) {
if (auto * o = item.if_object())
if (auto * p = ProductFromJSON(*o))
pl->push_back(p);
}
return pl;
}