Debian Codegraph @

src/WaipuData.cpp

raw
1 /*
2 * Copyright (C) 2019 - 2021 flubshi
3 * https://github.com/flubshi
4 *
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
8 * any later version.
9 *
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, write to
17 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 */
21
22 #include "WaipuData.h"
23
24 #include "Base64.h"
25 #include "Utils.h"
26 #include "kodi/General.h"
27 #include "kodi/tools/StringUtils.h"
28 #include "rapidjson/document.h"
29
30 #include <algorithm>
31 #include <chrono>
32 #include <ctime>
33 #include <regex>
34 #include <set>
35 #include <thread>
36
37 #include <kodi/gui/dialogs/OK.h>
38 #include <kodi/gui/dialogs/Progress.h>
39 #include <kodi/gui/dialogs/YesNo.h>
40
41 std::mutex WaipuData::mutex;
42
43 // BEGIN CURL helpers from zattoo addon:
44 std::string WaipuData::HttpGet(const std::string& url,
45 const std::map<std::string,
46 std::string>& headers,
47 bool ignoreStatusCode)
48 {
49 return HttpRequest("GET", url, "", headers, ignoreStatusCode);
50 }
51
52 std::string WaipuData::HttpDelete(const std::string& url,
53 const std::string& postData,
54 const std::map<std::string,
55 std::string>& headers,
56 bool ignoreStatusCode)
57 {
58 return HttpRequest("DELETE", url, postData, headers, ignoreStatusCode);
59 }
60
61 std::string WaipuData::HttpPost(const std::string& url,
62 const std::string& postData,
63 const std::map<std::string,
64 std::string>& headers,
65 bool ignoreStatusCode)
66 {
67 return HttpRequest("POST", url, postData, headers, ignoreStatusCode);
68 }
69
70 std::string WaipuData::HttpRequest(const std::string& action,
71 const std::string& url,
72 const std::string& postData,
73 const std::map<std::string,
74 std::string>& headers,
75 bool ignoreStatusCode)
76 {
77 Curl curl;
78 int statusCode;
79
80 for (auto const& header : headers)
81 {
82 curl.AddHeader(header.first, header.second);
83 }
84
85 curl.AddHeader("Authorization", "Bearer " + m_accessToken.getToken());
86
87 curl.AddHeader("User-Agent", WAIPU_USER_AGENT);
88 kodi::Log(ADDON_LOG_DEBUG, "HTTP User-Agent: %s.", WAIPU_USER_AGENT.c_str());
89
90 return HttpRequestToCurl(curl, action, url, postData, statusCode, ignoreStatusCode);
91 }
92
93 std::string WaipuData::HttpRequestToCurl(Curl& curl,
94 const std::string& action,
95 const std::string& url,
96 const std::string& postData,
97 int& statusCode,
98 bool ignoreStatusCode)
99 {
100 kodi::Log(ADDON_LOG_DEBUG, "Http-Request: %s %s.", action.c_str(), url.c_str());
101 std::string content;
102 if (action == "POST")
103 {
104 content = curl.Post(url, postData, statusCode);
105 }
106 else if (action == "DELETE")
107 {
108 content = curl.Delete(url, postData, statusCode);
109 }
110 else if (action == "PUT")
111 {
112 content = curl.Put(url, postData, statusCode);
113 }
114 else
115 {
116 content = curl.Get(url, statusCode);
117 }
118 if (ignoreStatusCode || (statusCode >= 200 && statusCode < 300))
119 return content;
120
121 kodi::Log(ADDON_LOG_ERROR, "[Http-GET-Request] error. status: %i, body: %s", statusCode,
122 content.c_str());
123 return "";
124 }
125 // END CURL helpers from zattoo addon
126
127 // returns true if m_apiToken contains valid session
128 bool WaipuData::IsConnected()
129 {
130 return m_login_status == WAIPU_LOGIN_STATUS::OK;
131 }
132
133 WAIPU_LOGIN_STATUS WaipuData::Login()
134 {
135 kodi::Log(ADDON_LOG_DEBUG, "[token] current time %i", std::time(0));
136 kodi::Log(ADDON_LOG_DEBUG, "[token] expire time %i", m_accessToken.getExp());
137 if (m_accessToken.isInitialized() && !m_accessToken.isExpired(20 * 60))
138 {
139 // API token exists and is valid, more than x in future
140 kodi::Log(ADDON_LOG_DEBUG, "[login check] old token still valid");
141 return WAIPU_LOGIN_STATUS::OK;
142 }
143
144 if (m_refreshToken.isInitialized() && !m_refreshToken.isExpired())
145 {
146 // Since the refresh token is valid for a long time, we do not check expiration for now
147 // refresh API token
148 std::string req = "refresh_token=" + Utils::UrlEncode(m_refreshToken.getToken()) +
149 "&grant_type=refresh_token" + "&waipu_device_id=" + m_device_id;
150 kodi::Log(ADDON_LOG_DEBUG, "[login check] Login-Request (refresh): %s;", req.c_str());
151 return OAuthRequest(req);
152 }
153
154 if (m_provider == WAIPU_PROVIDER_WAIPU)
155 {
156 kodi::Log(ADDON_LOG_DEBUG, "[login check] WAIPU.TV LOGIN...");
157
158 // get API by login user/pw
159 std::string req = "username=" + Utils::UrlEncode(m_username) +
160 "&password=" + Utils::UrlEncode(m_password) + "&grant_type=password" +
161 "&waipu_device_id=" + m_device_id;
162 kodi::Log(ADDON_LOG_DEBUG, "[login check] Login-Request (user/pw)");
163 return OAuthRequest(req);
164 }
165 else if (m_provider == WAIPU_PROVIDER_O2)
166 {
167 return DeviceLogin("o2");
168 }
169
170 // waipu oauth device workflow
171 return DeviceLogin("waipu");
172 }
173
174 void WaipuData::EPGTaskThread()
175 {
176 rapidjson::Document epgDoc;
177 while (true)
178 {
179 if (!m_EPGTaskThreadRunning)
180 return;
181
182 if (m_queue_epgtag_tasks.empty())
183 {
184 kodi::Log(ADDON_LOG_DEBUG, "Task queue empty - wait");
185 std::this_thread::sleep_for(std::chrono::milliseconds(200));
186 continue;
187 }
188 EPGQueueTask epgTask = m_queue_epgtag_tasks.pop();
189
190 kodi::Log(ADDON_LOG_DEBUG, "[epg-details] process %s", epgTask.epgid.c_str());
191
192 std::string jsonEpg =
193 HttpGet("https://epg-cache.waipu.tv/api/programs/" + epgTask.epgid );
194 kodi::Log(ADDON_LOG_DEBUG, "[epg-details] %s", jsonEpg.c_str());
195 if (jsonEpg.empty())
196 {
197 kodi::Log(ADDON_LOG_ERROR, "[epg-details] empty server response");
198 std::this_thread::sleep_for(std::chrono::milliseconds(3000));
199 continue;
200 }
201
202 epgDoc.ParseInsitu<rapidjson::kParseInsituFlag>(&jsonEpg[0]);
203 if (epgDoc.HasParseError())
204 {
205 kodi::Log(ADDON_LOG_ERROR, "[epg-details] ERROR: error while parsing json");
206 std::this_thread::sleep_for(std::chrono::milliseconds(3000));
207 continue;
208 }
209
210 if (!epgDoc.HasMember("id"))
211 {
212 kodi::Log(ADDON_LOG_ERROR, "[epg-details] ERROR: Missing epg id");
213 std::this_thread::sleep_for(std::chrono::milliseconds(3000));
214 continue;
215 }
216
217 kodi::addon::PVREPGTag epgTag = ParseEPGTagEntry(epgDoc, epgTask.kodiChannelID, epgTask.waipuChannelID, false);
218 kodi::addon::CInstancePVRClient::EpgEventStateChange(epgTag, EPG_EVENT_UPDATED);
219 kodi::Log(ADDON_LOG_DEBUG, "[epg-details] updated %s", epgTag.GetTitle().c_str());
220 std::this_thread::sleep_for(std::chrono::milliseconds(10));
221 }
222 }
223
224 void WaipuData::LoginThread()
225 {
226 while (true)
227 {
228 if (!m_loginThreadRunning)
229 return;
230
231 std::this_thread::sleep_for(std::chrono::milliseconds(100));
232
233 if (m_nextLoginAttempt > std::time(0) ||
234 m_login_status == WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS)
235 continue;
236
237 if (m_login_failed_counter >= WAIPU_LOGIN_FAILED_LOCK_LIMIT)
238 {
239 kodi::Log(ADDON_LOG_ERROR, "[API LOGIN] Reset login lock due to timer");
240 m_login_failed_counter = 0;
241 }
242
243 auto previousStatus = m_login_status;
244 m_login_status = Login();
245
246 m_nextLoginAttempt = std::time(0) + 1;
247 if (m_login_status == WAIPU_LOGIN_STATUS::OK)
248 {
249 // login okay, reset counter
250 m_login_failed_counter = 0;
251
252 kodi::addon::CInstancePVRClient::ConnectionStateChange("Connected",
253 PVR_CONNECTION_STATE_CONNECTED, "");
254 m_nextLoginAttempt = std::time(0) + 60;
255
256 if (previousStatus != m_login_status || m_lastUpdate < std::time(0) - 30 * 60)
257 {
258 m_lastUpdate = std::time(0);
259 kodi::addon::CInstancePVRClient::TriggerChannelUpdate();
260 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
261 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
262 }
263
264 continue;
265 } else if (m_login_status == WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS) {
266 kodi::QueueNotification(QUEUE_ERROR, "", kodi::addon::GetLocalizedString(30030));
267 }
268
269 kodi::addon::CInstancePVRClient::ConnectionStateChange("Connecting",
270 PVR_CONNECTION_STATE_CONNECTING, "");
271
272 if (m_login_status == WAIPU_LOGIN_STATUS::NO_NETWORK)
273 continue;
274
275 if (++m_login_failed_counter >= WAIPU_LOGIN_FAILED_LOCK_LIMIT)
276 m_nextLoginAttempt = std::time(0) + 180;
277 }
278 }
279
280 bool WaipuData::ParseAccessToken()
281 {
282 if (!m_accessToken.isInitialized() || m_accessToken.isExpired())
283 {
284 m_login_status = WAIPU_LOGIN_STATUS::UNKNOWN;
285 kodi::Log(ADDON_LOG_ERROR, "[jwt_doc] ERROR: error while parsing json (error/expired)");
286 return false;
287 }
288
289 m_userhandle = m_accessToken.parsedToken["userHandle"].GetString();
290 kodi::Log(ADDON_LOG_DEBUG, "[jwt] userHandle: %s", m_userhandle.c_str());
291 // generate the license
292 std::string license_plain = "{\"merchant\" : \"exaring\", \"sessionId\" : \"default\", "
293 "\"userId\" : \"" +
294 m_userhandle + "\"}";
295 kodi::Log(ADDON_LOG_DEBUG, "[jwt] license_plain: %s", license_plain.c_str());
296 m_license = base64_encode(license_plain.c_str(), license_plain.length());
297 kodi::Log(ADDON_LOG_DEBUG, "[jwt] license: %s", m_license.c_str());
298
299 if (m_accessToken.parsedToken.HasMember("userAssets"))
300 {
301 if (m_accessToken.parsedToken["userAssets"].HasMember("instantRestart"))
302 {
303 m_account_replay_allowed = m_accessToken.parsedToken["userAssets"]["instantRestart"].GetBool();
304 kodi::Log(ADDON_LOG_DEBUG, "[jwt] Account InstantStart: %i", m_account_replay_allowed);
305 }
306 if (m_accessToken.parsedToken["userAssets"].HasMember("hoursRecording"))
307 {
308 m_account_hours_recording = m_accessToken.parsedToken["userAssets"]["hoursRecording"].GetInt();
309 kodi::Log(ADDON_LOG_DEBUG, "[jwt] Account HoursReording: %i", m_account_hours_recording);
310 }
311 }
312 m_login_status = WAIPU_LOGIN_STATUS::OK;
313 return true;
314 }
315
316 const std::map<std::string, std::string> WaipuData::GetOAuthDeviceCode(const std::string& tenant)
317 {
318 kodi::Log(ADDON_LOG_DEBUG, "[device] GetOAuthDeviceCode, tenant '%s'", tenant.c_str());
319 std::string jsonString;
320 std::map<std::string, std::string> result;
321 // curl request
322 Curl curl;
323 int statusCode = 0;
324 curl.AddHeader("Authorization", "Basic YW5kcm9pZENsaWVudDpzdXBlclNlY3JldA==");
325 curl.AddHeader("Content-Type", "application/json");
326 curl.AddHeader("User-Agent", WAIPU_USER_AGENT);
327 jsonString = HttpRequestToCurl(curl, "POST", "https://auth.waipu.tv/oauth/device_authorization",
328 "{\"client_id\":\"" + tenant + "\", \"waipu_device_id\":\"" +
329 m_device_id + "\"}",
330 statusCode);
331
332 kodi::Log(ADDON_LOG_DEBUG, "[login check] GetOAuthDeviceCode-response: (HTTP %i) %s;", statusCode,
333 jsonString.c_str());
334
335 if (jsonString.empty() && statusCode == -1)
336 {
337 // no network connection?
338 kodi::Log(ADDON_LOG_ERROR, "[GetOAuthDeviceCode] no network connection");
339 return result;
340 }
341
342 if (!jsonString.empty())
343 {
344 rapidjson::Document doc;
345 doc.Parse(jsonString.c_str());
346 if (doc.HasParseError())
347 {
348 kodi::Log(ADDON_LOG_ERROR, "[GetOAuthDeviceCode] ERROR: error while parsing json");
349 return result;
350 }
351 for (const std::string key :
352 {"verification_uri", "user_code", "device_code", "verification_uri_complete"})
353 {
354 if (doc.HasMember(key.c_str()))
355 {
356 const std::string value = doc[key.c_str()].GetString();
357 kodi::Log(ADDON_LOG_DEBUG, "[GetOAuthDeviceCode] found %s: %s", key.c_str(), value.c_str());
358 result[key] = value;
359 }
360 }
361 }
362 return result;
363 }
364
365 const std::map<std::string, std::string> WaipuData::CheckOAuthState(const std::string& device_code)
366 {
367 kodi::Log(ADDON_LOG_DEBUG, "[device] CheckOAuthState");
368 std::string jsonString;
369 std::map<std::string, std::string> result;
370 // curl request
371 Curl curl;
372 int statusCode = 0;
373 curl.AddHeader("Authorization", "Basic YW5kcm9pZENsaWVudDpzdXBlclNlY3JldA==");
374 curl.AddHeader("User-Agent", WAIPU_USER_AGENT);
375 jsonString = HttpRequestToCurl(
376 curl, "POST", "https://auth.waipu.tv/oauth/token",
377 "device_code=" + device_code +
378 "&grant_type=urn:ietf:params:oauth:grant-type:device_code&waipu_device_id=" + m_device_id,
379 statusCode);
380
381 kodi::Log(ADDON_LOG_DEBUG, "[login check] CheckOAuthState-response: (HTTP %i) %s;", statusCode,
382 jsonString.c_str());
383
384 if (jsonString.empty() && statusCode == -1)
385 {
386 // no network connection?
387 kodi::Log(ADDON_LOG_ERROR, "[CheckOAuthState] no network connection");
388 return result;
389 }
390
391 if (!jsonString.empty())
392 {
393 rapidjson::Document doc;
394 doc.Parse(jsonString.c_str());
395 if (doc.HasParseError())
396 {
397 kodi::Log(ADDON_LOG_ERROR, "[CheckOAuthState] ERROR: error while parsing json");
398 return result;
399 }
400 for (const std::string key : {"access_token", "refresh_token", "token_type"})
401 {
402 if (doc.HasMember(key.c_str()))
403 {
404 const std::string value = doc[key.c_str()].GetString();
405 kodi::Log(ADDON_LOG_DEBUG, "[CheckOAuthState] found %s: %s", key.c_str(), value.c_str());
406 result[key] = value;
407 }
408 }
409 }
410 return result;
411 }
412
413 WAIPU_LOGIN_STATUS WaipuData::OAuthRequest(const std::string& postData)
414 {
415 kodi::Log(ADDON_LOG_DEBUG, "[OAuthRequest] Body: %s;", postData.c_str());
416 std::string jsonString;
417 // curl request
418 Curl curl;
419 int statusCode = 0;
420 curl.AddHeader("Authorization", "Basic YW5kcm9pZENsaWVudDpzdXBlclNlY3JldA==");
421 // curl.AddHeader("Content-Type", "application/x-www-form-urlencoded");
422 curl.AddHeader("User-Agent", WAIPU_USER_AGENT);
423 jsonString =
424 HttpRequestToCurl(curl, "POST", "https://auth.waipu.tv/oauth/token", postData, statusCode);
425
426 kodi::Log(ADDON_LOG_DEBUG, "[OAuthRequest] Login-response: (HTTP %i) %s;", statusCode,
427 jsonString.c_str());
428
429 if (statusCode == -1)
430 {
431 // no network connection?
432 kodi::Log(ADDON_LOG_ERROR, "[OAuthRequest] no network connection");
433 return WAIPU_LOGIN_STATUS::NO_NETWORK;
434 }
435 else if (statusCode == 401)
436 {
437 if (m_refreshToken.isInitialized() && !m_refreshToken.isExpired())
438 {
439 // we used invalid refresh token, delete it
440 m_refreshToken = JWT();
441 return WAIPU_LOGIN_STATUS::UNKNOWN;
442 }
443 // invalid credentials
444 return WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS;
445 }
446
447 if (jsonString.empty())
448 return WAIPU_LOGIN_STATUS::UNKNOWN;
449
450 rapidjson::Document doc;
451 doc.Parse(jsonString.c_str());
452 if (doc.HasParseError())
453 {
454 kodi::Log(ADDON_LOG_ERROR, "[OAuthRequest] ERROR: error while parsing json");
455 return WAIPU_LOGIN_STATUS::UNKNOWN;
456 }
457
458 if (doc.HasMember("error"))
459 {
460 if (doc["error"] == "invalid_request")
461 {
462 kodi::Log(ADDON_LOG_ERROR, "[OAuthRequest] ERROR: invalid credentials?");
463 return WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS;
464 }
465
466 // unhandled error -> handle if known
467 std::string err = doc["error"].GetString();
468 kodi::Log(ADDON_LOG_ERROR, "[OAuthRequest] ERROR: (%s)", err.c_str());
469 return WAIPU_LOGIN_STATUS::UNKNOWN;
470 }
471
472 m_accessToken = JWT(doc["access_token"].GetString());
473 kodi::Log(ADDON_LOG_DEBUG, "[OAuthRequest] accessToken: %s;", m_accessToken.getToken().c_str());
474 std::string refresh_token = doc["refresh_token"].GetString();
475 if (!refresh_token.empty())
476 {
477 m_refreshToken = JWT(refresh_token);
478 kodi::addon::SetSettingString("refresh_token", refresh_token);
479 kodi::Log(ADDON_LOG_DEBUG, "[OAuthRequest] refreshToken: %s;", refresh_token.c_str());
480 }
481
482 return ParseAccessToken() ? WAIPU_LOGIN_STATUS::OK : WAIPU_LOGIN_STATUS::UNKNOWN;
483 }
484
485 WAIPU_LOGIN_STATUS WaipuData::DeviceLogin(const std::string& tenant)
486 {
487 WAIPU_LOGIN_STATUS ret = WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS;
488
489 kodi::Log(ADDON_LOG_DEBUG, "[DeviceLogin] waipu.tv DeviceLogin, tenant '%s' ...", tenant.c_str());
490
491 const std::map<std::string, std::string> deviceCodeMap = GetOAuthDeviceCode(tenant);
492 if (!deviceCodeMap.count("verification_uri") || !deviceCodeMap.count("user_code") ||
493 !deviceCodeMap.count("device_code"))
494 {
495 kodi::Log(ADDON_LOG_DEBUG, "OAuth missing response");
496 return ret;
497 }
498 std::string code_req =
499 "device_code=" + deviceCodeMap.find("device_code")->second +
500 "&grant_type=urn:ietf:params:oauth:grant-type:device_code&waipu_device_id=" + m_device_id;
501 kodi::Log(ADDON_LOG_DEBUG, "Create Login Progress");
502 kodi::gui::dialogs::CProgress* progress = new kodi::gui::dialogs::CProgress;
503 progress->SetHeading("pvr.waipu - " + tenant + " Login");
504 progress->SetLine(1, "1) " + kodi::addon::GetLocalizedString(30039) + " " +
505 deviceCodeMap.find("verification_uri")->second);
506 progress->SetLine(2, "2) " + kodi::addon::GetLocalizedString(30040));
507 progress->SetLine(3, "3) " + kodi::addon::GetLocalizedString(30041) + " " +
508 deviceCodeMap.find("user_code")->second);
509 progress->SetCanCancel(true);
510 progress->ShowProgressBar(true);
511 progress->Open();
512 for (unsigned int i = 0; i < 100; i += 1)
513 {
514 progress->SetPercentage(i);
515 if (OAuthRequest(code_req) == WAIPU_LOGIN_STATUS::OK)
516 {
517 ret = WAIPU_LOGIN_STATUS::OK;
518 kodi::Log(ADDON_LOG_DEBUG, "OAuth success!");
519 break;
520 }
521
522 kodi::Log(ADDON_LOG_DEBUG, "OAuth pending");
523
524 if (progress->IsCanceled())
525 {
526 progress->Abort();
527 ret = WAIPU_LOGIN_STATUS::INVALID_CREDENTIALS;
528 kodi::Log(ADDON_LOG_DEBUG, "OAuth login canceled");
529 break;
530 }
531 std::this_thread::sleep_for(std::chrono::seconds(3));
532 }
533
534 progress->Abort();
535 delete progress;
536
537 return ret;
538 }
539
540 bool WaipuData::RefreshDeviceCapabiltiesToken()
541 {
542 kodi::Log(ADDON_LOG_DEBUG, "%s - Creating the waipu.tv PVR add-on", __FUNCTION__);
543
544 kodi::Log(ADDON_LOG_DEBUG, "[device token] expire time %i", m_deviceCapabilitiesToken.getExp());
545 if (m_deviceCapabilitiesToken.isInitialized() && !m_deviceCapabilitiesToken.isExpired(5 * 60))
546 {
547 // device token exists and is valid, more than x in future
548 kodi::Log(ADDON_LOG_DEBUG, "[device token] old token still valid, no need to refresh");
549 return true;
550 }
551
552 // Get new device token
553 kodi::Log(ADDON_LOG_DEBUG, "[device token] New deviceToken required...");
554
555 // \"sdpalp25\": false, \"sdpalp50\": false, \"hd720p25\": false, \"hd720p50\": false,
556 std::string appVersion;
557 GetBackendVersion(appVersion);
558
559 kodi_version_t kodi_version;
560 kodi::KodiVersion(kodi_version);
561
562 bool cap_audio_aac = kodi::addon::GetSettingBoolean("streaming_capabilities_audio_aac", false);
563
564 std::string capabilitesData =
565 "{\"type\": \"receiver\", \"model\": \"Kodi " + std::to_string(kodi_version.major) + "." +
566 std::to_string(kodi_version.minor) +
567 "\", \"manufacturer\": \"Team Kodi\", "
568 "\"platform\": \"Kodi " +
569 std::to_string(kodi_version.major) + "." + std::to_string(kodi_version.minor) +
570 "-pvr.waipu\", \"appVersion\": \"" + appVersion +
571 "\", \"capabilities\": {\"audio\": {\"aac\": " + (cap_audio_aac ? "true" : "false") +
572 "},\"video\": { ";
573
574 std::vector<std::string> video_cap_options = {"sdpalp25", "sdpalp50", "hd720p25",
575 "hd720p50", "hd1080p25", "hd1080p50",
576 "hevc1080p50", "hevc2160p50"};
577 bool first = true;
578 for (const std::string& cap_option : video_cap_options)
579 {
580 bool cap_value =
581 kodi::addon::GetSettingBoolean("streaming_capabilities_video_" + cap_option, false);
582 capabilitesData +=
583 std::string(first ? "" : ",") + "\"" + cap_option + "\": " + (cap_value ? "true" : "false");
584 first = false;
585 }
586 capabilitesData += "}}}";
587
588 std::string jsonDeviceToken =
589 HttpPost("https://device-capabilities.waipu.tv/api/device-capabilities", capabilitesData,
590 {{"Content-Type", "application/vnd.dc.device-info-v1+json"},
591 {"X-USERCONTEXT-USERHANDLE", m_userhandle.c_str()}});
592
593 kodi::Log(ADDON_LOG_DEBUG, "[X-Device-Token] response: %s", jsonDeviceToken.c_str());
594
595 rapidjson::Document deviceTokenDoc;
596 deviceTokenDoc.Parse(jsonDeviceToken.c_str());
597 if (deviceTokenDoc.HasParseError())
598 {
599 kodi::Log(ADDON_LOG_DEBUG, "[X-Device-Token] parse error :(");
600 return false;
601 }
602
603 if (deviceTokenDoc.HasMember("token"))
604 {
605 m_deviceCapabilitiesToken = JWT(deviceTokenDoc["token"].GetString());
606 kodi::Log(ADDON_LOG_DEBUG, "[X-Device-Token] discovered token: %s",
607 m_deviceCapabilitiesToken.getToken().c_str());
608 return true;
609 }
610
611 kodi::Log(ADDON_LOG_DEBUG, "[X-Device-Token] unknown error :(");
612 return false;
613 }
614
615 void WaipuData::ReadSettings()
616 {
617 kodi::Log(ADDON_LOG_DEBUG, "waipu.tv function call: [%s]", __FUNCTION__);
618
619 m_username = kodi::addon::GetSettingString("username");
620 m_password = kodi::addon::GetSettingString("password");
621 m_protocol = kodi::addon::GetSettingString("protocol", "auto");
622 m_provider = kodi::addon::GetSettingEnum<WAIPU_PROVIDER>("provider_select", WAIPU_PROVIDER_WAIPU);
623 m_channel_filter = kodi::addon::GetSettingEnum<WAIPU_CHANNEL_IMPORT_FILTER>(
624 "channel_import_filter", CHANNEL_FILTER_ALL_VISIBLE);
625 m_epg_show_preview_images = kodi::addon::GetSettingBoolean("epg_show_preview_images");
626 m_recordings_backend_handle_position = kodi::addon::GetSettingBoolean("recordings_backend_handle_position");
627 m_refreshToken = JWT(kodi::addon::GetSettingString("refresh_token", ""));
628 m_first_channel_number = kodi::addon::GetSettingInt("first_channel_number");
629
630 m_device_id = kodi::addon::GetSettingString("device_id_uuid4");
631 if (m_device_id.empty())
632 {
633 m_device_id = Utils::CreateUUID();
634 kodi::addon::SetSettingString("device_id_uuid4", m_device_id);
635 // new device id -> force new login
636 m_refreshToken = JWT();
637 }
638
639 kodi::Log(ADDON_LOG_DEBUG, "End Readsettings");
640 }
641
642 ADDON_STATUS WaipuData::SetSetting(const std::string& settingName,
643 const kodi::addon::CSettingValue& settingValue)
644 {
645 if (settingName == "username")
646 {
647 std::string username = settingValue.GetString();
648 if (username != m_username)
649 {
650 m_username = username;
651 m_login_failed_counter = 0;
652 kodi::addon::SetSettingString("refresh_token", "");
653 return ADDON_STATUS_NEED_RESTART;
654 }
655 }
656 else if (settingName == "password")
657 {
658 std::string password = settingValue.GetString();
659 if (password != m_password)
660 {
661 m_login_failed_counter = 0;
662 m_password = password;
663 kodi::addon::SetSettingString("refresh_token", "");
664 return ADDON_STATUS_NEED_RESTART;
665 }
666 }
667 else if (settingName == "protocol")
668 {
669 m_protocol = settingValue.GetString();
670 return ADDON_STATUS_OK;
671 }
672 else if (settingName == "epg_show_preview_images")
673 {
674 m_epg_show_preview_images = settingValue.GetBoolean();
675 return ADDON_STATUS_OK;
676 }
677 else if (settingName == "provider_select")
678 {
679 WAIPU_PROVIDER tmpProvider = settingValue.GetEnum<WAIPU_PROVIDER>();
680 if (tmpProvider != m_provider)
681 {
682 m_login_failed_counter = 0;
683 m_provider = tmpProvider;
684 kodi::addon::SetSettingString("refresh_token", "");
685 return ADDON_STATUS_NEED_RESTART;
686 }
687 }
688 else if (settingName == "channel_import_filter")
689 {
690 WAIPU_CHANNEL_IMPORT_FILTER tmpFilter = settingValue.GetEnum<WAIPU_CHANNEL_IMPORT_FILTER>();
691 if (tmpFilter != m_channel_filter)
692 {
693 m_channel_filter = tmpFilter;
694 // reload channels
695 m_channels.clear();
696 kodi::addon::CInstancePVRClient::TriggerChannelUpdate();
697 return ADDON_STATUS_OK;
698 }
699 }
700 else if (settingName == "first_channel_number")
701 {
702 const int tmp_first_channel_number = settingValue.GetInt();
703 if (m_first_channel_number != tmp_first_channel_number)
704 {
705 m_first_channel_number = tmp_first_channel_number;
706 // kodi does not update channel ID without restart
707 return ADDON_STATUS_NEED_RESTART;
708 }
709 }
710 else if (settingName.rfind("streaming_capabilities_", 0) == 0)
711 {
712 // settings name begins with "streaming_capabilities_"
713 // reset capabilities to force refresh
714 m_deviceCapabilitiesToken = JWT();
715 }
716 else if (settingName == "refresh_reset" && settingValue.GetBoolean())
717 {
718 kodi::addon::SetSettingBoolean("refresh_reset", false);
719 kodi::addon::SetSettingString("refresh_token", "");
720 return ADDON_STATUS_NEED_RESTART;
721 }
722 else if (settingName == "recordings_additional_infos")
723 {
724 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
725 }
726 else if (settingName == "recordings_backend_handle_position")
727 {
728 if (settingValue.GetBoolean() != m_recordings_backend_handle_position)
729 {
730 m_recordings_backend_handle_position = settingValue.GetBoolean();
731 return ADDON_STATUS_NEED_RESTART;
732 }
733 }
734
735 return ADDON_STATUS_OK;
736 }
737
738 PVR_ERROR WaipuData::GetCapabilities(kodi::addon::PVRCapabilities& capabilities)
739 {
740 capabilities.SetSupportsEPG(true);
741 capabilities.SetSupportsTV(true);
742 capabilities.SetSupportsRecordings(true);
743 capabilities.SetSupportsRecordingsDelete(true);
744 capabilities.SetSupportsTimers(true);
745 capabilities.SetSupportsChannelGroups(true);
746
747 const bool handle_position = kodi::addon::GetSettingBoolean("recordings_backend_handle_position", false);
748 capabilities.SetSupportsLastPlayedPosition(handle_position);
749
750 return PVR_ERROR_NO_ERROR;
751 }
752
753 PVR_ERROR WaipuData::GetBackendName(std::string& name)
754 {
755 name = "waipu.tv PVR add-on";
756 return PVR_ERROR_NO_ERROR;
757 }
758
759 PVR_ERROR WaipuData::GetBackendVersion(std::string& version)
760 {
761 version = STR(IPTV_VERSION);
762 return PVR_ERROR_NO_ERROR;
763 }
764
765 const std::string& WaipuData::GetLicense()
766 {
767 return m_license;
768 }
769
770 void WaipuData::SetStreamProperties(std::vector<kodi::addon::PVRStreamProperty>& properties,
771 const std::string& url,
772 bool realtime,
773 bool playTimeshiftBuffer,
774 const std::string& protocol)
775 {
776 kodi::Log(ADDON_LOG_DEBUG, "[PLAY STREAM] url: %s", url.c_str());
777
778 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, url);
779 properties.emplace_back(PVR_STREAM_PROPERTY_ISREALTIMESTREAM, realtime ? "true" : "false");
780
781 if ((protocol == "dash" || protocol == "MPEG_DASH") && Utils::CheckInputstreamInstalledAndEnabled("inputstream.adaptive"))
782 {
783 // MPEG DASH
784 kodi::Log(ADDON_LOG_DEBUG, "[PLAY STREAM] dash");
785 properties.emplace_back(PVR_STREAM_PROPERTY_INPUTSTREAM, "inputstream.adaptive");
786 properties.emplace_back("inputstream.adaptive.manifest_type", "mpd");
787 properties.emplace_back(PVR_STREAM_PROPERTY_MIMETYPE, "application/xml+dash");
788
789 if (playTimeshiftBuffer)
790 {
791 properties.emplace_back("inputstream.adaptive.play_timeshift_buffer", "true");
792 }
793
794 // get widevine license
795 std::string license = GetLicense();
796 properties.emplace_back("inputstream.adaptive.license_type", "com.widevine.alpha");
797 properties.emplace_back("inputstream.adaptive.license_key",
798 "https://drm.wpstr.tv/license-proxy-widevine/cenc/"
799 "|Content-Type=text%2Fxml&x-dt-custom-data=" +
800 license + "|R{SSM}|JBlicense");
801 }
802 else if ((protocol == "hls" || protocol == "HLS") && kodi::addon::GetSettingBoolean("streaming_use_ffmpegdirect", false))
803 {
804 if (!Utils::CheckInputstreamInstalledAndEnabled("inputstream.ffmpegdirect"))
805 {
806 kodi::addon::SetSettingBoolean("streaming_use_ffmpegdirect", false);
807 return;
808 }
809 // HLS
810 kodi::Log(ADDON_LOG_DEBUG, "[PLAY STREAM] hls using inputstream.ffmpegdirect");
811 properties.emplace_back(PVR_STREAM_PROPERTY_INPUTSTREAM, "inputstream.ffmpegdirect");
812 properties.emplace_back("inputstream.ffmpegdirect.manifest_type", "hls");
813 properties.emplace_back(PVR_STREAM_PROPERTY_MIMETYPE, "application/x-mpegURL");
814 properties.emplace_back("inputstream.ffmpegdirect.is_realtime_stream",
815 realtime ? "true" : "false");
816 }
817 else if ((protocol == "hls" || protocol == "HLS") && Utils::CheckInputstreamInstalledAndEnabled("inputstream.adaptive"))
818 {
819 kodi::Log(ADDON_LOG_DEBUG,
820 "[SetStreamProperties] play protocol '%s' using inputstream adaptive",
821 protocol.c_str());
822
823 properties.emplace_back(PVR_STREAM_PROPERTY_INPUTSTREAM, "inputstream.adaptive");
824 properties.emplace_back("inputstream.adaptive.manifest_type", "hls");
825 properties.emplace_back(PVR_STREAM_PROPERTY_MIMETYPE, "application/x-mpegURL");
826
827 if (playTimeshiftBuffer)
828 {
829 properties.emplace_back("inputstream.adaptive.play_timeshift_buffer", "true");
830 }
831 }
832 else
833 {
834 kodi::Log(
835 ADDON_LOG_ERROR,
836 "[SetStreamProperties] called with invalid protocol '%s' or missing inputstream addon.",
837 protocol.c_str());
838 }
839 }
840
841 bool WaipuData::LoadChannelData()
842 {
843 if (m_channels.size() > 0)
844 return true;
845
846 // user wishes no channels, maybe just uses the plugin for recordings?
847 if (m_channel_filter == CHANNEL_FILTER_NONE)
848 return true;
849
850 // no valid session
851 if (!IsConnected())
852 return false;
853
854 std::lock_guard<std::mutex> lock(mutex);
855
856 if (m_channels.size() > 0)
857 return true;
858
859 std::string stationConfigJson = HttpGet("https://web-proxy.waipu.tv/station-config");
860 kodi::Log(ADDON_LOG_DEBUG, "[%s] Station config JSON: %s", __FUNCTION__,
861 stationConfigJson.c_str());
862
863 rapidjson::Document stationConfigDoc;
864 stationConfigDoc.Parse(stationConfigJson.c_str());
865 if (stationConfigDoc.HasParseError())
866 {
867 kodi::Log(ADDON_LOG_ERROR, "[%s] Error while parsing station config JSON", __FUNCTION__);
868 m_login_status = WAIPU_LOGIN_STATUS::UNKNOWN;
869 return false;
870 }
871 const auto& stationConfigs = stationConfigDoc["stations"].GetArray();
872
873 std::string userStationsJson =
874 HttpGet("https://user-stations.waipu.tv/api/stations?omitted=false");
875 kodi::Log(ADDON_LOG_DEBUG, "[%s] User stations JSON: %s", __FUNCTION__, userStationsJson.c_str());
876
877 rapidjson::Document doc;
878 doc.Parse(userStationsJson.c_str());
879 if (doc.HasParseError())
880 {
881 kodi::Log(ADDON_LOG_ERROR, "[%s] Error while parsing user stations JSON", __FUNCTION__);
882 m_login_status = WAIPU_LOGIN_STATUS::UNKNOWN;
883 return false;
884 }
885
886 m_channelGroups.clear();
887
888 WaipuChannelGroup cgroup_fav;
889 cgroup_fav.name = "Favoriten";
890
891 WaipuChannelGroup cgroup_live;
892 cgroup_live.name = "Live TV";
893
894 WaipuChannelGroup cgroup_vod;
895 cgroup_vod.name = "VoD";
896
897 for (rapidjson::SizeType i = 0; i < doc.Size(); i++)
898 {
899 const auto& channel = doc[i];
900 const std::string waipuId = channel["stationId"].GetString();
901 if (channel.HasMember("locked") && channel["locked"].GetBool())
902 {
903 kodi::Log(ADDON_LOG_DEBUG, "[%s] Skip locked channel '%s'", __FUNCTION__, waipuId.c_str());
904 continue;
905 }
906
907 const auto& stationConfig =
908 std::find_if(stationConfigs.begin(), stationConfigs.end(),
909 [waipuId](const auto& v) { return v["id"].GetString() == waipuId; });
910 if (stationConfig == stationConfigs.end())
911 continue;
912
913 WaipuChannel waipuChannel;
914
915 waipuChannel.iChannelNumber = i + 1; // position
916 waipuChannel.waipuID = waipuId; // waipu[id]
917 // workaround: transform Station ID to uppercase, since old API (for recordings/timers) needs this
918 std::transform(waipuChannel.waipuID.begin(), waipuChannel.waipuID.end(),
919 waipuChannel.waipuID.begin(), ::toupper);
920 waipuChannel.iUniqueId = Utils::Hash(waipuId);
921 waipuChannel.strChannelName = channel["displayName"].GetString(); // waipu[displayName]
922
923 std::string iconUrl = (*stationConfig)["logoTemplateUrl"].GetString();
924 iconUrl = std::regex_replace(iconUrl, std::regex("\\$\\{streamQuality\\}"),
925 channel["streamQuality"].GetString());
926 iconUrl = std::regex_replace(iconUrl, std::regex("\\$\\{shape\\}"), "standard");
927 iconUrl = std::regex_replace(iconUrl, std::regex("\\$\\{resolution\\}"), "320x180");
928
929 std::string iconPath =
930 "special://home/addons/pvr.waipu/resources/channel_icons/" + waipuChannel.waipuID + ".png";
931 if (!kodi::vfs::FileExists(iconPath, true))
932 {
933 kodi::Log(ADDON_LOG_DEBUG, "[%s] Downloading channel logo %s to %s", __FUNCTION__,
934 iconUrl.c_str(), iconPath.c_str());
935 Utils::FileDownload(iconUrl, iconPath);
936 }
937 waipuChannel.strIconPath = iconPath;
938
939 const auto& userSettings = channel["userSettings"].GetObject();
940 bool isFav = userSettings["favorite"].GetBool();
941 waipuChannel.isFavorite = isFav;
942 bool isVisible = userSettings["visible"].GetBool();
943 waipuChannel.tvfuse = (*stationConfig)["newTv"].GetBool();
944
945 // skip if we do not enforce to show all
946 if (m_channel_filter != CHANNEL_FILTER_ALL && !isVisible)
947 continue;
948
949 // Apply LiveTV filter (=!tvfuse)
950 if (m_channel_filter == CHANNEL_FILTER_LIVE && waipuChannel.tvfuse)
951 continue;
952
953 // Apply Favourites filter
954 if (m_channel_filter == CHANNEL_FILTER_FAVOURITES && !isFav)
955 continue;
956
957 // user added channel to favorites
958 if (isFav)
959 cgroup_fav.channels.emplace_back(waipuChannel);
960
961 if (waipuChannel.tvfuse) // Video on Demand channel
962 cgroup_vod.channels.emplace_back(waipuChannel);
963 else // Not VoD -> Live TV
964 cgroup_live.channels.emplace_back(waipuChannel);
965
966 kodi::Log(ADDON_LOG_DEBUG,
967 "[channel] number: %i, tvfuse: %i, waipuId: %s, id: %i, name: %s, logo: %s",
968 waipuChannel.iChannelNumber, waipuChannel.tvfuse, waipuChannel.waipuID.c_str(),
969 waipuChannel.iUniqueId, waipuChannel.strChannelName.c_str(),
970 waipuChannel.strIconPath.c_str());
971
972 m_channels.emplace_back(waipuChannel);
973 }
974
975 if (!cgroup_fav.channels.empty())
976 m_channelGroups.emplace_back(cgroup_fav);
977 if (!cgroup_live.channels.empty())
978 m_channelGroups.emplace_back(cgroup_live);
979 if (!cgroup_vod.channels.empty())
980 m_channelGroups.emplace_back(cgroup_vod);
981
982 return true;
983 }
984
985 PVR_ERROR WaipuData::GetChannelsAmount(int& amount)
986 {
987 if (!IsConnected())
988 return PVR_ERROR_SERVER_ERROR;
989
990 kodi::Log(ADDON_LOG_DEBUG, "waipu.tv function call: [%s]", __FUNCTION__);
991 LoadChannelData();
992
993 amount = static_cast<int>(m_channels.size());
994 return PVR_ERROR_NO_ERROR;
995 }
996
997 PVR_ERROR WaipuData::GetChannels(bool radio, kodi::addon::PVRChannelsResultSet& results)
998 {
999 if (!IsConnected())
1000 return PVR_ERROR_SERVER_ERROR;
1001
1002 if (radio)
1003 {
1004 kodi::Log(ADDON_LOG_ERROR,
1005 "[%s] ERROR: Function was called with invalid parameter 'radio: true'", __FUNCTION__);
1006 return PVR_ERROR_INVALID_PARAMETERS;
1007 }
1008
1009 kodi::Log(ADDON_LOG_DEBUG, "waipu.tv function call: [%s]", __FUNCTION__);
1010 LoadChannelData();
1011
1012 for (const auto& channel : m_channels)
1013 {
1014 kodi::addon::PVRChannel kodiChannel;
1015
1016 kodiChannel.SetUniqueId(channel.iUniqueId);
1017 kodiChannel.SetIsRadio(false);
1018 // set channel plus offset from settings:
1019 kodiChannel.SetChannelNumber(channel.iChannelNumber + m_first_channel_number - 1);
1020 kodiChannel.SetChannelName(channel.strChannelName);
1021 kodiChannel.SetIconPath(channel.strIconPath);
1022 kodiChannel.SetIsHidden(false);
1023
1024 results.Add(kodiChannel);
1025 }
1026 return PVR_ERROR_NO_ERROR;
1027 }
1028
1029 PVR_ERROR WaipuData::GetChannelStreamProperties(
1030 const kodi::addon::PVRChannel& channel, std::vector<kodi::addon::PVRStreamProperty>& properties)
1031 {
1032 LoadChannelData();
1033 PVR_ERROR ret = PVR_ERROR_FAILED;
1034 std::string protocol = m_protocol;
1035 if (protocol == "auto")
1036 {
1037 // use hls where possible, fallback to dash
1038 protocol = "dash";
1039
1040 const auto& thisChannel =
1041 std::find_if(m_channels.begin(), m_channels.end(),
1042 [channel](const auto& v) { return v.iUniqueId == channel.GetUniqueId(); });
1043
1044 if (thisChannel != m_channels.end() && m_hls_allowlist.contains((*thisChannel).waipuID))
1045 {
1046 protocol = "hls";
1047 }
1048 kodi::Log(ADDON_LOG_DEBUG, "protocol auto select: %s", protocol.c_str());
1049 }
1050
1051 std::string strUrl = GetChannelStreamURL(channel.GetUniqueId(), protocol, "");
1052 kodi::Log(ADDON_LOG_DEBUG, "Stream URL -> %s", strUrl.c_str());
1053
1054 if (!strUrl.empty())
1055 {
1056 SetStreamProperties(properties, strUrl, true, false, protocol);
1057 ret = PVR_ERROR_NO_ERROR;
1058 }
1059 return ret;
1060 }
1061
1062 std::string WaipuData::GetChannelStreamURL(int uniqueId,
1063 const std::string& protocol,
1064 const std::string& startTime)
1065 {
1066 if (!IsConnected())
1067 {
1068 kodi::Log(ADDON_LOG_DEBUG, "[GetStreamURL] No stream login");
1069 return "";
1070 }
1071
1072 for (const auto& channel : m_channels)
1073 {
1074 if (channel.iUniqueId == uniqueId)
1075 {
1076 kodi::Log(ADDON_LOG_DEBUG, "[GetStreamURL] Get live URL for channel %s",
1077 channel.strChannelName.c_str());
1078
1079 // ensure device token is fresh
1080 RefreshDeviceCapabiltiesToken();
1081
1082 std::string postData = "{\"stream\": { \"station\": \"" + channel.waipuID +
1083 "\", \"protocol\": \"" + protocol +
1084 "\", \"requestMuxInstrumentation\": false";
1085 if (!startTime.empty())
1086 {
1087 postData += ", \"startTime\": " + startTime;
1088 }
1089 postData += "}}";
1090 kodi::Log(ADDON_LOG_DEBUG, "[GetStreamURL] Post data: %s", postData.c_str());
1091
1092 std::string jsonStreamURL = HttpPost(
1093 "https://stream-url-provider.waipu.tv/api/stream-url", postData,
1094 {{"Content-Type", "application/vnd.streamurlprovider.stream-url-request-v1+json"},
1095 {"X-Device-Token", m_deviceCapabilitiesToken.getToken().c_str()}},
1096 true);
1097
1098 rapidjson::Document streamURLDoc;
1099 streamURLDoc.Parse(jsonStreamURL.c_str());
1100 if (streamURLDoc.HasParseError())
1101 {
1102 kodi::Log(ADDON_LOG_ERROR, "[GetStreamURL] ERROR: error while parsing json");
1103 return "";
1104 }
1105
1106 if (streamURLDoc.HasMember("status") &&
1107 streamURLDoc["status"].GetInt() == 403 &&
1108 streamURLDoc.HasMember("title") &&
1109 streamURLDoc.HasMember("detail"))
1110 {
1111 const std::string errorTitle = streamURLDoc["title"].GetString();
1112 const std::string errorDetail = streamURLDoc["detail"].GetString();
1113
1114 if (errorDetail == "User is not allowed to view this channel")
1115 {
1116 // subscription expired? we need to refresh available channels
1117 m_channels.clear();
1118 kodi::addon::CInstancePVRClient::TriggerChannelUpdate();
1119 }
1120
1121 kodi::gui::dialogs::OK::ShowAndGetInput(errorTitle, errorDetail);
1122 return "";
1123 }
1124 if (!streamURLDoc.HasMember("streamUrl"))
1125 {
1126 kodi::Log(ADDON_LOG_ERROR, "[GetStreamURL] ERROR: missing param streamUrl");
1127 kodi::Log(ADDON_LOG_ERROR, "[GetStreamURL] body: %s", jsonStreamURL.c_str());
1128 return "";
1129 }
1130
1131 return streamURLDoc["streamUrl"].GetString();
1132 }
1133 }
1134 return "";
1135 }
1136
1137 PVR_ERROR WaipuData::GetChannelGroupsAmount(int& amount)
1138 {
1139 if (!IsConnected())
1140 return PVR_ERROR_SERVER_ERROR;
1141
1142 LoadChannelData();
1143 amount = static_cast<int>(m_channelGroups.size());
1144 return PVR_ERROR_NO_ERROR;
1145 }
1146
1147 PVR_ERROR WaipuData::GetChannelGroups(bool radio, kodi::addon::PVRChannelGroupsResultSet& results)
1148 {
1149 if (!IsConnected())
1150 return PVR_ERROR_SERVER_ERROR;
1151
1152 if (radio)
1153 {
1154 kodi::Log(ADDON_LOG_ERROR,
1155 "[%s] ERROR: Function was called with invalid parameter 'radio: true'", __FUNCTION__);
1156 return PVR_ERROR_INVALID_PARAMETERS;
1157 }
1158
1159 LoadChannelData();
1160 std::vector<WaipuChannelGroup>::iterator it;
1161 for (it = m_channelGroups.begin(); it != m_channelGroups.end(); ++it)
1162 {
1163 kodi::addon::PVRChannelGroup kodiGroup;
1164
1165 kodiGroup.SetPosition(0); /* not supported */
1166 kodiGroup.SetIsRadio(false); /* is radio group */
1167 kodiGroup.SetGroupName(it->name);
1168
1169 results.Add(kodiGroup);
1170 }
1171 return PVR_ERROR_NO_ERROR;
1172 }
1173
1174 PVR_ERROR WaipuData::GetChannelGroupMembers(const kodi::addon::PVRChannelGroup& group,
1175 kodi::addon::PVRChannelGroupMembersResultSet& results)
1176 {
1177 if (group.GetIsRadio())
1178 {
1179 kodi::Log(ADDON_LOG_ERROR, "[%s] ERROR: Function was called with a group having 'radio: true'",
1180 __FUNCTION__);
1181 return PVR_ERROR_INVALID_PARAMETERS;
1182 }
1183
1184 LoadChannelData();
1185 for (const auto& cgroup : m_channelGroups)
1186 {
1187 if (cgroup.name != group.GetGroupName())
1188 continue;
1189
1190 for (const auto& channel : cgroup.channels)
1191 {
1192 kodi::addon::PVRChannelGroupMember kodiGroupMember;
1193
1194 kodiGroupMember.SetGroupName(group.GetGroupName());
1195 kodiGroupMember.SetChannelUniqueId(static_cast<unsigned int>(channel.iUniqueId));
1196 kodiGroupMember.SetChannelNumber(static_cast<unsigned int>(channel.iChannelNumber));
1197
1198 results.Add(kodiGroupMember);
1199 }
1200 return PVR_ERROR_NO_ERROR;
1201 }
1202
1203 return PVR_ERROR_NO_ERROR;
1204 }
1205
1206 kodi::addon::PVREPGTag WaipuData::ParseEPGTagEntry(const rapidjson::Value& tagEntry, const int kodiChanneliUniqueId, const std::string waipuChannelID, const bool reSchedule)
1207 {
1208 kodi::addon::PVREPGTag tag;
1209
1210 // get id, example: 1f2b25b5-0a39-5957-b411-3825326a3e54
1211 const std::string epg_id = tagEntry["id"].GetString();
1212 kodi::Log(ADDON_LOG_DEBUG, "[epg] epg_id: %s;", epg_id.c_str());
1213 int dirtyID = Utils::GetIDDirty(epg_id);
1214 kodi::Log(ADDON_LOG_DEBUG, "[epg] epg_id dirty: %i;", dirtyID);
1215 tag.SetUniqueBroadcastId(dirtyID);
1216
1217 // channel ID
1218 tag.SetUniqueChannelId(kodiChanneliUniqueId);
1219
1220 unsigned int flags = EPG_TAG_FLAG_UNDEFINED;
1221
1222 // is recordable
1223 bool isRecordable = false;
1224
1225 if (tagEntry.HasMember("recordingForbidden"))
1226 {
1227 isRecordable = !tagEntry["recordingForbidden"].GetBool();
1228 }
1229 else if(tagEntry.HasMember("restrictions") && tagEntry["restrictions"].HasMember("recordingForbidden"))
1230 {
1231 isRecordable = !tagEntry["restrictions"]["recordingForbidden"].GetBool();
1232 }
1233 kodi::Log(ADDON_LOG_DEBUG, "[epg-new] recordable: %i;", isRecordable);
1234 if (isRecordable)
1235 {
1236 flags |= EPG_TAG_FLAG_IS_RECORDABLE_WAIPU;
1237 flags |= EPG_TAG_FLAG_INSTANT_RESTART_ALLOWED_WAIPU;
1238 }
1239
1240 // set title
1241 if (tagEntry.HasMember("title") && !tagEntry["title"].IsNull())
1242 {
1243 tag.SetTitle(tagEntry["title"].GetString());
1244 kodi::Log(ADDON_LOG_DEBUG, "[epg] title: %s;", tagEntry["title"].GetString());
1245 }
1246 else if (tagEntry.HasMember("textContent") && tagEntry["textContent"].HasMember("title"))
1247 {
1248 tag.SetTitle(tagEntry["textContent"]["title"].GetString());
1249 kodi::Log(ADDON_LOG_DEBUG, "[epg] title: %s;", tagEntry["textContent"]["title"].GetString());
1250 }
1251
1252 // SetOriginalTitle
1253 if (tagEntry.HasMember("textContent") && tagEntry["textContent"].HasMember("titleOriginal"))
1254 {
1255 tag.SetOriginalTitle(tagEntry["textContent"]["titleOriginal"].GetString());
1256 }
1257
1258 // set startTime
1259 const std::string entryStartTime = tagEntry["startTime"].GetString();
1260 tag.SetStartTime(Utils::StringToTime(entryStartTime));
1261
1262 // set endTime
1263 const std::string entryEndTime = tagEntry["stopTime"].GetString();
1264 tag.SetEndTime(Utils::StringToTime(entryEndTime));
1265
1266 // set SetSeriesLink
1267 // example: https://play.waipu.tv/programm/n24/1f2b25b5-0a39-5957-b411-3825326a3e54
1268 tag.SetSeriesLink("https://play.waipu.tv/programm/"+waipuChannelID+"/"+epg_id);
1269
1270 // epg preview image
1271 if (m_epg_show_preview_images && tagEntry.HasMember("previewImage"))
1272 {
1273 std::string tmp_img = tagEntry["previewImage"].GetString();
1274 tag.SetIconPath(tmp_img);
1275 kodi::Log(ADDON_LOG_DEBUG, "[epg] previewImage: %s;", tmp_img.c_str());
1276 } else if (m_epg_show_preview_images && tagEntry.HasMember("imageUrls") && tagEntry["imageUrls"].IsArray() && tagEntry["imageUrls"].Size() > 0)
1277 {
1278 std::string tmp_img = tagEntry["imageUrls"][0].GetString();
1279 tmp_img = std::regex_replace(tmp_img, std::regex("\\$\\{resolution\\}"), "320x180");
1280 tag.SetIconPath(tmp_img);
1281 kodi::Log(ADDON_LOG_DEBUG, "[epg] previewImage: %s;", tmp_img.c_str());
1282 }
1283
1284
1285
1286 if (tagEntry.HasMember("seriesId") && !tagEntry["seriesId"].IsNull())
1287 {
1288 flags |= EPG_TAG_FLAG_IS_SERIES;
1289 tag.SetSeriesNumber(EPG_TAG_INVALID_SERIES_EPISODE);
1290 } else if (tagEntry.HasMember("series") && tagEntry["series"].HasMember("id"))
1291 {
1292 flags |= EPG_TAG_FLAG_IS_SERIES;
1293 tag.SetSeriesNumber(EPG_TAG_INVALID_SERIES_EPISODE);
1294 }
1295
1296 // season & episode
1297 if (tagEntry.HasMember("series") && tagEntry["series"].HasMember("seasonNumber") && tagEntry["series"].HasMember("episodeNumber"))
1298 {
1299 tag.SetSeriesNumber(Utils::StringToInt(tagEntry["series"]["seasonNumber"].GetString(), 1));
1300 tag.SetEpisodeNumber(Utils::StringToInt(tagEntry["series"]["episodeNumber"].GetString(), 1));
1301 }
1302
1303 // episodeName
1304 if (tagEntry.HasMember("episodeTitle") && !tagEntry["episodeTitle"].IsNull())
1305 {
1306 tag.SetEpisodeName(tagEntry["episodeTitle"].GetString());
1307 }else if (tagEntry.HasMember("series") && tagEntry["series"].HasMember("episodeTitle"))
1308 {
1309 tag.SetEpisodeName(tagEntry["series"]["episodeTitle"].GetString());
1310 }
1311
1312 // description
1313 if (tagEntry.HasMember("textContent") && tagEntry["textContent"].HasMember("descLong"))
1314 {
1315 tag.SetPlot(tagEntry["textContent"]["descLong"].GetString());
1316 }
1317
1318 // cast
1319 if (tagEntry.HasMember("production") && tagEntry["production"].HasMember("castMembers") && tagEntry["production"]["castMembers"].IsArray())
1320 {
1321 std::string castStr = "";
1322 for (const auto& castEntry : tagEntry["production"]["castMembers"].GetArray())
1323 {
1324 if (castEntry.HasMember("name") && castEntry.HasMember("role"))
1325 {
1326 castStr += std::string(castEntry["name"].GetString()) + " (" + std::string(castEntry["role"].GetString()) + ") ";
1327 }
1328 }
1329 kodi::Log(ADDON_LOG_DEBUG, "[epg] SetCast: %s;", castStr.c_str());
1330 tag.SetCast(castStr);
1331 }
1332
1333 // year
1334 if (tagEntry.HasMember("production") && tagEntry["production"].HasMember("year"))
1335 {
1336 tag.SetYear(Utils::StringToInt(tagEntry["production"]["year"].GetString(), 1970));
1337 }
1338
1339 // genre
1340 std::string genreStr = "";
1341 if (tagEntry.HasMember("genre") && !tagEntry["genre"].IsNull())
1342 {
1343 genreStr = tagEntry["genre"].GetString();
1344 }
1345 else if (tagEntry.HasMember("contentMeta") && tagEntry["contentMeta"].HasMember("mainGenre"))
1346 {
1347 genreStr = tagEntry["contentMeta"]["mainGenre"].GetString();
1348 }
1349
1350 if (!genreStr.empty())
1351 {
1352 int genre = m_categories.Category(genreStr);
1353 if (genre)
1354 {
1355 tag.SetGenreSubType(genre & 0x0F);
1356 tag.SetGenreType(genre & 0xF0);
1357 }
1358 else
1359 {
1360 tag.SetGenreType(EPG_GENRE_USE_STRING);
1361 tag.SetGenreSubType(0); /* not supported */
1362 tag.SetGenreDescription(genreStr);
1363 }
1364 }
1365
1366 if (reSchedule)
1367 {
1368 EPGQueueTask task;
1369 task.epgid = epg_id;
1370 task.waipuChannelID = waipuChannelID;
1371 task.kodiChannelID = kodiChanneliUniqueId;
1372
1373 m_queue_epgtag_tasks.push(task);
1374 }
1375
1376 tag.SetFlags(flags);
1377 return tag;
1378 }
1379
1380 PVR_ERROR WaipuData::GetEPGForChannel(int channelUid,
1381 time_t start,
1382 time_t end,
1383 kodi::addon::PVREPGTagsResultSet& results)
1384 {
1385 if (!IsConnected())
1386 return PVR_ERROR_SERVER_ERROR;
1387
1388 LoadChannelData();
1389
1390 const int grid_align_hours = 4; // align 4h
1391
1392 for (const auto& channel : m_channels)
1393 {
1394 if (channel.iUniqueId != channelUid)
1395 continue;
1396
1397 std::string channelid = channel.waipuID;
1398
1399 std::transform(channelid.begin(), channelid.end(), channelid.begin(), ::tolower);
1400
1401 kodi::Log(ADDON_LOG_DEBUG, "[epg-new] channel: %s", channelid.c_str());
1402
1403 int limit = 32;
1404 char startTimeBuf[30];
1405 rapidjson::Document epgDoc;
1406
1407 while (start < end)
1408 {
1409 limit--;
1410
1411 struct tm* tm = std::gmtime(&start);
1412 tm->tm_hour -= tm->tm_hour % grid_align_hours; // align to grid window
1413 kodi::Log(ADDON_LOG_DEBUG, "[epg-new] tm %d", tm->tm_hour);
1414
1415
1416 // 2024-05-17T17:00:00.000Z
1417 strftime(startTimeBuf, 30, "%Y-%m-%dT%H:00:00.000Z", tm);
1418
1419 std::string jsonEpg =
1420 HttpGet("https://epg-cache.waipu.tv/api/grid/" + channelid + "/" + startTimeBuf);
1421 kodi::Log(ADDON_LOG_DEBUG, "[epg-new] %s", jsonEpg.c_str());
1422 if (jsonEpg.empty())
1423 {
1424 kodi::Log(ADDON_LOG_ERROR, "[epg-new] empty server response");
1425 return PVR_ERROR_SERVER_ERROR;
1426 }
1427 jsonEpg = "{\"result\": " + jsonEpg + "}";
1428
1429
1430 epgDoc.ParseInsitu<rapidjson::kParseInsituFlag>(&jsonEpg[0]);
1431 if (epgDoc.HasParseError())
1432 {
1433 kodi::Log(ADDON_LOG_ERROR, "[GetEPG] ERROR: error while parsing json");
1434 return PVR_ERROR_SERVER_ERROR;
1435 }
1436
1437 kodi::Log(ADDON_LOG_DEBUG, "[epg-new] size: %i;", epgDoc["result"].Size());
1438
1439 for (const auto& epgData : epgDoc["result"].GetArray())
1440 {
1441 // we limit epg details fetching to channel.isFavorite, because it takes a lot of time
1442 results.Add(ParseEPGTagEntry(epgData, channel.iUniqueId, channelid, channel.isFavorite));
1443 }
1444 start = start + grid_align_hours * 60 * 60;
1445 if (limit < 1)
1446 break;
1447 }
1448 }
1449 return PVR_ERROR_NO_ERROR;
1450 }
1451
1452 PVR_ERROR WaipuData::IsEPGTagRecordable(const kodi::addon::PVREPGTag& tag, bool& isRecordable)
1453 {
1454 LoadChannelData();
1455 if (m_account_hours_recording == 0)
1456 {
1457 // recording option not available
1458 isRecordable = false;
1459 return PVR_ERROR_NO_ERROR;
1460 }
1461
1462 time_t current_time;
1463 time(&current_time);
1464 if (tag.GetEndTime() < current_time)
1465 {
1466 // if tag is in past, no recording is possible
1467 isRecordable = false;
1468 return PVR_ERROR_NO_ERROR;
1469 }
1470
1471 isRecordable = (tag.GetFlags() & EPG_TAG_FLAG_IS_RECORDABLE_WAIPU);
1472 return PVR_ERROR_NO_ERROR;
1473 }
1474
1475 PVR_ERROR WaipuData::IsEPGTagPlayable(const kodi::addon::PVREPGTag& tag, bool& isPlayable)
1476 {
1477 LoadChannelData();
1478 isPlayable = false;
1479
1480 // check if channel is onDemand and allows playback
1481 for (const auto& channel : m_channels)
1482 {
1483 if (channel.iUniqueId != tag.GetUniqueChannelId())
1484 continue;
1485 isPlayable = channel.tvfuse;
1486 if (isPlayable)
1487 {
1488 return PVR_ERROR_NO_ERROR;
1489 }
1490 }
1491
1492 // check if program is running and replay allowed
1493 auto current_time = time(NULL);
1494 if (m_account_replay_allowed && current_time > tag.GetStartTime() &&
1495 (current_time < tag.GetEndTime() || current_time - 60 * 60 < tag.GetStartTime()))
1496 {
1497 isPlayable = (tag.GetFlags() & EPG_TAG_FLAG_INSTANT_RESTART_ALLOWED_WAIPU);
1498 }
1499
1500 return PVR_ERROR_NO_ERROR;
1501 }
1502
1503 std::string WaipuData::GetEPGTagStreamURL(const kodi::addon::PVREPGTag& tag, const std::string& protocol)
1504 {
1505 // Get UUID from SeriesLink - workaround: better save UUID somewhere else
1506 const std::string series_link = tag.GetSeriesLink();
1507 if (series_link.empty())
1508 return "";
1509 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] Series Link: %s", series_link.c_str());
1510 std::vector<std::string> urlsplit;
1511 urlsplit = kodi::tools::StringUtils::Split(series_link, "/");
1512 const std::string programId = urlsplit.back();
1513 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] ProgramId: %s", programId.c_str());
1514
1515 // https://epg-cache.waipu.tv/api/programs/ee05ce19-1b98-53c4-a4eb-2c9d912bb0b6
1516 std::string epgJSON = HttpGet("https://epg-cache.waipu.tv/api/programs/"+programId);
1517
1518 rapidjson::Document epgDoc;
1519 epgDoc.Parse(epgJSON.c_str());
1520 if (epgDoc.HasParseError())
1521 {
1522 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] error parse JSON %s", epgJSON.c_str());
1523 return "";
1524 }
1525 if (epgDoc.HasMember("newTvMeta") && epgDoc["newTvMeta"].HasMember("source"))
1526 {
1527 const std::string sourceURL = epgDoc["newTvMeta"]["source"].GetString();
1528 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] sourceURL %s", sourceURL.c_str());
1529 std::string tunerJSON = HttpGet(sourceURL);
1530
1531 rapidjson::Document tunerDoc;
1532 tunerDoc.Parse(tunerJSON.c_str());
1533 if (tunerDoc.HasParseError())
1534 {
1535 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] error parse JSON %s", epgJSON.c_str());
1536 return "";
1537 }
1538 if (tunerDoc.HasMember("player")){
1539 if ((protocol == "hls" || protocol == "HLS") && tunerDoc["player"].HasMember("hls"))
1540 return tunerDoc["player"]["hls"].GetString();
1541 if (tunerDoc["player"].HasMember("mpd"))
1542 return tunerDoc["player"]["mpd"].GetString();
1543 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] No valid stream found");
1544 }
1545 }
1546 kodi::Log(ADDON_LOG_DEBUG, "[play epg tag] missing ['newTvMeta']['source'] in JSON %s", epgJSON.c_str());
1547 return "";
1548 }
1549
1550 PVR_ERROR WaipuData::GetEPGTagStreamProperties(
1551 const kodi::addon::PVREPGTag& tag, std::vector<kodi::addon::PVRStreamProperty>& properties)
1552 {
1553 kodi::Log(ADDON_LOG_DEBUG, "[EPG TAG] play it...");
1554 LoadChannelData();
1555
1556 std::string protocol = m_protocol;
1557 if (protocol == "auto")
1558 protocol = "dash"; //fallback to dash
1559
1560 std::string strUrl = "";
1561
1562 const auto& thisChannel =
1563 std::find_if(m_channels.begin(), m_channels.end(),
1564 [tag](const auto& v) { return v.iUniqueId == tag.GetUniqueChannelId(); });
1565 // check if VoD Channel and we can obtain newMediaURL
1566 if (thisChannel != m_channels.end() && (*thisChannel).tvfuse)
1567 {
1568 strUrl = GetEPGTagStreamURL(tag, protocol);
1569 }
1570
1571 if (strUrl.empty())
1572 {
1573 // fallback: instant replay
1574 strUrl = GetChannelStreamURL(tag.GetUniqueChannelId(), protocol, std::to_string(tag.GetStartTime()));
1575 if (strUrl.empty())
1576 {
1577 return PVR_ERROR_FAILED;
1578 }
1579 }
1580
1581 SetStreamProperties(properties, strUrl, true, true, protocol);
1582
1583 return PVR_ERROR_NO_ERROR;
1584 }
1585
1586 PVR_ERROR WaipuData::GetRecordingsAmount(bool deleted, int& amount)
1587 {
1588 if (!IsConnected())
1589 return PVR_ERROR_SERVER_ERROR;
1590
1591 amount = m_recordings_count;
1592 return PVR_ERROR_NO_ERROR;
1593 }
1594
1595 kodi::addon::PVRRecording WaipuData::ParseRecordingEntry(const rapidjson::Value& recordingEntry)
1596 {
1597
1598 kodi::addon::PVRRecording tag;
1599 bool isSeries = false;
1600
1601 tag.SetIsDeleted(false);
1602 std::string recordingId = recordingEntry["id"].GetString();
1603 tag.SetRecordingId(recordingId);
1604 if (recordingEntry.HasMember("fullyWatchedCount"))
1605 tag.SetPlayCount(recordingEntry["fullyWatchedCount"].GetInt());
1606
1607 const std::string rec_title = recordingEntry["title"].GetString();
1608 tag.SetTitle(rec_title);
1609
1610 if (recordingEntry.HasMember("previewImage") && !recordingEntry["previewImage"].IsNull())
1611 {
1612 std::string rec_img = recordingEntry["previewImage"].GetString();
1613 rec_img = std::regex_replace(rec_img, std::regex("\\$\\{resolution\\}"), "320x180");
1614 tag.SetIconPath(rec_img);
1615 tag.SetThumbnailPath(rec_img);
1616 }
1617
1618 if (recordingEntry.HasMember("durationSeconds") && !recordingEntry["durationSeconds"].IsNull())
1619 tag.SetDuration(recordingEntry["durationSeconds"].GetInt());
1620
1621 if (recordingEntry.HasMember("positionPercentage") &&
1622 !recordingEntry["positionPercentage"].IsNull() &&
1623 recordingEntry["positionPercentage"].IsInt())
1624 {
1625 int positionPercentage = recordingEntry["positionPercentage"].GetInt();
1626 int position = tag.GetDuration() * positionPercentage / 100;
1627 tag.SetLastPlayedPosition(position);
1628 }
1629
1630 if (recordingEntry.HasMember("recordingStartTime") &&
1631 !recordingEntry["recordingStartTime"].IsNull())
1632 tag.SetRecordingTime(Utils::StringToTime(recordingEntry["recordingStartTime"].GetString()));
1633
1634 if (recordingEntry.HasMember("genreDisplayName") && !recordingEntry["genreDisplayName"].IsNull())
1635 {
1636 std::string genreStr = recordingEntry["genreDisplayName"].GetString();
1637 int genre = m_categories.Category(genreStr);
1638 if (genre)
1639 {
1640 tag.SetGenreSubType(genre & 0x0F);
1641 tag.SetGenreType(genre & 0xF0);
1642 }
1643 else
1644 {
1645 tag.SetGenreType(EPG_GENRE_USE_STRING);
1646 tag.SetGenreSubType(0); /* not supported */
1647 tag.SetGenreDescription(genreStr);
1648 }
1649 }
1650
1651 if (recordingEntry.HasMember("episodeTitle") && !recordingEntry["episodeTitle"].IsNull())
1652 {
1653 tag.SetEpisodeName(recordingEntry["episodeTitle"].GetString());
1654 isSeries = true;
1655 }
1656
1657 if (recordingEntry.HasMember("season") && !recordingEntry["season"].IsNull())
1658 tag.SetSeriesNumber(Utils::StringToInt(recordingEntry["season"].GetString(),
1659 PVR_RECORDING_INVALID_SERIES_EPISODE));
1660
1661 if (recordingEntry.HasMember("episode") && !recordingEntry["episode"].IsNull())
1662 tag.SetEpisodeNumber(Utils::StringToInt(recordingEntry["episode"].GetString(),
1663 PVR_RECORDING_INVALID_SERIES_EPISODE));
1664
1665 // epg mapping
1666 if (recordingEntry.HasMember("programId") && !recordingEntry["programId"].IsNull())
1667 {
1668 std::string epg_id = recordingEntry["programId"].GetString();
1669 int dirtyID = Utils::GetIDDirty(epg_id);
1670 tag.SetEPGEventId(dirtyID);
1671 }
1672
1673 // not every series is correctly tagged - lets assume recording groups are also series
1674 if (recordingEntry.HasMember("recordingGroup"))
1675 isSeries = true;
1676
1677 if (isSeries)
1678 {
1679 tag.SetFlags(PVR_RECORDING_FLAG_IS_SERIES);
1680 tag.SetDirectory(rec_title);
1681 }
1682
1683 // Additional program details like year or plot are on available in an additional details request. Maybe we should provide this as settings option?
1684 if (kodi::addon::GetSettingBoolean("recordings_additional_infos", false))
1685 {
1686
1687 std::string json = HttpGet("https://recording.waipu.tv/api/recordings/" + recordingId,
1688 {{"Accept", "application/vnd.waipu.recording-v4+json"}});
1689 kodi::Log(ADDON_LOG_DEBUG, "[recordings] %s", json.c_str());
1690
1691 rapidjson::Document doc;
1692 doc.Parse(json.c_str());
1693 if (!doc.HasParseError())
1694 {
1695 if (doc.HasMember("programDetails"))
1696 {
1697 if (doc["programDetails"].HasMember("textContent"))
1698 {
1699 if (doc["programDetails"]["textContent"].HasMember("descLong"))
1700 {
1701 std::string descr = doc["programDetails"]["textContent"]["descLong"].GetString();
1702 tag.SetPlot(descr);
1703 tag.SetPlotOutline(descr);
1704 }
1705 else if (doc["programDetails"]["textContent"].HasMember("descShort"))
1706 {
1707 std::string descr = doc["programDetails"]["textContent"]["descShort"].GetString();
1708 tag.SetPlot(descr);
1709 tag.SetPlotOutline(descr);
1710 }
1711 }
1712 if (doc["programDetails"].HasMember("production"))
1713 {
1714 if (doc["programDetails"]["production"].HasMember("year"))
1715 {
1716 std::string year = doc["programDetails"]["production"]["year"].GetString();
1717 tag.SetYear(Utils::StringToInt(year, 1970));
1718 }
1719 }
1720 }
1721 }
1722 }
1723 return tag;
1724 }
1725
1726 PVR_ERROR WaipuData::GetRecordings(bool deleted, kodi::addon::PVRRecordingsResultSet& results)
1727 {
1728 if (!IsConnected())
1729 return PVR_ERROR_SERVER_ERROR;
1730
1731 m_active_recordings_update = true;
1732
1733 {
1734 std::string recordingGroupsJSON =
1735 HttpGet("https://recording.waipu.tv/api/recordings",
1736 {{"Accept", "application/vnd.waipu.recordings-v4+json"}});
1737 kodi::Log(ADDON_LOG_DEBUG, "[recordingGroupsJSON] %s", recordingGroupsJSON.c_str());
1738
1739 rapidjson::Document recordingGroupsDoc;
1740 recordingGroupsDoc.Parse(recordingGroupsJSON.c_str());
1741 if (recordingGroupsDoc.HasParseError())
1742 {
1743 kodi::Log(ADDON_LOG_ERROR, "[GetRecordings] ERROR: error while parsing recordingGroupsJSON");
1744 return PVR_ERROR_SERVER_ERROR;
1745 }
1746 kodi::Log(ADDON_LOG_DEBUG, "[recordings] getGroups");
1747 std::set<int> recordingGroups;
1748 int recordings_count = 0;
1749
1750 for (const auto& recordingEntry : recordingGroupsDoc.GetArray())
1751 {
1752 // skip not FINISHED entries
1753 std::string status = recordingEntry["status"].GetString();
1754
1755 if (recordingEntry.HasMember("recordingGroup") && recordingEntry["recordingGroup"].IsInt())
1756 {
1757 int recordingGroup = recordingEntry["recordingGroup"].GetInt();
1758 kodi::Log(ADDON_LOG_DEBUG, "[%s] found group: %i;", __FUNCTION__, recordingGroup);
1759 recordingGroups.insert(recordingGroup);
1760 }
1761 else if (status == "FINISHED" || status == "RECORDING")
1762 {
1763 if (recordingEntry.HasMember("locked") && recordingEntry["locked"].GetBool())
1764 {
1765 kodi::Log(ADDON_LOG_DEBUG, "[%s] Skip locked recording", __FUNCTION__);
1766 continue;
1767 }
1768 recordings_count++;
1769 results.Add(ParseRecordingEntry(recordingEntry));
1770 }
1771 }
1772
1773 for (const int& recordingGroup : recordingGroups)
1774 {
1775 std::string json = HttpGet("https://recording.waipu.tv/api/recordings?recordingGroup=" +
1776 std::to_string(recordingGroup),
1777 {{"Accept", "application/vnd.waipu.recordings-v4+json"}});
1778 kodi::Log(ADDON_LOG_DEBUG, "[recordings] %s", json.c_str());
1779
1780 rapidjson::Document doc;
1781 doc.Parse(json.c_str());
1782 if (doc.HasParseError())
1783 {
1784 kodi::Log(ADDON_LOG_ERROR, "[GetRecordings] ERROR: error while parsing json");
1785 return PVR_ERROR_SERVER_ERROR;
1786 }
1787 kodi::Log(ADDON_LOG_DEBUG, "[recordings] iterate entries");
1788 kodi::Log(ADDON_LOG_DEBUG, "[recordings] size: %i;", doc.Size());
1789
1790 for (const rapidjson::Value& recordingEntry : doc.GetArray())
1791 {
1792 // skip not FINISHED entries
1793 std::string status = recordingEntry["status"].GetString();
1794 if (status != "FINISHED" && status != "RECORDING")
1795 continue;
1796
1797 if (recordingEntry.HasMember("locked") && recordingEntry["locked"].GetBool())
1798 {
1799 kodi::Log(ADDON_LOG_DEBUG, "[%s] Skip locked recording", __FUNCTION__);
1800 continue;
1801 }
1802 recordings_count++;
1803 results.Add(ParseRecordingEntry(recordingEntry));
1804 }
1805 }
1806 m_recordings_count = recordings_count;
1807 }
1808
1809 {
1810 std::string json = HttpGet("https://recording.waipu.tv/api/recordings/summary",
1811 {{"Accept", "application/vnd.waipu.recording-summary-v2+json"}});
1812 kodi::Log(ADDON_LOG_DEBUG, "[recordings summary] %s", json.c_str());
1813 rapidjson::Document doc;
1814 doc.Parse(json.c_str());
1815 if (!doc.HasParseError() && doc.HasMember("finishedRecordingsSeconds"))
1816 {
1817 m_finishedRecordingsSeconds = doc["finishedRecordingsSeconds"].GetInt();
1818 }
1819 }
1820
1821 m_active_recordings_update = false;
1822
1823 return PVR_ERROR_NO_ERROR;
1824 }
1825
1826 std::string WaipuData::GetRecordingURL(const kodi::addon::PVRRecording& recording,
1827 const std::string& protocol)
1828 {
1829 std::string recording_id = recording.GetRecordingId();
1830 kodi::Log(ADDON_LOG_DEBUG, "play recording -> %s", recording_id.c_str());
1831
1832 std::string rec_resp = HttpGet("https://recording.waipu.tv/api/recordings/" + recording_id + "/streamingdetails");
1833 kodi::Log(ADDON_LOG_DEBUG, "recording resp -> %s", rec_resp.c_str());
1834
1835 rapidjson::Document recordingDoc;
1836 recordingDoc.Parse(rec_resp.c_str());
1837 if (recordingDoc.HasParseError())
1838 {
1839 kodi::Log(ADDON_LOG_ERROR, "[getRecordingURL] ERROR: error while parsing json");
1840 return "";
1841 }
1842 kodi::Log(ADDON_LOG_DEBUG, "[recording] streams");
1843 // check if streams there
1844 if (!recordingDoc.HasMember("streams"))
1845 {
1846 kodi::Log(ADDON_LOG_ERROR, "[getRecordingURL] ERROR: missing streams");
1847 return "";
1848 }
1849
1850 kodi::Log(ADDON_LOG_DEBUG, "[recordings] size: %i;",
1851 recordingDoc["streams"].Size());
1852
1853 std::string protocol_fix = protocol == "dash" ? "MPEG_DASH" : "HLS";
1854
1855 for (const auto& stream : recordingDoc["streams"].GetArray())
1856 {
1857 std::string current_protocol = stream["protocol"].GetString();
1858 kodi::Log(ADDON_LOG_DEBUG, "[stream] protocol: %s;", current_protocol.c_str());
1859 if (current_protocol == protocol_fix)
1860 {
1861 std::string href = stream["href"].GetString();
1862 kodi::Log(ADDON_LOG_DEBUG, "[stream] selected href: %s;", href.c_str());
1863 return href;
1864 }
1865 }
1866 return "";
1867 }
1868
1869 PVR_ERROR WaipuData::DeleteRecording(const kodi::addon::PVRRecording& recording)
1870 {
1871 if (!IsConnected())
1872 return PVR_ERROR_FAILED;
1873
1874 std::string recording_id = recording.GetRecordingId();
1875 // {"ids":["1310978347"]}
1876 std::string request_data = "{\"ids\":[\"" + recording_id + "\"]}";
1877 kodi::Log(ADDON_LOG_DEBUG, "[delete recording] req: %s;", request_data.c_str());
1878 std::string deleted =
1879 HttpDelete("https://recording.waipu.tv/api/recordings", request_data,
1880 {{"Content-Type", "application/vnd.waipu.recording-ids-v4+json"}});
1881 kodi::Log(ADDON_LOG_DEBUG, "[delete recording] response: %s;", deleted.c_str());
1882 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
1883 return PVR_ERROR_NO_ERROR;
1884 }
1885
1886 PVR_ERROR WaipuData::GetRecordingStreamProperties(
1887 const kodi::addon::PVRRecording& recording,
1888 std::vector<kodi::addon::PVRStreamProperty>& properties)
1889 {
1890 kodi::Log(ADDON_LOG_DEBUG, "[recordings] play it...");
1891 LoadChannelData();
1892
1893 std::string protocol = m_protocol;
1894 if (protocol == "auto")
1895 protocol = "dash"; //fallback to dash
1896
1897 std::string strUrl = GetRecordingURL(recording, protocol);
1898 if (strUrl.empty())
1899 {
1900 return PVR_ERROR_FAILED;
1901 }
1902
1903 SetStreamProperties(properties, strUrl, true, true, protocol);
1904
1905 return PVR_ERROR_NO_ERROR;
1906 }
1907
1908 void WaipuData::AddTimerType(std::vector<kodi::addon::PVRTimerType>& types, int id, int attributes)
1909 {
1910 kodi::addon::PVRTimerType type;
1911 type.SetId(static_cast<unsigned int>(id));
1912 type.SetAttributes(static_cast<unsigned int>(attributes));
1913 types.emplace_back(type);
1914 }
1915
1916 PVR_ERROR WaipuData::GetTimerTypes(std::vector<kodi::addon::PVRTimerType>& types)
1917 {
1918 AddTimerType(types, 1, PVR_TIMER_TYPE_REQUIRES_EPG_TAG_ON_CREATE);
1919 AddTimerType(types, 2,
1920 PVR_TIMER_TYPE_REQUIRES_EPG_SERIES_ON_CREATE | PVR_TIMER_TYPE_IS_REPEATING);
1921
1922 return PVR_ERROR_NO_ERROR;
1923 }
1924
1925 PVR_ERROR WaipuData::GetTimersAmount(int& amount)
1926 {
1927 if (!IsConnected())
1928 return PVR_ERROR_SERVER_ERROR;
1929
1930 amount = m_timers_count;
1931 return PVR_ERROR_NO_ERROR;
1932 }
1933
1934 PVR_ERROR WaipuData::GetTimers(kodi::addon::PVRTimersResultSet& results)
1935 {
1936 if (!IsConnected())
1937 return PVR_ERROR_SERVER_ERROR;
1938
1939 LoadChannelData();
1940
1941 std::string jsonRecordings = HttpGet("https://recording.waipu.tv/api/recordings",
1942 {{"Accept", "application/vnd.waipu.recordings-v4+json"}});
1943 kodi::Log(ADDON_LOG_DEBUG, "[Timers] %s", jsonRecordings.c_str());
1944
1945 jsonRecordings = "{\"result\": " + jsonRecordings + "}";
1946
1947 rapidjson::Document timersDoc;
1948 timersDoc.Parse(jsonRecordings.c_str());
1949 if (timersDoc.HasParseError())
1950 {
1951 kodi::Log(ADDON_LOG_ERROR, "[timers] ERROR: error while parsing json");
1952 return PVR_ERROR_SERVER_ERROR;
1953 }
1954 kodi::Log(ADDON_LOG_DEBUG, "[timers] iterate entries");
1955 kodi::Log(ADDON_LOG_DEBUG, "[timers] size: %i;", timersDoc["result"].Size());
1956
1957 int recordings_count = 0;
1958 int timers_count = 0;
1959
1960 std::vector<int> timerGroups;
1961
1962 for (const auto& timer : timersDoc["result"].GetArray())
1963 {
1964 // skip if missing epgdata
1965 if (!timer.HasMember("status") || !timer.HasMember("stationId") || !timer.HasMember("title"))
1966 {
1967 kodi::Log(ADDON_LOG_DEBUG, "[timers] Skip due to missing status/station/title");
1968 continue;
1969 }
1970
1971 // skip not FINISHED entries
1972 std::string status = timer["status"].GetString();
1973 if (status != "SCHEDULED" && status != "RECORDING")
1974 {
1975 ++recordings_count;
1976 continue;
1977 }
1978
1979 // new tag
1980 kodi::addon::PVRTimer tag;
1981 ++timers_count;
1982
1983 if (status == "SCHEDULED")
1984 {
1985 tag.SetState(PVR_TIMER_STATE_SCHEDULED);
1986 }
1987 else if (status == "RECORDING")
1988 {
1989 tag.SetState(PVR_TIMER_STATE_RECORDING);
1990 }
1991 tag.SetLifetime(0);
1992
1993
1994 // set recording title
1995 std::string rec_title = timer["title"].GetString();
1996 kodi::Log(ADDON_LOG_DEBUG, "[timers] Add: %s;", rec_title.c_str());
1997 tag.SetTitle(rec_title);
1998
1999 int tag_channel;
2000 // channelid
2001 if (timer.HasMember("stationId") && !timer["stationId"].IsNull())
2002 {
2003 std::string station_id = timer["stationId"].GetString();
2004
2005 // workaround: transform Station ID to uppercase, since old API (for recordings/timers) needs this
2006 std::transform(station_id.begin(), station_id.end(),
2007 station_id.begin(), ::toupper);
2008
2009 for (const auto& channel : m_channels)
2010 {
2011 if (channel.waipuID != station_id)
2012 continue;
2013 tag_channel = channel.iUniqueId;
2014 tag.SetClientChannelUid(tag_channel);
2015 break;
2016 }
2017 }
2018
2019 if (timer.HasMember("recordingGroup"))
2020 {
2021
2022 int group = timer["recordingGroup"].GetInt();
2023 tag.SetRecordingGroup(group);
2024 if (std::find(timerGroups.begin(), timerGroups.end(), group) == timerGroups.end())
2025 {
2026 // add group
2027 kodi::addon::PVRTimer tagGroup;
2028 tagGroup.SetTimerType(2);
2029 tagGroup.SetTitle(rec_title);
2030 tagGroup.SetClientIndex(group);
2031 tagGroup.SetClientChannelUid(tag_channel);
2032 tag.SetRecordingGroup(group);
2033 kodi::Log(ADDON_LOG_DEBUG, "[add timer group] group: %i;", group);
2034
2035 results.Add(tagGroup);
2036 timerGroups.emplace_back(group);
2037 }
2038 }
2039
2040 tag.SetTimerType(1);
2041
2042 // set recording id
2043 std::string rec_id = timer["id"].GetString();
2044 tag.SetClientIndex(Utils::StringToInt(rec_id, 0));
2045 tag.SetEPGUid(Utils::StringToInt(rec_id, 0));
2046
2047 // get recording time
2048 time_t epgStartTime = 0;
2049 if (timer.HasMember("epgStartTime") && !timer["epgStartTime"].IsNull())
2050 {
2051 epgStartTime = Utils::StringToTime(timer["epgStartTime"].GetString());
2052 tag.SetStartTime(epgStartTime);
2053 }
2054 if (epgStartTime > 0 && timer.HasMember("durationSeconds") && !timer["durationSeconds"].IsNull())
2055 {
2056 int durationSeconds = timer["durationSeconds"].GetInt();
2057 tag.SetEndTime(epgStartTime + durationSeconds);
2058 }
2059
2060 // get plot
2061 //if (epgData.HasMember("description") && !epgData["description"].IsNull())
2062 //{
2063 // std::string rec_plot = epgData["description"].GetString();
2064 // tag.SetSummary(rec_plot);
2065 //}
2066
2067 // epg mapping
2068 if (timer.HasMember("programId") && !timer["programId"].IsNull())
2069 {
2070 std::string epg_id = timer["programId"].GetString();
2071 int dirtyID = Utils::GetIDDirty(epg_id);
2072 tag.SetEPGUid(dirtyID);
2073 }
2074
2075 results.Add(tag);
2076 }
2077
2078 if (recordings_count != m_recordings_count && !m_active_recordings_update)
2079 {
2080 // we detected another amount of recordings.
2081 // tell kodi about it
2082 m_active_recordings_update = true;
2083 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
2084 }
2085 m_timers_count = timers_count;
2086
2087 return PVR_ERROR_NO_ERROR;
2088 }
2089
2090 PVR_ERROR WaipuData::DeleteTimer(const kodi::addon::PVRTimer& timer, bool forceDelete)
2091 {
2092 if (!IsConnected())
2093 return PVR_ERROR_FAILED;
2094
2095 if (timer.GetTimerType() == 1)
2096 {
2097 // single tag
2098 int timer_id = timer.GetClientIndex();
2099 std::string request_data = "{\"ids\":[\"" + std::to_string(timer_id) + "\"]}";
2100 kodi::Log(ADDON_LOG_DEBUG, "[delete single timer] req: %s;", request_data.c_str());
2101 std::string deleted =
2102 HttpDelete("https://recording.waipu.tv/api/recordings", request_data,
2103 {{"Content-Type", "application/vnd.waipu.recording-ids-v4+json"}});
2104 kodi::Log(ADDON_LOG_DEBUG, "[delete single timer] response: %s;", deleted.c_str());
2105 kodi::QueueNotification(QUEUE_INFO, "Recording", "Recording Deleted");
2106 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
2107 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
2108 return PVR_ERROR_NO_ERROR;
2109 }
2110 else
2111 {
2112 // delete record series
2113 int groupID = timer.GetClientIndex();
2114 std::string request_data = "{\"serialRecordings\":[{\"id\":" + std::to_string(groupID) +
2115 ",\"deleteFutureRecordings\":true,\"deleteFinishedRecordings\":"
2116 "false,\"deleteRunningRecordings\":false}]}";
2117 kodi::Log(ADDON_LOG_DEBUG, "[delete multi timer] req (group: %i): %s;", groupID,
2118 request_data.c_str());
2119 std::string deleted =
2120 HttpPost("https://recording-scheduler.waipu.tv/api/delete-requests", request_data,
2121 {{"Content-Type",
2122 "application/vnd.waipu.recording-scheduler-delete-serial-recordings-v1+json"}});
2123 kodi::Log(ADDON_LOG_DEBUG, "[delete multi timer] response: %s;", deleted.c_str());
2124 kodi::QueueNotification(QUEUE_INFO, "Recording", "Rule Deleted");
2125 kodi::addon::CInstancePVRClient::TriggerRecordingUpdate();
2126 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
2127 return PVR_ERROR_NO_ERROR;
2128 }
2129 }
2130
2131 PVR_ERROR WaipuData::AddTimer(const kodi::addon::PVRTimer& timer)
2132 {
2133 // we currently only support epg based
2134 if (timer.GetEPGUid() <= EPG_TAG_INVALID_UID)
2135 return PVR_ERROR_REJECTED;
2136
2137 if (!IsConnected())
2138 return PVR_ERROR_FAILED;
2139
2140 // Get UUID from SeriesLink - workaround: better save UUID somewhere else
2141 const std::string series_link = timer.GetSeriesLink().c_str();
2142 kodi::Log(ADDON_LOG_DEBUG, "[add timer] Series Link: %s", series_link.c_str());
2143 std::vector<std::string> urlsplit;
2144 urlsplit = kodi::tools::StringUtils::Split(series_link, "/");
2145 const std::string programId = urlsplit.back();
2146 kodi::Log(ADDON_LOG_DEBUG, "[add timer] ProgramId: %s", programId.c_str());
2147
2148 std::string seriesID = "";
2149 std::string stationID = "";
2150 std::string recordingTitle = "";
2151 bool seriesRecording = false;
2152
2153 std::string jsonTimer = HttpGet("https://epg-cache.waipu.tv/api/programs/"+programId);
2154
2155 rapidjson::Document timerDoc;
2156 timerDoc.Parse(jsonTimer.c_str());
2157 if (!timerDoc.HasParseError())
2158 {
2159 if (timerDoc.HasMember("series") &&
2160 timerDoc["series"].HasMember("id") &&
2161 timerDoc["series"]["id"].IsString())
2162 {
2163 seriesID = timerDoc["series"]["id"].GetString();
2164 }
2165
2166 if (timerDoc.HasMember("stationId") &&
2167 timerDoc["stationId"].IsString())
2168 {
2169 stationID = timerDoc["stationId"].GetString();
2170 // we get the statioID in lower, but need uppercase for recording
2171 std::transform(stationID.begin(), stationID.end(),stationID.begin(), ::toupper);
2172 }
2173
2174 if (timerDoc.HasMember("textContent") &&
2175 timerDoc["textContent"].HasMember("title") &&
2176 timerDoc["textContent"]["title"].IsString())
2177 {
2178 recordingTitle = timerDoc["textContent"]["title"].GetString();
2179 }
2180 }
2181
2182 // it is a tv show - ask user whether to record all episodes
2183 if (!seriesID.empty() && !stationID.empty() && !recordingTitle.empty())
2184 {
2185 seriesRecording = kodi::gui::dialogs::YesNo::ShowAndGetInput(
2186 kodi::addon::GetLocalizedString(30058), // header
2187 kodi::addon::GetLocalizedString(30059),
2188 "",
2189 "",
2190 kodi::addon::GetLocalizedString(30060), // false label
2191 kodi::addon::GetLocalizedString(30061)); // true label
2192 // -1 == canceled
2193 kodi::Log(ADDON_LOG_DEBUG, "[add timer] Selcted recording type: %d (1 == all episodes)", seriesRecording);
2194 }
2195
2196 if (seriesRecording)
2197 {
2198 // series recording
2199 kodi::Log(ADDON_LOG_DEBUG, "[add timer] Record all episodes/series;");
2200 const std::string postData = "{\"channel\":\"" + stationID + "\",\"title\":\""+recordingTitle+"\",\"seriesId\":\""+seriesID+"\"}";
2201 const std::string recordResp =
2202 HttpPost("https://recording-scheduler.waipu.tv/api/serials", postData,
2203 {{"Content-Type", "application/vnd.waipu.recording-scheduler-serials-v1+json"}});
2204 kodi::Log(ADDON_LOG_DEBUG, "[add timer] record all episodes response: %s;", recordResp.c_str());
2205 }else{
2206 // record single element
2207 kodi::Log(ADDON_LOG_DEBUG, "[add timer] Record single tag;");
2208 // {"programId":"_1051966761","channelId":"PRO7","startTime":"2019-02-03T18:05:00.000Z","stopTime":"2019-02-03T19:15:00.000Z"}
2209 const std::string postData = "{\"programId\":\"" + programId + "\"}";
2210 const std::string recordResp =
2211 HttpPost("https://recording.waipu.tv/api/recordings", postData,
2212 {{"Content-Type", "application/vnd.waipu.recording-create-v4+json"}});
2213 kodi::Log(ADDON_LOG_DEBUG, "[add timer] single response: %s;", recordResp.c_str());
2214 }
2215 kodi::QueueNotification(QUEUE_INFO, "Recording", "Recording Created");
2216 std::this_thread::sleep_for(std::chrono::milliseconds(200));
2217 kodi::addon::CInstancePVRClient::TriggerTimerUpdate();
2218
2219 return PVR_ERROR_NO_ERROR;
2220 }
2221
2222 WaipuData::~WaipuData()
2223 {
2224 m_loginThreadRunning = false;
2225 if (m_loginThread.joinable())
2226 m_loginThread.join();
2227
2228 m_EPGTaskThreadRunning = false;
2229 if (m_EPGTaskThread.joinable())
2230 m_EPGTaskThread.join();
2231 }
2232
2233 ADDON_STATUS WaipuData::Create()
2234 {
2235 kodi::Log(ADDON_LOG_DEBUG, "%s - Creating the waipu.tv PVR add-on", __FUNCTION__);
2236
2237 // set User-Agent
2238 std::string ua = kodi::network::GetUserAgent();
2239 // use our replace, since kodi utils replaces all occurrences
2240 WAIPU_USER_AGENT =
2241 Utils::Replace(ua, " ", std::string(" pvr.waipu/").append(STR(IPTV_VERSION)).append(" "));
2242
2243 ReadSettings();
2244
2245 if (m_provider == WAIPU_PROVIDER_WAIPU && (m_username.empty() || m_password.empty()))
2246 {
2247 kodi::QueueNotification(QUEUE_ERROR, "", kodi::addon::GetLocalizedString(30033));
2248 return ADDON_STATUS_NEED_SETTINGS;
2249 }
2250
2251 m_loginThreadRunning = true;
2252 m_loginThread = std::thread([&] { LoginThread(); });
2253
2254 m_EPGTaskThreadRunning = true;
2255 m_EPGTaskThread = std::thread([&] { EPGTaskThread(); });
2256
2257 kodi::addon::CInstancePVRClient::ConnectionStateChange("Initializing",
2258 PVR_CONNECTION_STATE_CONNECTING, "");
2259
2260 return ADDON_STATUS_OK;
2261 }
2262
2263 PVR_ERROR WaipuData::GetDriveSpace(uint64_t& total, uint64_t& used)
2264 {
2265 if (!IsConnected())
2266 return PVR_ERROR_SERVER_ERROR;
2267
2268 total = m_account_hours_recording * 1024l * 1024l;
2269 used = m_finishedRecordingsSeconds > 0 ? m_finishedRecordingsSeconds * 1024 * 1024 / 3600 : 0;
2270
2271 return PVR_ERROR_NO_ERROR;
2272 }
2273
2274 PVR_ERROR WaipuData::OnSystemWake()
2275 {
2276 m_accessToken = JWT();
2277 m_deviceCapabilitiesToken = JWT();
2278 m_nextLoginAttempt = 0;
2279 m_login_status = WAIPU_LOGIN_STATUS::UNKNOWN;
2280
2281 return PVR_ERROR_NO_ERROR;
2282 }
2283
2284 PVR_ERROR WaipuData::GetRecordingLastPlayedPosition(const kodi::addon::PVRRecording& recording,
2285 int& position)
2286 {
2287 if (!IsConnected())
2288 return PVR_ERROR_FAILED;
2289
2290 std::string responseJSON =
2291 HttpGet("https://stream-position.waipu.tv/api/stream-positions/" + recording.GetRecordingId(),
2292 {{"Content-Type", "application/json"}}, true);
2293
2294 // body: {"type":"stream-position/not-found","title":"Stream Position Not Found","status":404,"...
2295 if (responseJSON.find("\"type\":\"stream-position/not-found\"") != std::string::npos &&
2296 responseJSON.find("\"status\":404") != std::string::npos) {
2297 kodi::Log(ADDON_LOG_DEBUG, "%s - No StreamPosition stored on backend - start from beginning.",
2298 __FUNCTION__);
2299 position = 0;
2300 return PVR_ERROR_NO_ERROR;
2301 }
2302
2303 if (responseJSON.empty())
2304 {
2305 kodi::Log(ADDON_LOG_DEBUG, "%s - Empty StreamPosition retrieved - start from beginning.",
2306 __FUNCTION__);
2307 position = 0;
2308 return PVR_ERROR_NO_ERROR;
2309 }
2310
2311 kodi::Log(ADDON_LOG_DEBUG, "%s - Response: %s", __FUNCTION__, responseJSON.c_str());
2312
2313 rapidjson::Document recordingPosDoc;
2314 recordingPosDoc.Parse(responseJSON.c_str());
2315 if (recordingPosDoc.HasParseError())
2316 {
2317 kodi::Log(ADDON_LOG_ERROR, "[%s] ERROR: Parsing StreamPosition JSON", __FUNCTION__);
2318 return PVR_ERROR_SERVER_ERROR;
2319 }
2320 // {"streamId":"1036499352","position":5040,"changed":"2024-06-21T17:54:52.000+00:00"}
2321 if (recordingPosDoc.HasMember("position") && recordingPosDoc["position"].IsInt())
2322 position = recordingPosDoc["position"].GetInt();
2323
2324 return PVR_ERROR_NO_ERROR;
2325 }
2326
2327 PVR_ERROR WaipuData::SetRecordingLastPlayedPosition(const kodi::addon::PVRRecording& recording,
2328 int lastplayedposition)
2329 {
2330 if (!IsConnected())
2331 return PVR_ERROR_FAILED;
2332
2333 if (lastplayedposition == -1)
2334 lastplayedposition = 0;
2335
2336 std::string request_data = "{\"position\":" + std::to_string(lastplayedposition) + "}";
2337 std::string response = HttpRequest(
2338 "PUT", "https://stream-position.waipu.tv/api/stream-positions/" + recording.GetRecordingId(),
2339 request_data, {{"Content-Type", "application/vnd.waipu.stream-position-request.v1+json"}});
2340 kodi::Log(ADDON_LOG_DEBUG, "%s - Response: %s", __FUNCTION__, response.c_str());
2341
2342 return PVR_ERROR_NO_ERROR;
2343 }
2344
2345 ADDONCREATOR(WaipuData)