Debian Codegraph @

src/Data.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 <set>
28 #include <sstream>
29 #include <string>
30 #include <fstream>
31 #include <iostream>
32 #include <json/json.h>
33 #include <chrono>
34 #include <algorithm>
35 #include <functional>
36
37 #include "Data.h"
38 #include "CallLimiter.hh"
39 #include "base64.hpp"
40 #include "kodi/General.h"
41 #include "kodi/Filesystem.h"
42 #include "kodi/gui/dialogs/Numeric.h"
43
44 #if defined(TARGET_WINDOWS)
45 # define LOCALTIME_R(src, dst) localtime_s(dst, src)
46 # define GMTIME_R(src, dst) gmtime_s(dst, src)
47 #else
48 # define LOCALTIME_R(src, dst) localtime_r(src, dst)
49 # define GMTIME_R(src, dst) gmtime_r(src, dst)
50 #endif
51
52 namespace sledovanitvcz
53 {
54
55 static unsigned DiffBetweenUtcAndLocalTime(const time_t * when = nullptr, int * isdst = nullptr)
56 {
57 time_t tloc;
58 if (0 == when)
59 time(&tloc);
60 else
61 tloc = *when;
62
63 struct tm tm1;
64 LOCALTIME_R(&tloc, &tm1);
65 auto l_isdst = tm1.tm_isdst;
66 if (isdst)
67 *isdst = l_isdst;
68 GMTIME_R(&tloc, &tm1);
69 tm1.tm_isdst = l_isdst;
70 time_t t2 = mktime(&tm1);
71
72 return tloc - t2;
73 }
74
75 static inline unsigned DiffBetweenPragueAndLocalTime(const time_t * when = nullptr)
76 {
77 int isdst = -1;
78 auto diff = DiffBetweenUtcAndLocalTime(when, &isdst);
79 // Note: Prague(Czech) is in Central Europe Time -> CET or CEST == UTC+1 or UTC+2 == +3600 or +7200
80 return diff - (isdst > 0 ? 7200 : 3600);
81 }
82
83 Data::Data(const kodi::addon::IInstanceInfo& instance)
84 : kodi::addon::CInstancePVRClient{instance}
85 , m_bKeepAlive{true}
86 , m_bLoadRecordings{true}
87 , m_bLoadPlayList{true}
88 , m_bChannelsLoaded{false}
89 , m_groups{std::make_shared<group_container_t>()}
90 , m_channels{std::make_shared<channel_container_t>()}
91 , m_epg{std::make_shared<epg_container_t>()}
92 , m_recordings{std::make_shared<recording_container_t>()}
93 , m_timers{std::make_shared<timer_container_t>()}
94 , m_recordingAvailableDuration{0}
95 , m_recordingRecordedDuration{0}
96 , m_epgMinTime{time(nullptr)}
97 , m_epgMaxTime{time(nullptr) + 3600}
98 , m_epgMaxFutureDays{EpgMaxFutureDays()}
99 , m_epgMaxPastDays{EpgMaxPastDays()}
100 , m_bEGPLoaded{false}
101 , m_iLastStart{0}
102 , m_iLastEnd{0}
103 , m_manager{
104 GetInstanceSettingEnum<ApiManager::ServiceProvider_t>("serviceProvider", ApiManager::SP_DEFAULT)
105 , GetInstanceSettingString("userName")
106 , GetInstanceSettingString("password")
107 , GetInstanceSettingString("deviceId")
108 , GetInstanceSettingString("productId")
109 , GetInstanceSettingString("userAgent")
110 , instance.GetNumber()
111 }
112 {
113 if (!kodi::vfs::DirectoryExists(UserPath()))
114 {
115 kodi::vfs::CreateDirectory(UserPath());
116 }
117
118 SetEPGMaxDays(m_epgMaxFutureDays, m_epgMaxPastDays);
119
120 m_streamQuality = GetInstanceSettingEnum<ApiManager::StreamQuality_t>("streamQuality", ApiManager::SQ_DEFAULT);
121 m_fullChannelEpgRefresh = GetInstanceSettingInt("fullChannelEpgRefresh", 24) * 3600; // make it seconds
122 m_loadingsRefresh = GetInstanceSettingInt("loadingsRefresh", 10) * 60; // make it seconds
123 m_keepAliveDelay = GetInstanceSettingInt("keepAliveDelay", 120) * 60; // make it seconds
124 m_epgCheckDelay = GetInstanceSettingInt("epgCheckDelay", 10) * 60; // make it seconds
125 m_useH265 = GetInstanceSettingBoolean("useH265", false);
126 m_useAdaptive = GetInstanceSettingBoolean("useAdaptive", false);
127 m_showLockedChannels = GetInstanceSettingBoolean("showLockedChannels", true);
128 m_showLockedOnlyPin = GetInstanceSettingBoolean("showLockedOnlyPin", true);
129 kodi::Log(ADDON_LOG_DEBUG, "loadingsRefresh: %d, keepAliveDelay: %d, epgCheckDelay: %d, useHa265: %d, useAdaptive: %d, showLockedChannels: %d, showLockedOnlyPin: %d"
130 , m_loadingsRefresh, m_keepAliveDelay, m_epgCheckDelay, m_useH265, m_useAdaptive, m_showLockedChannels, m_showLockedOnlyPin);
131
132 m_thread = std::thread{[this] { Process(); }};
133 }
134
135 template<typename Job>
136 bool Data::SimpleLoadJob(bool & jobGuard, const Job & job)
137 {
138 if (!KeepAlive())
139 return false;
140
141 bool load = false;
142 {
143 std::lock_guard<std::mutex> critical(m_mutex);
144 if (jobGuard)
145 {
146 load = true;
147 jobGuard = false;
148 }
149 }
150 if (load)
151 {
152 job();
153 }
154 return load;
155 }
156
157 void Data::SetLoadRecordings()
158 {
159 std::lock_guard<std::mutex> critical(m_mutex);
160 m_bLoadRecordings = true;
161 }
162
163 void Data::SetLoadPlaylist()
164 {
165 std::lock_guard<std::mutex> critical(m_mutex);
166 m_bLoadPlayList = true;
167 m_bChannelsLoaded = false;
168 }
169
170 void Data::TriggerFullRefresh()
171 {
172 kodi::Log(ADDON_LOG_INFO, "%s triggering channels/EGP full refresh", __FUNCTION__);
173 m_iLastEnd = 0;
174 m_iLastStart = 0;
175
176 int future_days = 0, past_days = 0;
177 {
178 std::lock_guard<std::mutex> critical(m_mutex);
179 future_days = m_epgMaxFutureDays;
180 past_days = m_epgMaxPastDays;
181 }
182 SetEPGMaxDays(future_days, past_days);
183 LoadPlayList();
184 }
185
186 bool Data::LoadEPGJob()
187 {
188 kodi::Log(ADDON_LOG_DEBUG, "%s will check if EGP loading needed", __FUNCTION__);
189 time_t min_epg, max_epg;
190 {
191 std::lock_guard<std::mutex> critical(m_mutex);
192 min_epg = m_epgMinTime;
193 max_epg = m_epgMaxTime;
194 }
195 bool updated = false;
196 if (KeepAlive() && 0 == m_iLastEnd)
197 {
198 // the first run...load just needed data as soon as posible
199 LoadEPG(time(nullptr), true);
200 updated = true;
201 } else
202 {
203 if (KeepAlive() && max_epg > m_iLastEnd)
204 {
205 time_t start = m_iLastEnd + DiffBetweenUtcAndLocalTime(&m_iLastEnd);
206 LoadEPG(start - (start % 86400) - DiffBetweenUtcAndLocalTime(&start), false);
207 updated = true;
208 }
209 if (KeepAlive() && min_epg < m_iLastStart)
210 {
211 time_t start = m_iLastStart - 86400;
212 start += DiffBetweenUtcAndLocalTime(&start);
213 LoadEPG(start - (start % 86400) - DiffBetweenUtcAndLocalTime(&start), false);
214 updated = true;
215 }
216 }
217 if (KeepAlive())
218 ReleaseUnneededEPG();
219 return updated;
220 }
221
222 void Data::ReleaseUnneededEPG()
223 {
224 decltype (m_epg) epg;
225 time_t min_epg, max_epg;
226 {
227 std::lock_guard<std::mutex> critical(m_mutex);
228 min_epg = m_epgMinTime;
229 max_epg = m_epgMaxTime;
230 epg = m_epg;
231 }
232 auto epg_copy = std::make_shared<epg_container_t>();
233 kodi::Log(ADDON_LOG_DEBUG, "%s min_epg=%s max_epg=%s", __FUNCTION__, ApiManager::formatTime(min_epg).c_str(), ApiManager::formatTime(max_epg).c_str());
234
235 for (const auto & epg_channel : *epg)
236 {
237 auto & epg_data = epg_channel.second.epg;
238 std::vector<time_t> to_delete;
239 for (auto entry_i = epg_data.cbegin(); entry_i != epg_data.cend(); ++entry_i)
240 {
241 const EpgEntry & entry = entry_i->second;
242 if (entry_i->second.startTime > max_epg || entry_i->second.endTime < min_epg)
243 {
244 kodi::Log(ADDON_LOG_DEBUG, "Removing TV show: %s - %s, start=%s end=%s", epg_channel.second.strName.c_str(), entry.strTitle.c_str()
245 , ApiManager::formatTime(entry.startTime).c_str(), ApiManager::formatTime(entry.endTime).c_str());
246 // notify about the epg change...and delete it
247 kodi::addon::PVREPGTag tag;
248 tag.SetSeriesNumber(EPG_TAG_INVALID_SERIES_EPISODE);
249 tag.SetEpisodeNumber(EPG_TAG_INVALID_SERIES_EPISODE);
250 tag.SetEpisodePartNumber(EPG_TAG_INVALID_SERIES_EPISODE);
251 tag.SetUniqueBroadcastId(entry.iBroadcastId);
252 tag.SetUniqueChannelId(entry.iChannelId);
253 EpgEventStateChange(tag, EPG_EVENT_DELETED);
254
255 to_delete.push_back(entry_i->first);
256 }
257 }
258 if (!to_delete.empty())
259 {
260 auto & epg_copy_channel = (*epg_copy)[epg_channel.first];
261 epg_copy_channel = epg_channel.second;
262 for (const auto key_delete : to_delete)
263 {
264 epg_copy_channel.epg.erase(key_delete);
265 }
266 }
267 }
268
269 // check if something deleted, if so make copy and atomically reassign
270 if (!epg_copy->empty())
271 {
272 for (const auto & epg_channel : *epg)
273 {
274 if (epg_copy->count(epg_channel.first) <= 0)
275 (*epg_copy)[epg_channel.first] = epg_channel.second;
276 }
277
278 {
279 std::lock_guard<std::mutex> critical(m_mutex);
280 m_epg = std::move(epg_copy);
281 }
282 }
283
284 // narrow the loaded time info (if needed)
285 m_iLastStart = std::max(m_iLastStart, min_epg);
286 m_iLastEnd = std::min(m_iLastEnd, max_epg);
287 }
288
289 void Data::KeepAliveJob()
290 {
291 if (!KeepAlive())
292 return;
293
294 kodi::Log(ADDON_LOG_DEBUG, "keepAlive:: trigger");
295 if (!m_manager.keepAlive())
296 {
297 LoginLoop();
298 }
299 }
300
301 void Data::LoginLoop()
302 {
303 unsigned login_delay = 0;
304 for ( ; KeepAlive(); --login_delay)
305 {
306 if (0 >= login_delay)
307 {
308 if (m_manager.login())
309 {
310 registerDrm();
311 ConnectionStateChange("Connected", PVR_CONNECTION_STATE_CONNECTED, "");
312 break;
313 }
314 else
315 {
316 ConnectionStateChange("Disconnected", PVR_CONNECTION_STATE_DISCONNECTED, "");
317 login_delay = 30; // try in 30 seconds
318 }
319 }
320 std::this_thread::sleep_for(std::chrono::seconds{1});
321 }
322 }
323
324 void Data::registerDrm()
325 {
326 std::string licenseUrl, certificate;
327 if (!m_manager.registerDrm(licenseUrl, certificate))
328 {
329 kodi::Log(ADDON_LOG_WARNING, "DRM registration failed. DRM may not work");
330 }
331 static constexpr char url_placeholder[] = "={streamURL|base64}";
332 auto pos = licenseUrl.rfind(url_placeholder);
333 if (pos == licenseUrl.size() - sizeof(url_placeholder) + 1)
334 licenseUrl.erase(pos + 1);
335 else
336 kodi::Log(ADDON_LOG_WARNING, "Expecting DRM licenseUrl in form '...&streamURL%s', got %s. DRM may not work", url_placeholder, licenseUrl.c_str());
337 certificate = base64::to_base64(certificate);
338 {
339 std::lock_guard<std::mutex> critical(m_mutex);
340 m_drmCertificate = std::make_shared<std::string>(std::move(certificate));
341 m_drmLicenseUrl = std::make_shared<std::string>(std::move(licenseUrl));
342 }
343 }
344
345 bool Data::WaitForChannels() const
346 {
347 std::unique_lock<std::mutex> critical(m_mutex);
348 return m_waitCond.wait_for(critical, std::chrono::seconds{5}, [this] { return m_bChannelsLoaded; });
349 }
350
351 void Data::Process(void)
352 {
353 kodi::Log(ADDON_LOG_DEBUG, "keepAlive:: thread started");
354
355 LoginLoop();
356
357 bool epg_updated = false;
358
359 auto keep_alive_job = getCallLimiter(std::bind(&Data::KeepAliveJob, this), std::chrono::seconds{m_keepAliveDelay}, true);
360 auto trigger_full_refresh = getCallLimiter(std::bind(&Data::TriggerFullRefresh, this), std::chrono::seconds{m_fullChannelEpgRefresh}, true);
361 auto trigger_load_recordings = getCallLimiter(std::bind(&Data::SetLoadRecordings, this), std::chrono::seconds{m_loadingsRefresh}, true);
362 auto epg_dummy_trigger = getCallLimiter([] {}, std::chrono::seconds{m_epgCheckDelay}, false); // using the CallLimiter just to test if the epg should be done
363 auto load_playlist_job = std::bind(&Data::LoadPlayList, this);
364 auto load_recordings_job = std::bind(&Data::LoadRecordings, this);
365
366 bool work_done = true;
367 while (KeepAlive())
368 {
369 if (!work_done)
370 std::this_thread::sleep_for(std::chrono::seconds{1});
371
372 work_done = false;
373
374 work_done |= SimpleLoadJob(m_bLoadPlayList, load_playlist_job);
375 work_done |= SimpleLoadJob(m_bLoadRecordings, load_recordings_job);
376 // trigger full refresh once a time
377 work_done |= trigger_full_refresh.Call();
378 // trigger loading of recordings once a time
379 work_done |= trigger_load_recordings.Call();
380
381 if (epg_dummy_trigger.Call() || epg_updated)
382 {
383 // perform epg loading in next cycle if something updated in this one
384 epg_updated = LoadEPGJob();
385 work_done = true;
386 } else
387 {
388 epg_updated = false;
389 }
390
391 // do keep alive call once a time
392 work_done |= keep_alive_job.Call();
393 }
394 kodi::Log(ADDON_LOG_DEBUG, "keepAlive:: thread stopped");
395 }
396
397 Data::~Data(void)
398 {
399 {
400 std::lock_guard<std::mutex> critical(m_mutex);
401 m_bKeepAlive = false;
402 }
403 m_thread.join();
404 kodi::Log(ADDON_LOG_DEBUG, "%s destructed", __FUNCTION__);
405 }
406
407 ADDON_STATUS Data::SetInstanceSetting(const std::string & settingName, const kodi::addon::CSettingValue & settingValue)
408 {
409 // just force our data to be re-created
410 return ADDON_STATUS_NEED_RESTART;
411 }
412
413 PVR_ERROR Data::GetCapabilities(kodi::addon::PVRCapabilities& capabilities)
414 {
415 kodi::Log(ADDON_LOG_DEBUG, "%s", __FUNCTION__);
416
417 capabilities.SetSupportsEPG(true);
418 capabilities.SetSupportsTV(true);
419 capabilities.SetSupportsRadio(true);
420 capabilities.SetSupportsRecordings(true);
421 capabilities.SetSupportsRecordingsDelete(true);
422 capabilities.SetSupportsRecordingsUndelete(false);
423 capabilities.SetSupportsTimers(true);
424 capabilities.SetSupportsChannelGroups(true);
425 capabilities.SetSupportsChannelScan(false);
426 capabilities.SetSupportsChannelSettings(false);
427 capabilities.SetHandlesInputStream(false);
428 capabilities.SetHandlesDemuxing(false);
429 capabilities.SetSupportsRecordingPlayCount(false);
430 capabilities.SetSupportsLastPlayedPosition(false);
431 capabilities.SetSupportsRecordingEdl(false);
432 capabilities.SetSupportsRecordingsRename(false);
433 capabilities.SetSupportsRecordingsLifetimeChange(false);
434 capabilities.SetSupportsDescrambleInfo(false);
435
436 return PVR_ERROR_NO_ERROR;
437 }
438
439 PVR_ERROR Data::GetBackendName(std::string& name)
440 {
441 name = "PVR sledovanitv.cz (unofficial)";
442 return PVR_ERROR_NO_ERROR;
443 }
444
445 PVR_ERROR Data::GetBackendVersion(std::string& version)
446 {
447 version = "";
448 return PVR_ERROR_NO_ERROR;
449 }
450
451 PVR_ERROR Data::GetConnectionString(std::string& connection)
452 {
453 connection = "connected";
454 return PVR_ERROR_NO_ERROR;
455 }
456
457 bool Data::KeepAlive()
458 {
459 std::lock_guard<std::mutex> critical(m_mutex);
460 return m_bKeepAlive;
461 }
462
463 bool Data::LoadEPG(time_t iStart, bool bSmallStep)
464 {
465 const int step = bSmallStep ? 3600 : 86400;
466 kodi::Log(ADDON_LOG_DEBUG, "%s last start %s, start %s, last end %s, end %s", __FUNCTION__, ApiManager::formatTime(m_iLastStart).c_str()
467 , ApiManager::formatTime(iStart).c_str(), ApiManager::formatTime(m_iLastEnd).c_str(), ApiManager::formatTime(iStart + step).c_str());
468 if (m_bEGPLoaded && m_iLastStart != 0 && iStart >= m_iLastStart && iStart + step <= m_iLastEnd)
469 return false;
470
471 Json::Value root;
472
473 if (!m_manager.getEpg(iStart, bSmallStep, std::string() /*ChannelsList()*/, root))
474 {
475 kodi::Log(ADDON_LOG_INFO, "Cannot parse EPG data. EPG not loaded.");
476 m_bEGPLoaded = true;
477 return false;
478 }
479
480 if (m_iLastEnd == 0)
481 {
482 // the first run
483 m_iLastStart = m_iLastEnd = iStart;
484 } else
485 {
486 if (m_iLastStart > iStart)
487 m_iLastStart = iStart;
488 if (iStart + step > m_iLastEnd)
489 m_iLastEnd = iStart + step;
490 }
491
492 decltype (m_channels) channels;
493 decltype (m_epg) epg;
494 {
495 std::lock_guard<std::mutex> critical(m_mutex);
496 channels = m_channels;
497 epg = m_epg;
498 // extend min/max (if needed)
499 m_epgMinTime = std::min(m_epgMinTime, m_iLastStart);
500 m_epgMaxTime = std::max(m_epgMaxTime, m_iLastEnd);
501 }
502
503 auto epg_copy = std::make_shared<epg_container_t>(*epg);
504
505 Json::Value json_channels = root["channels"];
506 Json::Value::Members chIds = json_channels.getMemberNames();
507 for (Json::Value::Members::iterator i = chIds.begin(); i != chIds.end(); i++)
508 {
509 std::string strChId = *i;
510
511 const auto channel_i = std::find_if(channels->cbegin(), channels->cend(), [&strChId] (const Channel & ch) { return ch.strId == strChId; });
512 if (channel_i != channels->cend())
513 {
514 EpgChannel & epgChannel = (*epg_copy)[strChId];
515 epgChannel.strId = strChId;
516
517 Json::Value epgData = json_channels[strChId];
518 for (unsigned int j = 0; j < epgData.size(); j++)
519 {
520 Json::Value epgEntry = epgData[j];
521
522 const time_t start_time = ParseDateTime(epgEntry.get("startTime", "").asString());
523 const time_t end_time = ParseDateTime(epgEntry.get("endTime", "").asString());
524 EpgEntry iptventry;
525 iptventry.iBroadcastId = start_time; // unique id for channel (even if time_t is wider, int should be enough for short period of time)
526 iptventry.iGenreType = 0;
527 iptventry.iGenreSubType = 0;
528 iptventry.iChannelId = channel_i->iUniqueId;
529 iptventry.strTitle = epgEntry.get("title", "").asString();
530 iptventry.strPlot = epgEntry.get("description", "").asString();
531 iptventry.startTime = start_time;
532 iptventry.endTime = end_time;
533 iptventry.strEventId = epgEntry.get("eventId", "").asString();
534 iptventry.strIconPath = epgEntry.get("poster", "").asString();
535 std::string availability = epgEntry.get("availability", "none").asString();
536 iptventry.availableTimeshift = availability == "timeshift" || availability == "pvr";
537 iptventry.strRecordId = epgEntry["recordId"].asString();
538 iptventry.starRating = round(epgEntry.get("score", 0.0).asDouble());
539 const Json::Value parent_rating{epgEntry.get("ratingAge", Json::nullValue)};
540 iptventry.parentalRating = parent_rating.isNumeric() ? parent_rating.asInt() : 0;
541
542 kodi::Log(ADDON_LOG_DEBUG, "Loading TV show: %s - %s, start=%s(epoch=%llu)", strChId.c_str(), iptventry.strTitle.c_str()
543 , epgEntry.get("startTime", "").asString().c_str(), static_cast<long long unsigned>(start_time));
544
545 // notify about the epg change...and store it
546 kodi::addon::PVREPGTag tag;
547 tag.SetSeriesNumber(EPG_TAG_INVALID_SERIES_EPISODE);
548 tag.SetEpisodeNumber(EPG_TAG_INVALID_SERIES_EPISODE);
549 tag.SetEpisodePartNumber(EPG_TAG_INVALID_SERIES_EPISODE);
550
551 tag.SetUniqueBroadcastId(iptventry.iBroadcastId);
552 tag.SetUniqueChannelId(iptventry.iChannelId);
553 tag.SetTitle(iptventry.strTitle);
554 tag.SetStartTime(iptventry.startTime);
555 tag.SetEndTime(iptventry.endTime);
556 tag.SetPlotOutline(iptventry.strPlotOutline);
557 tag.SetPlot(iptventry.strPlot);
558 tag.SetIconPath(iptventry.strIconPath);
559 tag.SetGenreType(EPG_GENRE_USE_STRING); //iptventry.iGenreType;
560 tag.SetGenreSubType(0); //iptventry.iGenreSubType;
561 tag.SetGenreDescription(iptventry.strGenreString);
562 tag.SetStarRating(iptventry.starRating);
563 tag.SetParentalRating(iptventry.parentalRating);
564
565 auto result = epgChannel.epg.emplace(iptventry.startTime, iptventry);
566 bool value_changed = !result.second;
567 if (value_changed)
568 {
569 epgChannel.epg[iptventry.startTime] = std::move(iptventry);
570 }
571
572 EpgEventStateChange(tag, value_changed ? EPG_EVENT_UPDATED : EPG_EVENT_CREATED);
573 }
574 }
575 }
576
577 // atomic assign new version of the epg all epgs
578 {
579 std::lock_guard<std::mutex> critical(m_mutex);
580 m_epg = epg_copy;
581 }
582
583 m_bEGPLoaded = true;
584 kodi::Log(ADDON_LOG_INFO, "EPG Loaded.");
585
586 return true;
587 }
588
589 bool Data::LoadRecordings()
590 {
591 decltype (m_channels) channels;
592 decltype (m_recordings) recordings;
593 decltype (m_timers) timers;
594 {
595 std::lock_guard<std::mutex> critical(m_mutex);
596 channels = m_channels;
597 recordings = m_recordings;
598 timers = m_timers;
599 }
600
601 auto new_recordings = std::make_shared<recording_container_t>();
602 auto new_timers = std::make_shared<timer_container_t>();
603 long long available_duration = 0;
604 long long recorded_duration = 0;
605
606 Json::Value root;
607
608 if (!m_manager.getPvr(root))
609 {
610 kodi::Log(ADDON_LOG_INFO, "Cannot parse recordings.");
611 return false;
612 }
613
614 available_duration = root["summary"].get("availableDuration", 0).asInt() / 60 * 1024; //report minutes as MB
615 recorded_duration = root["summary"].get("recordedDuration", 0).asInt() / 60 * 1024;
616
617 Json::Value records = root["records"];
618 for (unsigned int i = 0; i < records.size(); i++)
619 {
620 Json::Value record = records[i];
621 const std::string title = record.get("title", "").asString();
622 const std::string locked = record.get("channelLocked", "none").asString();
623 std::string directory;
624 if (locked != "none")
625 {
626 directory = kodi::addon::GetLocalizedString(30201);
627 directory += " - ";
628 directory += locked;
629 kodi::Log(ADDON_LOG_INFO, "Timer/recording '%s' is locked(%s)", title.c_str(), locked.c_str());
630 }
631 std::string str_ch_id = record.get("channel", "").asString();
632 const auto channel_i = std::find_if(channels->cbegin(), channels->cend(), [&str_ch_id] (const Channel & ch) { return ch.strId == str_ch_id; });
633 Recording iptvrecording;
634 Timer iptvtimer;
635 time_t startTime = ParseDateTime(record.get("startTime", "").asString());
636 int duration = record.get("duration", 0).asInt();
637 time_t now;
638 time(&now);
639
640 if ((startTime + duration) < now)
641 {
642 char buf[256];
643 sprintf(buf, "%d", record.get("id", 0).asInt());
644 iptvrecording.strRecordId = buf;
645 iptvrecording.strTitle = std::move(title);
646
647 if (channel_i != channels->cend())
648 {
649 iptvrecording.strChannelName = channel_i->strChannelName;
650 iptvrecording.iChannelUid = channel_i->iUniqueId;
651 } else
652 {
653 iptvrecording.iChannelUid = PVR_CHANNEL_INVALID_UID;
654 }
655 iptvrecording.startTime = startTime;
656 iptvrecording.strPlotOutline = record.get("event", "").get("description", "").asString();
657 iptvrecording.duration = duration;
658 iptvrecording.bRadio = channel_i->bIsRadio;
659 iptvrecording.iLifeTime = (ParseDateTime(record.get("expires", "").asString() + "00:00") - now) / 86400;
660 iptvrecording.strDirectory = std::move(directory);
661 iptvrecording.bIsPinLocked = locked == "pin";
662
663 kodi::Log(ADDON_LOG_DEBUG, "Loading recording '%s'", iptvrecording.strTitle.c_str());
664
665 new_recordings->push_back(iptvrecording);
666 }
667 else
668 {
669 iptvtimer.iClientIndex = record.get("id", 0).asInt();
670 if (channel_i != channels->cend())
671 {
672 iptvtimer.iClientChannelUid = channel_i->iUniqueId;
673 }
674 iptvtimer.startTime = ParseDateTime(record.get("startTime", "").asString());
675 iptvtimer.endTime = iptvtimer.startTime + record.get("duration", 0).asInt();
676
677 if (startTime < now && (startTime + duration) >= now)
678 {
679 iptvtimer.state = PVR_TIMER_STATE_RECORDING;
680 }
681 else
682 {
683 iptvtimer.state = PVR_TIMER_STATE_SCHEDULED;
684 }
685 iptvtimer.strTitle = std::move(title);
686 iptvtimer.iLifeTime = (ParseDateTime(record.get("expires", "").asString() + "00:00") - now) / 86400;
687 iptvtimer.strDirectory = std::move(directory);
688
689 kodi::Log(ADDON_LOG_DEBUG, "Loading timer '%s'", iptvtimer.strTitle.c_str());
690
691 new_timers->push_back(iptvtimer);
692 }
693
694 }
695
696 bool changed_r = new_recordings->size() != recordings->size();
697 for (size_t i = 0; !changed_r && i < new_recordings->size(); ++i)
698 {
699 const auto & old_rec = (*recordings)[i];
700 const auto & new_rec = (*new_recordings)[i];
701 if (new_rec.strRecordId != old_rec.strRecordId)
702 {
703 changed_r = true;
704 break;
705 }
706 }
707 bool changed_t = new_timers->size() != timers->size();
708 for (size_t i = 0; !changed_t && i < new_timers->size(); ++i)
709 {
710 const auto & old_timer = (*timers)[i];
711 const auto & new_timer = (*new_timers)[i];
712 if (new_timer.iClientIndex != old_timer.iClientIndex)
713 {
714 changed_t = true;
715 break;
716 }
717 }
718 {
719 std::lock_guard<std::mutex> critical(m_mutex);
720 if (changed_r)
721 {
722 m_recordings = std::move(new_recordings);
723 TriggerRecordingUpdate();
724 }
725
726 if (changed_t)
727 {
728 m_timers = std::move(new_timers);
729 TriggerTimerUpdate();
730 }
731 m_recordingAvailableDuration = available_duration;
732 m_recordingRecordedDuration = recorded_duration;
733 }
734
735 return true;
736 }
737
738 bool Data::LoadPlayList(void)
739 {
740 if (!KeepAlive())
741 return false;
742
743 Json::Value root;
744
745 if (!m_manager.getPlaylist(m_streamQuality, m_useH265, m_useAdaptive, root))
746 {
747 kodi::Log(ADDON_LOG_INFO, "Cannot get/parse playlist.");
748 return false;
749 }
750
751 /*
752 std::string qualities = m_manager.getStreamQualities();
753 kodi::Log(ADDON_LOG_DEBUG, "Stream qualities: %s", qualities.c_str());
754 */
755
756 //channels
757 auto new_channels = std::make_shared<channel_container_t>();
758 Json::Value channels = root["channels"];
759 for (unsigned int i = 0; i < channels.size(); i++)
760 {
761 Json::Value channel = channels[i];
762 const std::string locked = channel.get("locked", "none").asString();
763 if (locked != "none")
764 {
765 if (!m_showLockedChannels || (m_showLockedOnlyPin && locked != "pin"))
766 {
767 kodi::Log(ADDON_LOG_INFO, "Skipping locked(%s) channel#%u %s", locked.c_str(), i + 1, channel.get("name", "").asString().c_str());
768 continue;
769 }
770 }
771
772 Channel iptvchan;
773
774 iptvchan.strId = channel.get("id", "").asString();
775 iptvchan.strChannelName = channel.get("name", "").asString();
776 iptvchan.strGroupId = channel.get("group", "").asString();
777 iptvchan.strStreamURL = channel.get("url", "").asString();
778 iptvchan.strStreamType = channel.get("streamType", "").asString();
779 iptvchan.bIsDrm = channel.get("drm", "0").asInt() != 0;
780 iptvchan.iUniqueId = i + 1;
781 iptvchan.iChannelNumber = i + 1;
782 kodi::Log(ADDON_LOG_DEBUG, "Channel#%d %s, URL: %s", iptvchan.iUniqueId, iptvchan.strChannelName.c_str(), iptvchan.strStreamURL.c_str());
783 iptvchan.strIconPath = channel.get("logoUrl", "").asString();
784 iptvchan.bIsRadio = channel.get("type", "").asString() != "tv";
785 iptvchan.bIsPinLocked = locked == "pin";
786
787 new_channels->push_back(iptvchan);
788 }
789
790 auto new_groups = std::make_shared<group_container_t>();
791 Json::Value groups = root["groups"];
792 for (const auto & group_id : groups.getMemberNames())
793 {
794 ChannelGroup group;
795 group.bRadio = false; // currently there is no way to distinguish group types in the returned json
796 group.strGroupId = group_id;
797 group.strGroupName = groups[group_id].asString();
798 for (const auto & channel : *new_channels)
799 {
800 if (channel.strGroupId == group_id && !channel.bIsRadio)
801 group.members.push_back(channel.iUniqueId);
802 }
803 new_groups->push_back(std::move(group));
804 }
805
806 kodi::Log(ADDON_LOG_INFO, "Loaded %d channels.", new_channels->size());
807 kodi::QueueFormattedNotification(QUEUE_INFO, "%s - %d channels loaded.", GetInstanceSettingString("kodi_addon_instance_name").c_str(), new_channels->size());
808
809 {
810 std::lock_guard<std::mutex> critical(m_mutex);
811 m_channels = std::move(new_channels);
812 m_groups = std::move(new_groups);
813 m_bChannelsLoaded = true;
814 }
815 m_waitCond.notify_all();
816 TriggerChannelUpdate();
817 TriggerChannelGroupsUpdate();
818
819 return true;
820 }
821
822 PVR_ERROR Data::GetChannelsAmount(int& amount)
823 {
824 decltype (m_channels) channels;
825 {
826 std::lock_guard<std::mutex> critical(m_mutex);
827 channels = m_channels;
828 }
829
830 amount = channels->size();
831 return PVR_ERROR_NO_ERROR;
832 }
833
834 PVR_ERROR Data::GetChannels(bool radio, kodi::addon::PVRChannelsResultSet& results)
835 {
836 kodi::Log(ADDON_LOG_DEBUG, "%s %s", __FUNCTION__, radio ? "radio" : "tv");
837 WaitForChannels();
838
839 decltype (m_channels) channels;
840 {
841 std::lock_guard<std::mutex> critical(m_mutex);
842 channels = m_channels;
843 }
844
845 for (const auto & channel : *channels)
846 {
847 if (channel.bIsRadio == radio)
848 {
849 kodi::addon::PVRChannel kodiChannel;
850
851 kodiChannel.SetUniqueId(channel.iUniqueId);
852 kodiChannel.SetIsRadio(channel.bIsRadio);
853 kodiChannel.SetChannelNumber(channel.iChannelNumber);
854 kodiChannel.SetChannelName(channel.strChannelName);
855 kodiChannel.SetEncryptionSystem(channel.iEncryptionSystem);
856 kodiChannel.SetIconPath(channel.strIconPath);
857 kodiChannel.SetIsHidden(false);
858
859 results.Add(kodiChannel);
860 }
861 }
862
863 return PVR_ERROR_NO_ERROR;
864 }
865
866 PVR_ERROR Data::GetChannelStreamProperties(const kodi::addon::PVRChannel& channel, std::vector<kodi::addon::PVRStreamProperty>& properties)
867 {
868 std::string streamUrl, streamType;
869 bool isDrm;
870 PVR_ERROR ret = GetChannelStreamUrl(channel, streamUrl, streamType, isDrm);
871 if (PVR_ERROR_NO_ERROR != ret)
872 return ret;
873
874 properties = StreamProperties(streamUrl, streamType, isDrm, true);
875 return PVR_ERROR_NO_ERROR;
876 }
877
878 PVR_ERROR Data::GetSignalStatus(int channelUid, kodi::addon::PVRSignalStatus& signalStatus)
879 {
880 signalStatus.SetAdapterName("sledovanitv.cz");
881 signalStatus.SetAdapterStatus("OK");
882
883 return PVR_ERROR_NO_ERROR;
884 }
885
886 PVR_ERROR Data::GetChannelStreamUrl(const kodi::addon::PVRChannel& channel, std::string & streamUrl, std::string & streamType, bool & isDrm)
887 {
888 decltype (m_channels->cbegin()) channel_i;
889 auto chan_getter = [this, &channel, &channel_i]() -> bool {
890 decltype (m_channels) channels;
891 {
892 std::lock_guard<std::mutex> critical(m_mutex);
893 channels = m_channels;
894 }
895
896 channel_i = std::find_if(channels->cbegin(), channels->cend(), [&channel] (const Channel & c) { return c.iUniqueId == channel.GetUniqueId(); });
897 return channels->cend() != channel_i;
898 };
899 if (!chan_getter())
900 {
901 kodi::Log(ADDON_LOG_INFO, "%s can't find channel %d", __FUNCTION__, channel.GetUniqueId());
902 return PVR_ERROR_INVALID_PARAMETERS;
903 }
904
905 bool unlocked_now = false;
906 if (!PinCheckUnlock(channel_i->bIsPinLocked, unlocked_now))
907 return PVR_ERROR_REJECTED;
908
909 if (unlocked_now) {
910 // reget the data
911 if (!chan_getter())
912 return PVR_ERROR_INVALID_PARAMETERS;
913 }
914
915 streamUrl = channel_i->strStreamURL;
916 streamType = channel_i->strStreamType;
917 isDrm = channel_i->bIsDrm;
918 return PVR_ERROR_NO_ERROR;
919
920 }
921
922 PVR_ERROR Data::GetChannelGroupsAmount(int& amount)
923 {
924 decltype (m_groups) groups;
925 {
926 std::lock_guard<std::mutex> critical(m_mutex);
927 groups = m_groups;
928 }
929 amount = groups->size();
930 return PVR_ERROR_NO_ERROR;
931 }
932
933 PVR_ERROR Data::GetChannelGroups(bool radio, kodi::addon::PVRChannelGroupsResultSet& results)
934 {
935 kodi::Log(ADDON_LOG_DEBUG, "%s %s", __FUNCTION__, radio ? "radio" : "tv");
936 WaitForChannels();
937
938 decltype (m_groups) groups;
939 {
940 std::lock_guard<std::mutex> critical(m_mutex);
941 groups = m_groups;
942 }
943
944 for (const auto & group : *groups)
945 {
946 if (group.bRadio == radio)
947 {
948 kodi::addon::PVRChannelGroup kodiGroup;
949
950 kodiGroup.SetIsRadio(radio);
951 kodiGroup.SetGroupName(group.strGroupName);
952
953 results.Add(kodiGroup);
954 }
955 }
956
957 return PVR_ERROR_NO_ERROR;
958 }
959
960 PVR_ERROR Data::GetChannelGroupMembers(const kodi::addon::PVRChannelGroup& group, kodi::addon::PVRChannelGroupMembersResultSet& results)
961 {
962 kodi::Log(ADDON_LOG_DEBUG, "%s %s", __FUNCTION__, group.GetGroupName().c_str());
963 WaitForChannels();
964
965 decltype (m_groups) groups;
966 decltype (m_channels) channels;
967 {
968 std::lock_guard<std::mutex> critical(m_mutex);
969 groups = m_groups;
970 channels = m_channels;
971 }
972
973 std::vector<kodi::addon::PVRChannelGroupMember> kodi_group_members;
974 auto group_i = std::find_if(groups->cbegin(), groups->cend(), [&group] (ChannelGroup const & g) { return g.strGroupName == group.GetGroupName(); });
975 if (group_i != groups->cend())
976 {
977 int order = 0;
978 for (const auto & member : group_i->members)
979 {
980 if (member < 0 || member >= channels->size())
981 continue;
982
983 const Channel &channel = (*channels)[member];
984 kodi::addon::PVRChannelGroupMember kodiGroupMember;
985
986 kodiGroupMember.SetGroupName(group.GetGroupName());
987 kodiGroupMember.SetChannelUniqueId(channel.iUniqueId);
988 kodiGroupMember.SetChannelNumber(++order);
989
990 kodi_group_members.push_back(std::move(kodiGroupMember));
991 }
992 }
993 for (const auto & kodiGroupMember : kodi_group_members)
994 {
995 results.Add(kodiGroupMember);
996 }
997
998 return PVR_ERROR_NO_ERROR;
999 }
1000
1001 PVR_ERROR Data::GetEPGForChannel(int channelUid, time_t start, time_t end, kodi::addon::PVREPGTagsResultSet& results)
1002 {
1003 kodi::Log(ADDON_LOG_DEBUG, "%s %i, from=%s to=%s", __FUNCTION__, channelUid, ApiManager::formatTime(start).c_str(), ApiManager::formatTime(end).c_str());
1004 std::lock_guard<std::mutex> critical(m_mutex);
1005 // Note: For future scheduled timers Kodi requests EPG (this function) with
1006 // start & end as given by the timer timespan. But we don't want to narrow
1007 // our EPG interval in such cases.
1008 m_epgMinTime = start < m_epgMinTime ? start : m_epgMinTime;
1009 m_epgMaxTime = end > m_epgMaxTime ? end : m_epgMaxTime;
1010 return PVR_ERROR_NO_ERROR;
1011 }
1012
1013 static PVR_ERROR GetEPGData(const kodi::addon::PVREPGTag& tag
1014 , const channel_container_t * channels
1015 , const epg_container_t * epg
1016 , epg_entry_container_t::const_iterator & epg_i
1017 , bool * isChannelPinLocked = nullptr
1018 , bool * isChannelDrm = nullptr
1019 )
1020 {
1021 auto channel_i = std::find_if(channels->cbegin(), channels->cend(), [tag] (const Channel & c) { return c.iUniqueId == tag.GetUniqueChannelId(); });
1022 if (channels->cend() == channel_i)
1023 {
1024 kodi::Log(ADDON_LOG_INFO, "%s can't find channel %d", __FUNCTION__, tag.GetUniqueChannelId());
1025 return PVR_ERROR_INVALID_PARAMETERS;
1026 }
1027 if (isChannelPinLocked)
1028 *isChannelPinLocked = channel_i->bIsPinLocked;
1029 if (isChannelDrm)
1030 *isChannelDrm = channel_i->bIsDrm;
1031
1032 auto ch_epg_i = epg->find(channel_i->strId);
1033
1034 if (epg->cend() == ch_epg_i || (epg_i = ch_epg_i->second.epg.find(tag.GetUniqueBroadcastId())) == ch_epg_i->second.epg.cend())
1035 {
1036 kodi::Log(ADDON_LOG_INFO, "%s can't find EPG data for channel %s, time %d", __FUNCTION__, channel_i->strId.c_str(), tag.GetUniqueBroadcastId());
1037 return PVR_ERROR_INVALID_PARAMETERS;
1038 }
1039 return PVR_ERROR_NO_ERROR;
1040 }
1041
1042 PVR_ERROR Data::IsEPGTagPlayable(const kodi::addon::PVREPGTag& tag, bool& isPlayable)
1043 {
1044 decltype (m_channels) channels;
1045 decltype (m_epg) epg;
1046 {
1047 std::lock_guard<std::mutex> critical(m_mutex);
1048 channels = m_channels;
1049 epg = m_epg;
1050 }
1051
1052 epg_entry_container_t::const_iterator epg_i;
1053 PVR_ERROR ret = GetEPGData(tag, channels.get(), epg.get(), epg_i);
1054 if (PVR_ERROR_NO_ERROR != ret)
1055 return ret;
1056
1057 isPlayable = epg_i->second.availableTimeshift && tag.GetStartTime() < time(nullptr);
1058 return PVR_ERROR_NO_ERROR;
1059 }
1060
1061 PVR_ERROR Data::IsEPGTagRecordable(const kodi::addon::PVREPGTag& tag, bool& isRecordable)
1062 {
1063 decltype (m_channels) channels;
1064 decltype (m_epg) epg;
1065 {
1066 std::lock_guard<std::mutex> critical(m_mutex);
1067 channels = m_channels;
1068 epg = m_epg;
1069 }
1070
1071 epg_entry_container_t::const_iterator epg_i;
1072 PVR_ERROR ret = GetEPGData(tag, channels.get(), epg.get(), epg_i);
1073 if (PVR_ERROR_NO_ERROR != ret)
1074 return ret;
1075
1076 isRecordable = epg_i->second.availableTimeshift && !RecordingExists(epg_i->second.strRecordId) && tag.GetStartTime() < time(nullptr);
1077 return PVR_ERROR_NO_ERROR;
1078 }
1079
1080 PVR_ERROR Data::GetEPGTagStreamProperties(const kodi::addon::PVREPGTag& tag, std::vector<kodi::addon::PVRStreamProperty>& properties)
1081 {
1082 std::string streamUrl, streamType;
1083 bool isDrm;
1084 PVR_ERROR ret = GetEPGStreamUrl(tag, streamUrl, streamType, isDrm);
1085 if (PVR_ERROR_NO_ERROR != ret)
1086 return ret;
1087
1088 properties = StreamProperties(streamUrl, streamType, isDrm, false);
1089 return PVR_ERROR_NO_ERROR;
1090 }
1091
1092 PVR_ERROR Data::GetEPGStreamUrl(const kodi::addon::PVREPGTag& tag, std::string & streamUrl, std::string & streamType, bool & isDrm)
1093 {
1094 decltype (m_channels) channels;
1095 decltype (m_epg) epg;
1096 {
1097 std::lock_guard<std::mutex> critical(m_mutex);
1098 channels = m_channels;
1099 epg = m_epg;
1100 }
1101
1102 bool isPinLocked;
1103 epg_entry_container_t::const_iterator epg_i;
1104 PVR_ERROR ret = GetEPGData(tag, channels.get(), epg.get(), epg_i, &isPinLocked, &isDrm);
1105 if (PVR_ERROR_NO_ERROR != ret)
1106 return ret;
1107
1108 bool unlocked_now = false;
1109 if (!PinCheckUnlock(isPinLocked, unlocked_now))
1110 return PVR_ERROR_REJECTED;
1111
1112 if (RecordingExists(epg_i->second.strRecordId))
1113 return GetRecordingStreamUrl(epg_i->second.strRecordId, streamUrl, streamType, isDrm);
1114
1115 std::string channel_id;
1116 int duration;
1117 if (!m_manager.getTimeShiftInfo(epg_i->second.strEventId, streamUrl, channel_id, duration))
1118 return PVR_ERROR_INVALID_PARAMETERS;
1119 // get the stream type based on channel
1120 streamType = ChannelStreamType(channel_id);
1121
1122 return PVR_ERROR_NO_ERROR;
1123 }
1124
1125 PVR_ERROR Data::SetEPGMaxFutureDays(int iFutureDays)
1126 {
1127 return SetEPGMaxDays(iFutureDays, -1);
1128 }
1129
1130 PVR_ERROR Data::SetEPGMaxPastDays(int iPastDays)
1131 {
1132 return SetEPGMaxDays(-1, iPastDays);
1133 }
1134
1135 PVR_ERROR Data::SetEPGMaxDays(int iFutureDays, int iPastDays)
1136 {
1137 kodi::Log(ADDON_LOG_DEBUG, "%s iFutureDays=%d, iPastDays=%d", __FUNCTION__, iFutureDays, iPastDays);
1138 time_t now = time(nullptr);
1139 std::lock_guard<std::mutex> critical(m_mutex);
1140 m_epgMaxFutureDays = (iFutureDays == -1 ? m_epgMaxFutureDays : iFutureDays);
1141 m_epgMaxPastDays = (iPastDays == -1 ? m_epgMaxPastDays : iPastDays);
1142 m_epgMinTime = now - m_epgMaxPastDays * 86400;
1143 m_epgMaxTime = now + m_epgMaxFutureDays * 86400;
1144
1145 return PVR_ERROR_NO_ERROR;
1146 }
1147
1148 int Data::ParseDateTime(std::string strDate)
1149 {
1150 struct tm timeinfo;
1151 memset(&timeinfo, 0, sizeof(tm));
1152
1153 sscanf(strDate.c_str(), "%04d-%02d-%02d %02d:%02d", &timeinfo.tm_year, &timeinfo.tm_mon, &timeinfo.tm_mday, &timeinfo.tm_hour, &timeinfo.tm_min);
1154 timeinfo.tm_sec = 0;
1155
1156 timeinfo.tm_mon -= 1;
1157 timeinfo.tm_year -= 1900;
1158 timeinfo.tm_isdst = -1;
1159
1160 time_t t = mktime(&timeinfo);
1161 return t - DiffBetweenPragueAndLocalTime(&t);
1162 }
1163
1164 PVR_ERROR Data::GetRecordingsAmount(bool deleted, int& amount)
1165 {
1166 decltype (m_recordings) recordings;
1167 {
1168 std::lock_guard<std::mutex> critical(m_mutex);
1169 recordings = m_recordings;
1170 }
1171 amount = recordings->size();
1172 return PVR_ERROR_NO_ERROR;
1173 }
1174
1175 PVR_ERROR Data::GetRecordings(bool deleted, kodi::addon::PVRRecordingsResultSet& results)
1176 {
1177 decltype (m_recordings) recordings;
1178 {
1179 std::lock_guard<std::mutex> critical(m_mutex);
1180 recordings = m_recordings;
1181 }
1182 auto insert_lambda = [&results] (const Recording & rec)
1183 {
1184 kodi::addon::PVRRecording kodiRecord;
1185
1186 kodiRecord.SetRecordingId(rec.strRecordId);
1187 kodiRecord.SetTitle(rec.strTitle);
1188 kodiRecord.SetDirectory(rec.strDirectory);
1189 kodiRecord.SetChannelName(rec.strChannelName);
1190 kodiRecord.SetRecordingTime(rec.startTime);
1191 kodiRecord.SetPlotOutline(rec.strPlotOutline);
1192 kodiRecord.SetPlot(rec.strPlotOutline);
1193 kodiRecord.SetDuration(rec.duration);
1194 kodiRecord.SetLifetime(rec.iLifeTime);
1195 kodiRecord.SetChannelUid(rec.iChannelUid);
1196 kodiRecord.SetChannelType(rec.bRadio ? PVR_RECORDING_CHANNEL_TYPE_RADIO : PVR_RECORDING_CHANNEL_TYPE_TV);
1197
1198 results.Add(kodiRecord);
1199 };
1200
1201 std::for_each(recordings->cbegin(), recordings->cend(), insert_lambda);
1202
1203 return PVR_ERROR_NO_ERROR;
1204 }
1205
1206 PVR_ERROR Data::GetRecordingStreamProperties(const kodi::addon::PVRRecording& recording, std::vector<kodi::addon::PVRStreamProperty>& properties)
1207 {
1208 std::string streamUrl, streamType;
1209 bool isDrm;
1210 PVR_ERROR ret = GetRecordingStreamUrl(recording.GetRecordingId(), streamUrl, streamType, isDrm);
1211 if (PVR_ERROR_NO_ERROR != ret)
1212 return ret;
1213
1214 properties = StreamProperties(streamUrl, streamType, isDrm, false);
1215 return PVR_ERROR_NO_ERROR;
1216 }
1217
1218 PVR_ERROR Data::GetRecordingStreamUrl(const std::string & recording, std::string & streamUrl, std::string & streamType, bool & isDrm)
1219 {
1220 decltype (m_recordings) recordings;
1221 {
1222 std::lock_guard<std::mutex> critical(m_mutex);
1223 recordings = m_recordings;
1224 }
1225 auto rec_i = std::find_if(recordings->cbegin(), recordings->cend(), [recording] (const Recording & r) { return recording == r.strRecordId; });
1226 if (recordings->cend() == rec_i)
1227 return PVR_ERROR_INVALID_PARAMETERS;
1228
1229 bool unlocked_now = false;
1230 if (!PinCheckUnlock(rec_i->bIsPinLocked, unlocked_now))
1231 return PVR_ERROR_REJECTED;
1232
1233 std::string channel_id;
1234 streamUrl = m_manager.getRecordingUrl(rec_i->strRecordId, channel_id, isDrm);
1235 // get the stream type based on channel
1236 streamType = ChannelStreamType(channel_id);
1237 return PVR_ERROR_NO_ERROR;
1238 }
1239
1240 bool Data::RecordingExists(const std::string & recordId) const
1241 {
1242 decltype (m_recordings) recordings;
1243 {
1244 std::lock_guard<std::mutex> critical(m_mutex);
1245 recordings = m_recordings;
1246 }
1247 return recordings->cend() != std::find_if(recordings->cbegin(), recordings->cend(), [&recordId] (const Recording & r) { return recordId == r.strRecordId; });
1248 }
1249
1250 PVR_ERROR Data::GetTimerTypes(std::vector<kodi::addon::PVRTimerType>& types)
1251 {
1252 kodi::Log(ADDON_LOG_DEBUG, "%s", __FUNCTION__);
1253
1254 int id = 0;
1255 kodi::addon::PVRTimerType type;
1256
1257 type.SetId(++id);
1258 type.SetAttributes(PVR_TIMER_TYPE_IS_MANUAL | PVR_TIMER_TYPE_SUPPORTS_CHANNELS | PVR_TIMER_TYPE_SUPPORTS_START_TIME);
1259 kodi::Log(ADDON_LOG_DEBUG, "%s - id %i attributes: 0x%x", __FUNCTION__, id, type.GetAttributes());
1260 types.push_back(type);
1261
1262 type.SetId(++id);
1263 type.SetAttributes(PVR_TIMER_TYPE_REQUIRES_EPG_TAG_ON_CREATE | PVR_TIMER_TYPE_SUPPORTS_CHANNELS | PVR_TIMER_TYPE_SUPPORTS_START_TIME);
1264 kodi::Log(ADDON_LOG_DEBUG, "%s - id %i attributes: 0x%x", __FUNCTION__, id, type.GetAttributes());
1265 types.push_back(type);
1266
1267 type.SetId(++id);
1268 type.SetAttributes(PVR_TIMER_TYPE_IS_REPEATING | PVR_TIMER_TYPE_REQUIRES_EPG_TAG_ON_CREATE | PVR_TIMER_TYPE_SUPPORTS_CHANNELS | PVR_TIMER_TYPE_SUPPORTS_START_TIME);
1269 kodi::Log(ADDON_LOG_DEBUG, "%s - id %i attributes: 0x%x", __FUNCTION__, id, type.GetAttributes());
1270 types.push_back(type);
1271
1272 return PVR_ERROR_NO_ERROR;
1273 }
1274
1275 PVR_ERROR Data::GetTimersAmount(int& amount)
1276 {
1277 decltype (m_timers) timers;
1278 {
1279 std::lock_guard<std::mutex> critical(m_mutex);
1280 timers = m_timers;
1281 }
1282 amount = timers->size();
1283 return PVR_ERROR_NO_ERROR;
1284 }
1285
1286
1287 PVR_ERROR Data::GetTimers(kodi::addon::PVRTimersResultSet& results)
1288 {
1289 decltype (m_timers) timers;
1290 {
1291 std::lock_guard<std::mutex> critical(m_mutex);
1292 timers = m_timers;
1293 }
1294
1295 for (const auto & timer : *timers)
1296 {
1297 kodi::addon::PVRTimer kodiTimer;
1298
1299 kodiTimer.SetClientIndex(timer.iClientIndex);
1300 kodiTimer.SetClientChannelUid(timer.iClientChannelUid);
1301 kodiTimer.SetStartTime(timer.startTime);
1302 kodiTimer.SetEndTime(timer.endTime);
1303 kodiTimer.SetState(timer.state);
1304 kodiTimer.SetTimerType(1); // Note: this must match some type from GetTimerTypes()
1305 kodiTimer.SetLifetime(timer.iLifeTime);
1306 kodiTimer.SetTitle(timer.strTitle);
1307 kodiTimer.SetSummary(timer.strSummary);
1308 kodiTimer.SetDirectory(timer.strDirectory);
1309
1310 results.Add(kodiTimer);
1311 }
1312
1313 return PVR_ERROR_NO_ERROR;
1314 }
1315
1316 PVR_ERROR Data::AddTimer(const kodi::addon::PVRTimer& timer)
1317 {
1318 decltype (m_channels) channels;
1319 decltype (m_epg) epg;
1320 {
1321 std::lock_guard<std::mutex> critical(m_mutex);
1322 channels = m_channels;
1323 epg = m_epg;
1324 }
1325
1326 const auto channel_i = std::find_if(channels->cbegin(), channels->cend(), [&timer] (const Channel & ch) { return ch.iUniqueId == timer.GetClientChannelUid(); });
1327 if (channel_i == channels->cend())
1328 {
1329 kodi::Log(ADDON_LOG_ERROR, "%s - channel not found", __FUNCTION__);
1330 return PVR_ERROR_SERVER_ERROR;
1331 }
1332 const auto epg_channel_i = epg->find(channel_i->strId);
1333 if (epg_channel_i == epg->cend())
1334 {
1335 kodi::Log(ADDON_LOG_ERROR, "%s - epg channel not found", __FUNCTION__);
1336 return PVR_ERROR_SERVER_ERROR;
1337 }
1338
1339 const auto epg_i = epg_channel_i->second.epg.find(timer.GetStartTime());
1340 if (epg_i == epg_channel_i->second.epg.cend())
1341 {
1342 kodi::Log(ADDON_LOG_ERROR, "%s - event not found", __FUNCTION__);
1343 return PVR_ERROR_SERVER_ERROR;
1344 }
1345
1346 const EpgEntry & epg_entry = epg_i->second;
1347 std::string record_id;
1348 if (m_manager.addTimer(epg_entry.strEventId, record_id))
1349 {
1350 // update the record_id into EPG
1351 // Note: the m_epg/epg is read-only, so the keys must exist
1352 auto epg_copy = std::make_shared<epg_container_t>(*epg);
1353 (*epg_copy)[channel_i->strId].epg[timer.GetStartTime()].strRecordId = record_id;
1354 {
1355 std::lock_guard<std::mutex> critical(m_mutex);
1356 m_epg = epg_copy;
1357 }
1358 SetLoadRecordings();
1359 return PVR_ERROR_NO_ERROR;
1360 }
1361 return PVR_ERROR_SERVER_ERROR;
1362 }
1363
1364 PVR_ERROR Data::DeleteRecording(const kodi::addon::PVRRecording& recording)
1365 {
1366 if (m_manager.deleteRecord(recording.GetRecordingId()))
1367 {
1368 SetLoadRecordings();
1369 return PVR_ERROR_NO_ERROR;
1370 }
1371 return PVR_ERROR_SERVER_ERROR;
1372 }
1373
1374 PVR_ERROR Data::DeleteTimer(const kodi::addon::PVRTimer& timer, bool forceDelete)
1375 {
1376 if (m_manager.deleteRecord(std::to_string((timer.GetClientIndex()))))
1377 {
1378 SetLoadRecordings();
1379 return PVR_ERROR_NO_ERROR;
1380 }
1381 return PVR_ERROR_SERVER_ERROR;
1382 }
1383
1384 PVR_ERROR Data::GetDriveSpace(uint64_t& total, uint64_t& used)
1385 {
1386 {
1387 std::lock_guard<std::mutex> critical(m_mutex);
1388 total = m_recordingAvailableDuration;
1389 used = m_recordingRecordedDuration;
1390 }
1391 return PVR_ERROR_NO_ERROR;
1392 }
1393
1394 bool Data::LoggedIn() const
1395 {
1396 return m_manager.loggedIn();
1397 }
1398
1399 std::vector<kodi::addon::PVRStreamProperty> Data::StreamProperties(const std::string & url, const std::string & streamType, bool isDrm, bool isLive) const
1400 {
1401 static const std::set<std::string> ADAPTIVE_TYPES = {"mpd", "ism", "hls"};
1402
1403 std::vector<kodi::addon::PVRStreamProperty> properties;
1404 properties.emplace_back(PVR_STREAM_PROPERTY_STREAMURL, url);
1405 if (m_useAdaptive && 0 < ADAPTIVE_TYPES.count(streamType))
1406 {
1407 properties.emplace_back(PVR_STREAM_PROPERTY_INPUTSTREAM, "inputstream.adaptive");
1408 properties.emplace_back("inputstream.adaptive.live_delay", "30");
1409 if (isDrm)
1410 {
1411 decltype (m_drmCertificate) certificate;
1412 decltype (m_drmLicenseUrl) licenseUrl;
1413 {
1414 std::lock_guard<std::mutex> critical(m_mutex);
1415 certificate = m_drmCertificate;
1416 licenseUrl = m_drmLicenseUrl;
1417 }
1418 properties.emplace_back("inputstream.adaptive.license_type", "com.widevine.alpha");
1419 properties.emplace_back("inputstream.adaptive.server_certificate", *certificate);
1420 std::string license_url{*licenseUrl};
1421 license_url += ApiManager::urlEncode(base64::to_base64(url));
1422 properties.emplace_back("inputstream.adaptive.license_key", license_url);
1423 }
1424 }
1425 if (isLive)
1426 properties.emplace_back(PVR_STREAM_PROPERTY_ISREALTIMESTREAM, "true");
1427 return properties;
1428 }
1429
1430 std::string Data::ChannelsList() const
1431 {
1432 decltype (m_channels) channels;
1433 {
1434 std::lock_guard<std::mutex> critical(m_mutex);
1435 channels = m_channels;
1436 }
1437 std::ostringstream os;
1438 bool first = true;
1439 std::for_each(channels->cbegin(), channels->cend(), [&os, &first] (channel_container_t::const_reference chan)
1440 {
1441 if (first)
1442 first = false;
1443 else
1444 os << ",";
1445 os << chan.strId;
1446 });
1447 return os.str();
1448 }
1449
1450 std::string Data::ChannelStreamType(const std::string & channelId) const
1451 {
1452 decltype (m_channels) channels;
1453 {
1454 std::lock_guard<std::mutex> critical(m_mutex);
1455 channels = m_channels;
1456 }
1457
1458 std::string stream_type = "unknown";
1459 auto channel_i = std::find_if(channels->cbegin(), channels->cend(), [&channelId] (const Channel & c) { return c.strId == channelId; });
1460 if (channels->cend() == channel_i)
1461 kodi::Log(ADDON_LOG_INFO, "%s can't find channel %s", __FUNCTION__, channelId.c_str());
1462 else
1463 stream_type = channel_i->strStreamType;
1464 return stream_type;
1465 }
1466
1467 bool Data::PinCheckUnlock(bool isPinLocked, bool & unlockedNow)
1468 {
1469 unlockedNow = false;
1470 if (!isPinLocked)
1471 return true;
1472
1473 if (!m_manager.pinUnlocked())
1474 {
1475 std::string pin;
1476 if (kodi::gui::dialogs::Numeric::ShowAndGetNumber(pin, kodi::addon::GetLocalizedString(30202)))
1477 {
1478 if (!m_manager.pinUnlock(pin))
1479 {
1480 kodi::Log(ADDON_LOG_ERROR, "PIN-unlocking failed");
1481 return false;
1482 }
1483 unlockedNow = true;
1484 SetLoadPlaylist();
1485 WaitForChannels();
1486 } else
1487 {
1488 kodi::Log(ADDON_LOG_ERROR, "PIN-entering cancelled");
1489 return false;
1490 }
1491 }
1492 // unlocking can lead to unlock of recordings
1493 SetLoadRecordings();
1494 return true;
1495 }
1496
1497 } // namespace sledovanitvcz