/
ApiManager.cpp
593 lines (513 loc) · 16.5 KB
/
ApiManager.cpp
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/*
* Copyright (c) 2018~now Palo Kisa <palo.kisa@gmail.com>
*
* Copyright (C) 2014 Josef Rokos
* http://github.com/PepaRokos/xbmc-pvr-addons/
*
* Copyright (C) 2011 Pulse-Eight
* http://www.pulse-eight.com/
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this addon; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include <json/json.h>
#if defined(TARGET_POSIX)
#include <unistd.h>
#endif
#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
#include <net/if.h>
#include <ifaddrs.h>
# if defined(TARGET_LINUX)
#include <linux/if_packet.h>
# else //defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
#include <net/if_types.h>
#include <net/if_dl.h>
# endif
# if defined(TARGET_ANDROID)
#include <android/api-level.h>
# endif
#elif defined(TARGET_WINDOWS)
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "WSOCK32.lib")
#endif
#include <fstream>
#include <iostream>
#include "client.h"
#include "ApiManager.h"
#include "picosha2.h"
#include <ctime>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <atomic>
namespace sledovanitvcz
{
const std::string ApiManager::API_URL = "https://sledovanitv.cz/api/";
const std::string ApiManager::TIMESHIFTINFO_URL = "https://sledovanitv.cz/playback/timeshiftInfo";
const std::string ApiManager::PAIR_FILE = "pairinfo";
/* Converts a hex character to its integer value */
char from_hex(char ch)
{
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Converts an integer value to its hex character*/
char to_hex(char code)
{
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
char *url_encode(const char *str)
{
char *pstr = (char*) str, *buf = (char *)malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr)
{
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if (*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
#if defined(TARGET_ANDROID) && __ANDROID_API__ < 24
// Note: declare dummy "ifaddr" functions to make this compile on pre API-24 versions
#warning "Compiling for ANDROID with API version < 24, getting MAC addres will not be available."
static int getifaddrs(struct ifaddrs ** /*ifap*/) { errno = ENOTSUP; return -1; }
static void freeifaddrs(struct ifaddrs * /*ifa*/) {}
#endif
static std::string get_mac_address()
{
std::string mac_addr;
#if defined(TARGET_ANDROID) && __ANDROID_API__ < 24
XBMC->Log(ADDON::LOG_NOTICE, "Can't get MAC address with target Android API < 24 (no getifaddrs() support)");
#endif
#if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
struct ifaddrs * addrs;
if (0 != getifaddrs(&addrs))
{
XBMC->Log(ADDON::LOG_NOTICE, "While getting MAC address getifaddrs() failed, %s", strerror(errno));
return mac_addr;
}
std::unique_ptr<struct ifaddrs, decltype (&freeifaddrs)> if_addrs{addrs, &freeifaddrs};
for (struct ifaddrs * p = if_addrs.get(); p; p = p->ifa_next)
{
#if defined(TARGET_LINUX)
if (nullptr != p->ifa_addr && p->ifa_addr->sa_family == AF_PACKET && 0 == (p->ifa_flags & IFF_LOOPBACK))
{
struct sockaddr_ll * address = reinterpret_cast<struct sockaddr_ll *>(p->ifa_addr);
std::ostringstream addr;
for (int i = 0; i < address->sll_halen; ++i)
addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(address->sll_addr[i]);
mac_addr = addr.str();
break;
}
#else
if (nullptr != p->ifa_addr && p->ifa_addr->sa_family == AF_LINK)
{
struct sockaddr_dl * address = reinterpret_cast<struct sockaddr_dl *>(p->ifa_addr);
if (address->sdl_type == IFT_LOOP)
continue;
std::ostringstream addr;
for (int i = 0; i < address->sdl_alen; ++i)
addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(*(address->sdl_data + address->sdl_nlen + i));
mac_addr = addr.str();
break;
}
#endif
}
#elif defined(TARGET_WINDOWS)
std::unique_ptr<IP_ADAPTER_ADDRESSES, void (*)(void *)> pAddresses{static_cast<IP_ADAPTER_ADDRESSES *>(malloc(15 * 1024)), &free};
ULONG outBufLen = 0;
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses.get(), &outBufLen) == ERROR_BUFFER_OVERFLOW)
{
pAddresses.reset(static_cast<IP_ADAPTER_ADDRESSES *>(malloc(outBufLen)));
}
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses.get(), &outBufLen) == NO_ERROR)
{
IP_ADAPTER_ADDRESSES * p_addr = pAddresses.get();
while (p_addr)
{
if (p_addr->PhysicalAddressLength > 0)
{
std::ostringstream addr;
for (int i = 0; i < p_addr->PhysicalAddressLength; ++i)
addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(p_addr->PhysicalAddress[i]);
mac_addr = addr.str();
break;
}
p_addr = p_addr->Next;
}
} else
{
XBMC->Log(ADDON::LOG_NOTICE, "GetAdaptersAddresses failed...");
}
#endif
return mac_addr;
}
std::string ApiManager::formatTime(time_t t)
{
std::string buf(17, ' ');
std::strftime(const_cast<char *>(buf.data()), buf.size(), "%Y-%m-%d %H:%M", std::localtime(&t));
return buf;
}
ApiManager::ApiManager(const std::string & userName
, const std::string & userPassword
, const std::string & overridenMac
, const std::string & product)
: m_userName{userName}
, m_userPassword{userPassword}
, m_overridenMac{overridenMac}
, m_product{product}
, m_pinUnlocked{false}
, m_sessionId{std::make_shared<std::string>()}
{
XBMC->Log(ADDON::LOG_NOTICE, "Loading ApiManager");
}
std::string ApiManager::call(const std::string & urlPath, const ApiParams_t & paramsMap, bool putSessionVar) const
{
if (putSessionVar)
{
auto session_id = std::atomic_load(&m_sessionId);
// if we need to put the sessionVar, but not logged in... do nothing
if (session_id->empty())
return std::string();
}
std::string url = urlPath;
url += '?';
url += buildQueryString(paramsMap, putSessionVar);
// add User-Agent header... TODO: make it configurable
url += "|User-Agent=okhttp%2F3.12.0";
std::string response;
void *fh = XBMC->OpenFile(url.c_str(), XFILE::READ_NO_CACHE);
if (fh)
{
char buffer[1024];
while (int bytesRead = XBMC->ReadFile(fh, buffer, 1024))
response.append(buffer, bytesRead);
XBMC->CloseFile(fh);
}
else
{
XBMC->Log(ADDON::LOG_ERROR, "Cannot open url");
}
return response;
}
std::string ApiManager::apiCall(const std::string &function, const ApiParams_t & paramsMap, bool putSessionVar /*= true*/) const
{
std::string url = API_URL;
url += function;
return call(url, paramsMap, putSessionVar);
}
bool ApiManager::isSuccess(const std::string &response, Json::Value & root)
{
std::string jsonReaderError;
Json::CharReaderBuilder jsonReaderBuilder;
std::unique_ptr<Json::CharReader> const reader(jsonReaderBuilder.newCharReader());
if (reader->parse(response.c_str(), response.c_str() + response.size(), &root, &jsonReaderError))
{
bool success = root.get("status", 0).asInt() == 1;
if (!success)
XBMC->Log(ADDON::LOG_ERROR, "Error indicated in response. status: %d, error: %s", root.get("status", 0).asInt(), root.get("error", "").asString().c_str());
return success;
}
XBMC->Log(ADDON::LOG_ERROR, "Error parsing response. Response is: %*s, reader error: %s", std::min(response.size(), static_cast<size_t>(1024)), response.c_str(), jsonReaderError.c_str());
return false;
}
bool ApiManager::isSuccess(const std::string &response)
{
Json::Value root;
return isSuccess(response, root);
}
bool ApiManager::pairDevice()
{
bool new_pairing = false;
std::string pairJson = readPairFile();
std::string macAddr = m_overridenMac.empty() ? get_mac_address() : m_overridenMac;
if (macAddr.empty())
{
XBMC->Log(ADDON::LOG_NOTICE, "Unable to get MAC address, using a dummy for serial");
macAddr = "11223344";
}
// compute SHA256 of string representation of MAC address
m_serial = picosha2::hash256_hex_string(macAddr);
Json::Value root;
if (pairJson.empty() || !isSuccess(pairJson, root)
|| root.get("userName", "").asString() != m_userName
|| root.get("serial", "").asString() != m_serial
)
{
// remove pairing if any exising
const std::string old_dev_id = root.get("deviceId", "").asString();
const std::string old_password = root.get("password", "").asString();
if (!old_dev_id.empty())
{
ApiParams_t params_del;
params_del.emplace_back("deviceId", old_dev_id);
params_del.emplace_back("password", old_password);
params_del.emplace_back("unit", "default");
isSuccess(apiCall("delete-pairing", params_del, false));
}
new_pairing = true;
ApiParams_t params;
std::string product = m_product;
if (product.empty())
{
char host_name[256];
gethostname(host_name, 256);
product = host_name;
}
params.emplace_back("username", m_userName);
params.emplace_back("password", m_userPassword);
params.emplace_back("type", "androidportable");
params.emplace_back("serial", m_serial);
params.emplace_back("product", product);
params.emplace_back("unit", "default");
params.emplace_back("checkLimit", "1");
pairJson = apiCall("create-pairing", params, false);
}
if (isSuccess(pairJson, root))
{
int devId = root.get("deviceId", 0).asInt();
std::string passwd = root.get("password", "").asString();
char buf[256];
sprintf(buf, "%d", devId);
m_deviceId = buf;
m_password = passwd;
XBMC->Log(ADDON::LOG_DEBUG, "Device ID: %d, Password: %s", devId, passwd.c_str());
const bool paired = !m_deviceId.empty() && !m_password.empty();
if (paired && new_pairing)
{
// add the userName to written json
root["userName"] = m_userName;
root["serial"] = m_serial;
std::ostringstream os;
os << root;
createPairFile(os.str());
}
return paired;
}
else
{
XBMC->Log(ADDON::LOG_ERROR, "Error in pairing response.");
}
return false;
}
bool ApiManager::login()
{
m_pinUnlocked = false;
if (m_deviceId.empty() && m_password.empty())
{
if (!pairDevice())
{
XBMC->Log(ADDON::LOG_ERROR, "Cannot pair device");
return false;
}
}
ApiParams_t param;
param.emplace_back("deviceId", m_deviceId);
param.emplace_back("password", m_password);
param.emplace_back("version", "2.6.21");
param.emplace_back("lang", "en");
param.emplace_back("unit", "default");
Json::Value root;
std::string new_session_id;
if (isSuccess(apiCall("device-login", param, false), root))
{
new_session_id = root.get("PHPSESSID", "").asString();
if (new_session_id.empty())
{
XBMC->Log(ADDON::LOG_ERROR, "Cannot perform device login");
}
else
{
XBMC->Log(ADDON::LOG_NOTICE, "Device logged in. Session ID: %s", new_session_id.c_str());
}
}
const bool success = !new_session_id.empty();
if (!success)
{
m_deviceId.clear();
m_password.clear();
createPairFile(std::string{}); // truncate any "old" pairing response
}
std::atomic_store(&m_sessionId, std::make_shared<const std::string>(std::move(new_session_id)));
return success;
}
bool ApiManager::pinUnlock(const std::string & pin)
{
ApiParams_t params;
params.emplace_back("pin", pin);
bool result = isSuccess(apiCall("pin-unlock", params));
if (result)
m_pinUnlocked = true;
return result;
}
bool ApiManager::pinUnlocked() const
{
return m_pinUnlocked;
}
bool ApiManager::getPlaylist(StreamQuality_t quality, bool useH265, bool useAdaptive, Json::Value & root)
{
ApiParams_t params;
params.emplace_back("uuid", m_serial);
params.emplace_back("format", "m3u8");
params.emplace_back("quality", std::to_string(quality));
std::string caps = useH265 ? "h265" : "";
if (useAdaptive)
{
if (!caps.empty())
caps += ',';
caps += "adaptive2";
}
params.emplace_back("capabilities", std::move(caps));
return isSuccess(apiCall("playlist", params), root);
}
bool ApiManager::getStreamQualities(Json::Value & root)
{
return isSuccess(apiCall("get-stream-qualities", ApiParams_t{}), root);
}
bool ApiManager::getEpg(time_t start, bool smallDuration, const std::string & channels, Json::Value & root)
{
ApiParams_t params;
params.emplace_back("time", formatTime(start));
params.emplace_back("duration", smallDuration ? "60" : "1439");
params.emplace_back("detail", "1");
params.emplace_back("allowOrder", "1");
if (!channels.empty())
params.emplace_back("channels", std::move(channels));
return isSuccess(apiCall("epg", params), root);
}
bool ApiManager::getPvr(Json::Value & root)
{
return isSuccess(apiCall("get-pvr", ApiParams_t()), root);
}
std::string ApiManager::getRecordingUrl(const std::string &recId, std::string & channel)
{
ApiParams_t param;
param.emplace_back("recordId", recId);
param.emplace_back("format", "m3u8");
Json::Value root;
if (isSuccess(apiCall("record-timeshift", param), root))
{
channel = root.get("channel", "").asString();
return root.get("url", "").asString();
}
return "";
}
bool ApiManager::getTimeShiftInfo(const std::string &eventId
, std::string & streamUrl
, std::string & channel
, int & duration) const
{
ApiParams_t param;
param.emplace_back("eventId", eventId);
param.emplace_back("format", "m3u8");
Json::Value root;
if (isSuccess(apiCall("event-timeshift", param), root))
{
streamUrl = root.get("url", "").asString();
channel = root.get("channel", "").asString();
duration = root.get("duration", 0).asInt();
return true;
}
return false;
}
bool ApiManager::addTimer(const std::string &eventId, std::string & recordId)
{
ApiParams_t param;
param.emplace_back("eventId", eventId);
Json::Value root;
if (isSuccess(apiCall("record-event", param), root))
{
recordId = root.get("recordId", "").asString();
return true;
}
return false;
}
bool ApiManager::deleteRecord(const std::string &recId)
{
ApiParams_t param;
param.emplace_back("recordId", recId);
return isSuccess(apiCall("delete-record", param));
}
bool ApiManager::keepAlive()
{
ApiParams_t param;
return isSuccess(apiCall("keepalive", param));
}
bool ApiManager::loggedIn() const
{
auto session_id = std::atomic_load(&m_sessionId);
return !session_id->empty();
}
std::string ApiManager::urlEncode(const std::string &str)
{
std::string strOut;
strOut.append(url_encode(str.c_str()));
return strOut;
}
std::string ApiManager::buildQueryString(const ApiParams_t & paramMap, bool putSessionVar) const
{
XBMC->Log(ADDON::LOG_DEBUG, "%s - size %d", __FUNCTION__, paramMap.size());
std::string strOut;
for (const auto & param : paramMap)
{
if (!strOut.empty())
{
strOut += "&";
}
strOut += std::get<0>(param) + "=" + urlEncode(std::get<1>(param));
}
if (putSessionVar)
{
auto session_id = std::atomic_load(&m_sessionId);
strOut += "&PHPSESSID=";
strOut += *session_id;
}
return strOut;
}
std::string ApiManager::readPairFile()
{
std::string url = GetUserFilePath(PAIR_FILE);
std::string strContent;
XBMC->Log(ADDON::LOG_DEBUG, "Openning file %s", url.c_str());
void* fileHandle = XBMC->OpenFile(url.c_str(), 0);
if (fileHandle)
{
char buffer[1024];
while (int bytesRead = XBMC->ReadFile(fileHandle, buffer, 1024))
strContent.append(buffer, bytesRead);
XBMC->CloseFile(fileHandle);
}
return strContent;
}
void ApiManager::createPairFile(const std::string &content)
{
std::string url = GetUserFilePath(PAIR_FILE);
void *fileHandle = XBMC->OpenFileForWrite(url.c_str(), true);
if (fileHandle)
{
XBMC->WriteFile(fileHandle, content.c_str(), content.length());
XBMC->CloseFile(fileHandle);
}
}
} // namespace sledovanitvcz