-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheansearch.cpp
More file actions
276 lines (255 loc) · 8.79 KB
/
eansearch.cpp
File metadata and controls
276 lines (255 loc) · 8.79 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
/*
* 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 Relaxed Communications GmBH, <info@relaxedcommunications.com>
*
* License: MIT https://opensource.org/license/mit
*/
#include "eansearch.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#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;
}
}
static Product * ProductFromJSON(const json::value & api_result) {
Product * p = nullptr;
auto json_product = api_result.if_object();
if (json_product) {
if (json_product->if_contains("googleCategoryId")) {
p = new ProductFull();
auto * pf = static_cast<ProductFull *>(p);
pf->googleCategoryId = stoi(json_product->at("googleCategoryId").as_string().c_str());
} else {
p = new Product();
}
p->ean = json_product->at("ean").as_string();
p->name = json_product->at("name").as_string();
p->categoryId = stoi(json_product->at("categoryId").as_string().c_str());
p->categoryName = json_product->at("categoryName").as_string();
p->issuingCountry = json_product->at("issuingCountry").as_string();
}
return p;
}
EANSearch::EANSearch(const string & token) {
this->token = token;
this->remaining = -1;
}
ProductFull * EANSearch::BarcodeLookup(const string & ean, int language)
{
string result;
if (APICall("op=barcode-lookup&ean=" + ean + "&language=" + to_string(language), result)) {
auto api_result = json::parse(result);
ProductFull * p = dynamic_cast<ProductFull *>(ProductFromJSON(api_result.at(0)));
return p;
} else {
return nullptr;
}
}
ProductFull * EANSearch::IsbnLookup(const string & isbn)
{
string result;
if (APICall("op=barcode-lookup&isbn=" + isbn, result)) {
auto api_result = json::parse(result);
ProductFull * p = dynamic_cast<ProductFull *>(ProductFromJSON(api_result.at(0)));
return p;
} else {
return nullptr;
}
}
bool EANSearch::VerifyChecksum(const string & ean)
{
string result;
if (APICall("op=verify-checksum&ean=" + ean, result)) {
auto api_result = json::parse(result);
return (api_result.at(0).at("valid").as_string() == "1");
} else {
return false;
}
}
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=" + 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=" + ean, result)) {
error_code ec;
auto api_result = json::parse(result, ec);
return api_result.at(0).at("issuingCountry").as_string().c_str();
} else {
return "";
}
}
string EANSearch::BarcodeImage(const string & ean, int width, int height)
{
string result;
if (APICall("op=barcode-image&ean=" + ean + "&width=" + to_string(width) + "&height=" + to_string(height), result)) {
auto api_result = json::parse(result);
return api_result.at(0).at("barcode").as_string().c_str();
} else {
return "";
}
}
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=" + 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;
auto len = http::read(stream, buffer, res);
output = res.body();
beast::error_code ec;
stream.shutdown(ec);
if (ec == boost::asio::error::eof) {
ec.assign(0, ec.category());
}
if (ec) {
throw boost::system::system_error{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;
} else {
remaining = stoi(res.base()["X-Credits-Remaining"]);
}
}
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) {
error_code ec;
auto api_result = json::parse(str, ec);
json::array * arr = nullptr;
if (!ec) {
arr = api_result.at("productlist").if_array();
}
if (ec || !arr) {
return nullptr;
}
ProductList * pl = new ProductList();
for (auto o : *arr) {
auto * p = ProductFromJSON(o);
if (p) {
pl->push_back(p);
}
}
return pl;
}