Debian Codegraph @

src/ApiManager.cpp

raw
1 /*
2 * Copyright (c) 2018~now Palo Kisa <[email protected]>
3 *
4 * Copyright (C) 2014 Josef Rokos
5 * http://github.com/PepaRokos/xbmc-pvr-addons/
6 *
7 * Copyright (C) 2011 Pulse-Eight
8 * http://www.pulse-eight.com/
9 *
10 * This Program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
13 * any later version.
14 *
15 * This Program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this addon; see the file COPYING. If not, write to
22 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 */
26
27 #include "kodi/AddonBase.h"
28 #include <json/json.h>
29 #if defined(TARGET_POSIX)
30 #include <unistd.h>
31 #endif
32 #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
33 #include <net/if.h>
34 #include <ifaddrs.h>
35 # if defined(TARGET_LINUX)
36 #include <linux/if_packet.h>
37 # else //defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
38 #include <net/if_types.h>
39 #include <net/if_dl.h>
40 # endif
41 # if defined(TARGET_ANDROID)
42 #include <android/api-level.h>
43 # endif
44 #elif defined(TARGET_WINDOWS)
45 #include <winsock2.h>
46 #include <iphlpapi.h>
47 #include <ws2tcpip.h>
48 #pragma comment(lib, "IPHLPAPI.lib")
49 #pragma comment(lib, "WSOCK32.lib")
50 #endif
51
52 #include <fstream>
53 #include <iostream>
54
55 #include "ApiManager.h"
56 #include "picosha2.h"
57 #include "kodi/General.h"
58 #include "kodi/Filesystem.h"
59 #include <ctime>
60 #include <sstream>
61 #include <iomanip>
62 #include <algorithm>
63 #include <atomic>
64 #include <chrono>
65
66 namespace sledovanitvcz
67 {
68
69 const std::string ApiManager::API_URL[SP_END] = { "https://sledovanitv.cz/api/", "https://api.moderntv.eu/api/" };
70 const std::string ApiManager::API_UNIT[SP_END] = { "default", "modernitv" };
71 const std::string ApiManager::PAIR_FILE = "pairinfo";
72
73 /* Converts a hex character to its integer value */
74 char from_hex(char ch)
75 {
76 return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
77 }
78
79 /* Converts an integer value to its hex character*/
80 char to_hex(char code)
81 {
82 static char hex[] = "0123456789abcdef";
83 return hex[code & 15];
84 }
85
86 #if defined(TARGET_ANDROID) && __ANDROID_API__ < 24
87 // Note: declare dummy "ifaddr" functions to make this compile on pre API-24 versions
88 #warning "Compiling for ANDROID with API version < 24, getting MAC addres will not be available."
89 static int getifaddrs(struct ifaddrs ** /*ifap*/) { errno = ENOTSUP; return -1; }
90 static void freeifaddrs(struct ifaddrs * /*ifa*/) {}
91 #endif
92 static std::string get_mac_address()
93 {
94 std::string mac_addr;
95 #if defined(TARGET_ANDROID) && __ANDROID_API__ < 24
96 kodi::Log(ADDON_LOG_INFO, "Can't get MAC address with target Android API < 24 (no getifaddrs() support)");
97 #endif
98 #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) || defined(TARGET_DARWIN)
99 struct ifaddrs * addrs;
100 if (0 != getifaddrs(&addrs))
101 {
102 kodi::Log(ADDON_LOG_INFO, "While getting MAC address getifaddrs() failed, %s", strerror(errno));
103 return mac_addr;
104 }
105 std::unique_ptr<struct ifaddrs, decltype (&freeifaddrs)> if_addrs{addrs, &freeifaddrs};
106 for (struct ifaddrs * p = if_addrs.get(); p; p = p->ifa_next)
107 {
108 #if defined(TARGET_LINUX)
109 if (nullptr != p->ifa_addr && p->ifa_addr->sa_family == AF_PACKET && 0 == (p->ifa_flags & IFF_LOOPBACK))
110 {
111 struct sockaddr_ll * address = reinterpret_cast<struct sockaddr_ll *>(p->ifa_addr);
112 std::ostringstream addr;
113 for (int i = 0; i < address->sll_halen; ++i)
114 addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(address->sll_addr[i]);
115 mac_addr = addr.str();
116 break;
117 }
118 #else
119 if (nullptr != p->ifa_addr && p->ifa_addr->sa_family == AF_LINK)
120 {
121 struct sockaddr_dl * address = reinterpret_cast<struct sockaddr_dl *>(p->ifa_addr);
122 if (address->sdl_type == IFT_LOOP)
123 continue;
124 std::ostringstream addr;
125 for (int i = 0; i < address->sdl_alen; ++i)
126 addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(*(address->sdl_data + address->sdl_nlen + i));
127 mac_addr = addr.str();
128 break;
129 }
130 #endif
131 }
132 #elif defined(TARGET_WINDOWS)
133 std::unique_ptr<IP_ADAPTER_ADDRESSES, void (*)(void *)> pAddresses{static_cast<IP_ADAPTER_ADDRESSES *>(malloc(15 * 1024)), &free};
134 ULONG outBufLen = 0;
135
136 if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses.get(), &outBufLen) == ERROR_BUFFER_OVERFLOW)
137 {
138 pAddresses.reset(static_cast<IP_ADAPTER_ADDRESSES *>(malloc(outBufLen)));
139 }
140
141 if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses.get(), &outBufLen) == NO_ERROR)
142 {
143 IP_ADAPTER_ADDRESSES * p_addr = pAddresses.get();
144 while (p_addr)
145 {
146 if (p_addr->PhysicalAddressLength > 0)
147 {
148 std::ostringstream addr;
149 for (int i = 0; i < p_addr->PhysicalAddressLength; ++i)
150 addr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(p_addr->PhysicalAddress[i]);
151 mac_addr = addr.str();
152 break;
153 }
154 p_addr = p_addr->Next;
155 }
156 } else
157 {
158 kodi::Log(ADDON_LOG_INFO, "GetAdaptersAddresses failed...");
159 }
160 #endif
161 return mac_addr;
162 }
163
164 std::string ApiManager::formatTime(time_t t)
165 {
166 std::string buf(17, ' ');
167 std::strftime(const_cast<char *>(buf.data()), buf.size(), "%Y-%m-%d %H:%M", std::localtime(&t));
168 return buf;
169 }
170
171 std::string ApiManager::generateUserAgent()
172 {
173 return "Kodi-" + kodi::addon::GetAddonInfo("id") + '/' + kodi::addon::GetAddonInfo("version");
174 }
175
176 ApiManager::ApiManager(ServiceProvider_t serviceProvider
177 , const std::string & userName
178 , const std::string & userPassword
179 , const std::string & overridenMac
180 , const std::string & product
181 , const std::string & userAgent
182 , uint64_t instanceNo)
183 : m_serviceProvider{serviceProvider}
184 , m_userName{userName}
185 , m_userPassword{userPassword}
186 , m_overridenMac{overridenMac}
187 , m_product{product}
188 , m_userAgent{userAgent.empty() ? generateUserAgent() : userAgent}
189 , m_instanceNo{instanceNo}
190 , m_pinUnlocked{false}
191 , m_sessionId{std::make_shared<std::string>()}
192 {
193 kodi::Log(ADDON_LOG_INFO, "Loading ApiManager");
194 }
195
196 std::string ApiManager::call(const std::string & urlPath, const ApiParams_t & paramsMap, bool putSessionVar) const
197 {
198 if (putSessionVar)
199 {
200 auto session_id = std::atomic_load(&m_sessionId);
201 // if we need to put the sessionVar, but not logged in... do nothing
202 if (session_id->empty())
203 return std::string();
204 }
205 std::string url = urlPath;
206 const std::string query = buildQueryString(paramsMap, putSessionVar);
207 if (!query.empty())
208 {
209 url += '?';
210 url += query;
211 }
212
213 url += "|User-Agent=";
214 url += m_userAgent;
215 std::string response;
216
217 kodi::vfs::CFile fh;
218 if (fh.OpenFile(url, ADDON_READ_NO_CACHE))
219 {
220 char buffer[1024];
221 while (int bytesRead = fh.Read(buffer, 1024))
222 response.append(buffer, bytesRead);
223 }
224 else
225 {
226 kodi::Log(ADDON_LOG_ERROR, "Cannot open url");
227 }
228
229 return response;
230 }
231
232 std::string ApiManager::apiCall(const std::string &function, const ApiParams_t & paramsMap, bool putSessionVar /*= true*/) const
233 {
234 std::string url = API_URL[m_serviceProvider];
235 url += function;
236 return call(url, paramsMap, putSessionVar);
237 }
238
239 bool ApiManager::isSuccess(const std::string &response, Json::Value & root)
240 {
241 std::string jsonReaderError;
242 Json::CharReaderBuilder jsonReaderBuilder;
243 std::unique_ptr<Json::CharReader> const reader(jsonReaderBuilder.newCharReader());
244
245 if (reader->parse(response.c_str(), response.c_str() + response.size(), &root, &jsonReaderError))
246 {
247 bool success = root.get("status", 0).asInt() == 1;
248 if (!success)
249 kodi::Log(ADDON_LOG_ERROR, "Error indicated in response. status: %d, error: %s", root.get("status", 0).asInt(), root.get("error", "").asString().c_str());
250 return success;
251 }
252
253 kodi::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());
254 return false;
255 }
256
257 bool ApiManager::isSuccess(const std::string &response)
258 {
259 Json::Value root;
260 return isSuccess(response, root);
261 }
262
263 bool ApiManager::deletePairing(const Json::Value & root)
264 {
265 // try to delete pairing
266 const std::string old_dev_id = root.get("deviceId", "").asString();
267 if (old_dev_id.empty())
268 return true; // no previous pairing
269
270 const std::string old_password = root.get("password", "").asString();
271 ApiParams_t params;
272 params.emplace_back("deviceId", old_dev_id);
273 params.emplace_back("password", old_password);
274 params.emplace_back("unit", API_UNIT[m_serviceProvider]);
275 const std::string response = apiCall("delete-pairing", params, false);
276 Json::Value del_root;
277 if (isSuccess(response, del_root)
278 || (del_root.get("error", "").asString() == "no device")
279 || (del_root.get("error", "").asString() == "not logged")
280 )
281 {
282 kodi::Log(ADDON_LOG_INFO, "Previous pairing(deviceId:%s) deleted (or no such device)", old_dev_id.c_str());
283 return true;
284 }
285
286 return false;
287 }
288
289 bool ApiManager::pairDevice(Json::Value & root)
290 {
291 bool new_pairing = false;
292 std::string pairJson = readPairFile(getPairFilePath());
293
294 std::string macAddr = m_overridenMac.empty() ? get_mac_address() : m_overridenMac;
295 if (macAddr.empty())
296 {
297 std::ostringstream os;
298 os << std::chrono::high_resolution_clock::now().time_since_epoch().count();
299 macAddr = os.str();
300 kodi::Log(ADDON_LOG_INFO, "Unable to get MAC address, using a dummy(%s) for serial", macAddr.c_str());
301 }
302 // compute SHA256 of string representation of MAC address
303 m_serial = picosha2::hash256_hex_string(macAddr);
304
305
306 if (pairJson.empty() || !isSuccess(pairJson, root)
307 || root.get("userName", "").asString() != m_userName
308 || root.get("serial", "").asString() != m_serial
309 )
310 {
311 // remove pairing if any exising
312 if (!deletePairing(root))
313 return false;
314
315 new_pairing = true;
316 ApiParams_t params;
317
318 std::string product = m_product;
319 if (product.empty())
320 {
321 char host_name[256];
322 gethostname(host_name, 256);
323 product = host_name;
324 }
325
326 params.emplace_back("username", m_userName);
327 params.emplace_back("password", m_userPassword);
328 params.emplace_back("type", "androidportable");
329 params.emplace_back("serial", m_serial);
330 params.emplace_back("product", product);
331 params.emplace_back("unit", API_UNIT[m_serviceProvider]);
332 params.emplace_back("checkLimit", "1");
333
334 pairJson = apiCall("create-pairing", params, false);
335 }
336
337 if (isSuccess(pairJson, root))
338 {
339 int devId = root.get("deviceId", 0).asInt();
340 std::string passwd = root.get("password", "").asString();
341
342 char buf[256];
343 sprintf(buf, "%d", devId);
344 m_deviceId = buf;
345 m_password = passwd;
346
347 kodi::Log(ADDON_LOG_DEBUG, "Device ID: %d, Password: %s", devId, passwd.c_str());
348
349 const bool paired = !m_deviceId.empty() && !m_password.empty();
350
351 if (paired && new_pairing)
352 {
353 // add the userName to written json
354 root["userName"] = m_userName;
355 root["serial"] = m_serial;
356 createPairFile(root);
357 }
358 return paired;
359 }
360 else
361 {
362 kodi::Log(ADDON_LOG_ERROR, "Error in pairing response.");
363 }
364
365 return false;
366 }
367
368 bool ApiManager::login()
369 {
370 m_pinUnlocked = false;
371 Json::Value pairing_root;
372 if (m_deviceId.empty() && m_password.empty())
373 {
374 if (!pairDevice(pairing_root))
375 {
376 kodi::Log(ADDON_LOG_ERROR, "Cannot pair device");
377 return false;
378 }
379 }
380
381 ApiParams_t param;
382 param.emplace_back("deviceId", m_deviceId);
383 param.emplace_back("password", m_password);
384 param.emplace_back("version", "2.6.21");
385 param.emplace_back("lang", "en");
386 param.emplace_back("unit", API_UNIT[m_serviceProvider]);
387
388 Json::Value root;
389
390 std::string new_session_id;
391 const std::string response = apiCall("device-login", param, false);
392 if (isSuccess(response, root))
393 {
394 new_session_id = root.get("PHPSESSID", "").asString();
395
396 if (new_session_id.empty())
397 {
398 kodi::Log(ADDON_LOG_ERROR, "Cannot perform device login");
399 }
400 else
401 {
402 kodi::Log(ADDON_LOG_INFO, "Device logged in. Session ID: %s", new_session_id.c_str());
403 }
404 } else if (response.empty()) {
405 kodi::Log(ADDON_LOG_INFO, "No login response. Is something wrong with network or remote servers?");
406 // don't do anything, let the state as is to give it another try
407 return false;
408 }
409
410 const bool success = !new_session_id.empty();
411 if (!success)
412 {
413 m_deviceId.clear();
414 m_password.clear();
415 // change userName in stored pairing response to "re-pair" this device
416 pairing_root["userName"] = "";
417 createPairFile(pairing_root);
418 }
419
420 std::atomic_store(&m_sessionId, std::make_shared<const std::string>(std::move(new_session_id)));
421
422 return success;
423 }
424
425 bool ApiManager::registerDrm(std::string & licenseUrl, std::string & certificate) const
426 {
427 ApiParams_t param;
428 param.emplace_back("type", "widevine");
429
430 const std::string response = apiCall("drm-registration", param, true);
431 Json::Value root;
432 if (!isSuccess(response, root))
433 return false;
434
435 const Json::Value & info = const_cast<const Json::Value &>(root)["info"];
436 if (info["type"].asString() != "widevine")
437 kodi::Log(ADDON_LOG_WARNING, "Expected DRM type widevine, got %s. DRM may not work", info["type"].asString().c_str());
438 if (info["licenseHandler"]["requestEncoding"].asString() != "binary")
439 kodi::Log(ADDON_LOG_WARNING, "Expected DRM requestEncoding binary, got %s. DRM may not work", info["licenseHandler"]["requestEncoding"].asString().c_str());
440 if (info["licenseHandler"]["responseEncoding"].asString() != "binary")
441 kodi::Log(ADDON_LOG_WARNING, "Expected DRM responseEncoding binary, got %s. DRM may not work", info["licenseHandler"]["responseEncoding"].asString().c_str());
442 licenseUrl = info["licenseUrl"].asString();
443 if (info["licenseUrl"].empty())
444 kodi::Log(ADDON_LOG_WARNING, "Got empty DRM licenseUrl. DRM may not work");
445 certificate = call(info["certificateUrl"].asString(), ApiParams_t{}, false);
446 if (certificate.empty())
447 kodi::Log(ADDON_LOG_WARNING, "Got empty DRM certificate from %s. DRM may not work", info["certificateUrl"].asString().c_str());
448 return true;
449 }
450
451 bool ApiManager::pinUnlock(const std::string & pin)
452 {
453 ApiParams_t params;
454 params.emplace_back("pin", pin);
455
456 bool result = isSuccess(apiCall("pin-unlock", params));
457 if (result)
458 m_pinUnlocked = true;
459 return result;
460 }
461
462 bool ApiManager::pinUnlocked() const
463 {
464 return m_pinUnlocked;
465 }
466
467 bool ApiManager::getPlaylist(StreamQuality_t quality, bool useH265, bool useAdaptive, Json::Value & root)
468 {
469 ApiParams_t params;
470 params.emplace_back("uuid", m_serial);
471 params.emplace_back("format", "m3u8");
472 params.emplace_back("quality", std::to_string(quality));
473 std::string caps = "webvtt";
474 if (useH265)
475 caps += ",h265";
476 if (useAdaptive)
477 caps += ",adaptive2";
478 params.emplace_back("capabilities", std::move(caps));
479 params.emplace_back("drm", "widevine");
480 params.emplace_back("subtitles", "1");
481 return isSuccess(apiCall("playlist", params), root);
482 }
483
484 bool ApiManager::getStreamQualities(Json::Value & root)
485 {
486 return isSuccess(apiCall("get-stream-qualities", ApiParams_t{}), root);
487 }
488
489 bool ApiManager::getEpg(time_t start, bool smallDuration, const std::string & channels, Json::Value & root)
490 {
491 ApiParams_t params;
492
493 params.emplace_back("time", formatTime(start));
494 params.emplace_back("duration", smallDuration ? "60" : "1439");
495 params.emplace_back("detail", "description,score,poster,rating");
496 params.emplace_back("allowOrder", "1");
497 if (!channels.empty())
498 params.emplace_back("channels", std::move(channels));
499
500 return isSuccess(apiCall("epg", params), root);
501 }
502
503 bool ApiManager::getPvr(Json::Value & root)
504 {
505 return isSuccess(apiCall("get-pvr", ApiParams_t()), root);
506 }
507
508 std::string ApiManager::getRecordingUrl(const std::string &recId, std::string & channel, bool & isDrm)
509 {
510 ApiParams_t param;
511 param.emplace_back("recordId", recId);
512 param.emplace_back("format", "m3u8");
513
514 Json::Value root;
515
516 if (isSuccess(apiCall("record-timeshift", param), root))
517 {
518 channel = root.get("channel", "").asString();
519 isDrm = root.get("drm", 0).asInt() != 0;
520 return root.get("url", "").asString();
521 }
522
523 return "";
524 }
525
526 bool ApiManager::getTimeShiftInfo(const std::string &eventId
527 , std::string & streamUrl
528 , std::string & channel
529 , int & duration) const
530 {
531 ApiParams_t param;
532 param.emplace_back("eventId", eventId);
533 param.emplace_back("format", "m3u8");
534
535 Json::Value root;
536
537 if (isSuccess(apiCall("event-timeshift", param), root))
538 {
539 streamUrl = root.get("url", "").asString();
540 channel = root.get("channel", "").asString();
541 duration = root.get("duration", 0).asInt();
542 return true;
543 }
544
545 return false;
546 }
547
548 bool ApiManager::addTimer(const std::string &eventId, std::string & recordId)
549 {
550 ApiParams_t param;
551 param.emplace_back("eventId", eventId);
552
553 Json::Value root;
554
555 if (isSuccess(apiCall("record-event", param), root))
556 {
557 recordId = root.get("recordId", "").asString();
558 return true;
559 }
560 return false;
561 }
562
563 bool ApiManager::deleteRecord(const std::string &recId)
564 {
565 ApiParams_t param;
566 param.emplace_back("recordId", recId);
567
568 return isSuccess(apiCall("delete-record", param));
569 }
570
571 bool ApiManager::keepAlive()
572 {
573 ApiParams_t param;
574 return isSuccess(apiCall("keepalive", param));
575 }
576
577 bool ApiManager::loggedIn() const
578 {
579 auto session_id = std::atomic_load(&m_sessionId);
580 return !session_id->empty();
581 }
582
583 std::string ApiManager::urlEncode(const std::string &str)
584 {
585 std::string result;
586 for (const auto c : str)
587 {
588 if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
589 result += c;
590 else if (c == ' ')
591 result += '+';
592 else
593 {
594 result += '%';
595 result += to_hex(c >> 4);
596 result += to_hex(c & 15);
597 }
598 }
599 return result;
600 }
601
602 std::string ApiManager::buildQueryString(const ApiParams_t & paramMap, bool putSessionVar) const
603 {
604 kodi::Log(ADDON_LOG_DEBUG, "%s - size %d", __FUNCTION__, paramMap.size());
605 std::string strOut;
606 for (const auto & param : paramMap)
607 {
608 if (!strOut.empty())
609 {
610 strOut += "&";
611 }
612
613 strOut += std::get<0>(param) + "=" + urlEncode(std::get<1>(param));
614 }
615
616 if (putSessionVar)
617 {
618 auto session_id = std::atomic_load(&m_sessionId);
619 if (!strOut.empty())
620 {
621 strOut += "&";
622 }
623 strOut += "PHPSESSID=";
624 strOut += *session_id;
625 }
626
627 return strOut;
628 }
629
630 std::string ApiManager::getPairFilePath() const
631 {
632 std::ostringstream os;
633 os << PAIR_FILE << '-' << m_instanceNo;
634 return kodi::addon::GetUserPath(os.str());
635 }
636
637 std::string ApiManager::readPairFile(const std::string & pairFile)
638 {
639 std::string strContent;
640
641 kodi::Log(ADDON_LOG_DEBUG, "Openning file %s", pairFile.c_str());
642
643 kodi::vfs::CFile fileHandle;
644 if (fileHandle.OpenFile(pairFile, 0))
645 {
646 char buffer[1024];
647 while (int bytesRead = fileHandle.Read(buffer, 1024))
648 strContent.append(buffer, bytesRead);
649 }
650
651 return strContent;
652 }
653
654 void ApiManager::createPairFile(Json::Value & contentRoot) const
655 {
656 kodi::vfs::CFile fileHandle;
657 if (fileHandle.OpenFileForWrite(getPairFilePath(), true))
658 {
659 std::ostringstream os;
660 os << contentRoot;
661 const std::string & content = os.str();
662 fileHandle.Write(content.c_str(), content.length());
663 }
664 }
665
666 } // namespace sledovanitvcz