/
VBox.cpp
1268 lines (1059 loc) · 38.8 KB
/
VBox.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015 Sam Stenvall
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "VBox.h"
#include <string>
#include <sstream>
#include <chrono>
#include <algorithm>
#include "p8-platform/util/timeutils.h"
#include "../client.h"
#include "../compat.h"
#include "ContentIdentifier.h"
#include "Exceptions.h"
#include "Utilities.h"
#include "response/Factory.h"
#include "request/Request.h"
#include "request/ApiRequest.h"
#include "request/FileRequest.h"
#include "response/Content.h"
#include "../xmltv/Utilities.h"
using namespace ADDON;
using namespace vbox;
const char * VBox::MINIMUM_SOFTWARE_VERSION = "2.48";
const time_t STREAMING_STATUS_UPDATE_INTERVAL = 10;
const int CHANNELS_PER_CHANNELBATCH = 100;
const int CHANNELS_PER_EPGBATCH = 10;
const size_t VBOX_LOG_BUFFER = 16384;
VBox::VBox(const Settings &settings)
: m_settings(settings), m_currentChannel(nullptr), m_categoryGenreMapper(nullptr), m_shouldSyncEpg(false), m_reminderManager(nullptr),
m_lastStreamStatus({ChannelStreamingStatus(), time(nullptr)})
{
}
VBox::~VBox()
{
// Wait for the background thread to stop
m_active = false;
if (m_backgroundThread.joinable())
m_backgroundThread.join();
}
void VBox::Initialize()
{
// Determine which connection parameters should be used
DetermineConnectionParams();
// Query the software version, we need a few elements from that response
request::ApiRequest versionRequest("QuerySwVersion");
response::ResponsePtr response = PerformRequest(versionRequest);
response::Content versionContent(response->GetReplyElement());
// Query the board info, we need some elements from that as well
request::ApiRequest boardRequest("QueryBoardInfo");
response::ResponsePtr boardResponse = PerformRequest(boardRequest);
response::Content boardInfo(boardResponse->GetReplyElement());
// Construct the model string
std::string model = versionContent.GetString("Custom"); // VBox
model += " " + versionContent.GetString("DeviceType"); // e.g. XTI
model += " " + boardInfo.GetString("ProductNumber"); // e.g. 3352
Log(LOG_INFO, "device information: ");
Log(LOG_INFO, std::string(" model: " + model).c_str());
Log(LOG_INFO, std::string(" hardware revision: " + boardInfo.GetString("HWRev")).c_str());
Log(LOG_INFO, std::string(" firmware revision: " + boardInfo.GetString("FWRev")).c_str());
Log(LOG_INFO, std::string(" uboot version: " + boardInfo.GetString("UbootVersion")).c_str());
Log(LOG_INFO, std::string(" kernel version: " + boardInfo.GetString("KernelVersion")).c_str());
Log(LOG_INFO, std::string(" software version: " + boardInfo.GetString("SoftwareVersion")).c_str());
Log(LOG_INFO, std::string(" number of tuners: " + compat::to_string(boardInfo.GetInteger("TunersNumber"))).c_str());
// Construct backend information
m_backendInformation.name = model;
m_backendInformation.version = SoftwareVersion::ParseString(boardInfo.GetString("SoftwareVersion"));
// Check that the backend uses a compatible software version
if (m_backendInformation.version < SoftwareVersion::ParseString(MINIMUM_SOFTWARE_VERSION))
{
std::string error = std::string("Firmware version ") +
MINIMUM_SOFTWARE_VERSION + " or higher is required";
throw FirmwareVersionException(error);
}
// Query external media status. The request will error if no external media
// is attached
try {
request::ApiRequest mediaRequest("QueryExternalMediaStatus");
response::ResponsePtr mediaResponse = PerformRequest(mediaRequest);
response::Content mediaStatus = response::Content(mediaResponse->GetReplyElement());
ExternalMediaStatus externalMediaStatus;
externalMediaStatus.present = true;
externalMediaStatus.spaceTotal = static_cast<int64_t>(mediaStatus.GetInteger("TotalMem")) * 1048576;
externalMediaStatus.spaceUsed = static_cast<int64_t>(mediaStatus.GetInteger("UsedMem")) * 1048576;
m_backendInformation.externalMediaStatus = externalMediaStatus;
}
catch (VBoxException &e)
{
LogException(e);
}
// Query the timezone offset used
request::ApiRequest timezoneRequest("QuerySystemTime");
timezoneRequest.AddParameter("TimeFormat", "XMLTV");
response::ResponsePtr timezoneResponse = PerformRequest(timezoneRequest);
response::Content timezoneInfo(timezoneResponse->GetReplyElement());
std::string timestamp = timezoneInfo.GetString("Time");
m_backendInformation.timezoneOffset = ::xmltv::Utilities::GetTimezoneOffset(timestamp);
// Consider the addon initialized
m_stateHandler.EnterState(StartupState::INITIALIZED);
// Start the background updater thread
m_active = true;
m_backgroundThread = std::thread([this]()
{
BackgroundUpdater();
});
}
void VBox::DetermineConnectionParams()
{
// Attempt to perform a request using the internal connection parameters
m_currentConnectionParameters = m_settings.m_internalConnectionParams;
try {
request::ApiRequest request("QuerySwVersion");
request.SetTimeout(m_currentConnectionParameters.timeout);
PerformRequest(request);
}
catch (VBoxException&)
{
// Retry the request with the external parameters
if (m_settings.m_externalConnectionParams.AreValid())
{
Log(LOG_INFO, "Unable to connect using internal connection settings, trying with external");
m_currentConnectionParameters = m_settings.m_externalConnectionParams;
request::ApiRequest request("QuerySwVersion");
request.SetTimeout(m_currentConnectionParameters.timeout);
PerformRequest(request);
}
}
auto ¶ms = m_currentConnectionParameters;
Log(LOG_INFO, "Connection parameters used: ");
Log(LOG_INFO, " Hostname: %s", params.hostname.c_str());
if (params.UseHttps())
Log(LOG_INFO, " HTTPS port: %d", params.httpsPort);
else
Log(LOG_INFO, " HTTP port: %d", params.httpPort);
Log(LOG_INFO, " UPnP port: %d", params.upnpPort);
}
void VBox::InitScanningEPG(std::string &rScanMethod, std::string &rGetStatusMethod, std::string &rfIsScanningFlag)
{
// determine wether the device is in External XMLTV mode (internal, not through Kodi definitions)
SendScanEPG(rScanMethod);
GetEpgDetectionState(rGetStatusMethod, rfIsScanningFlag);
// if state is not collecting EPG - we're not in External XMLTV so
// try the Live Signal mode syncing methods. If not - keep External XMLTV methods
if (m_epgScanState != EPGSCAN_SCANNING)
{
// send EPG scanning request (live signal)
rScanMethod = "ScanEPG";
SendScanEPG(rScanMethod);
rGetStatusMethod = "QueryEpgDetectionStatus";
rfIsScanningFlag = "IsInDetection";
}
// set EPG scan state
m_epgScanState = EPGSCAN_SCANNING;
}
void VBox::UpdateEpgScan(bool fRetrieveGuide)
{
static std::string scanEpgMethod("SyncExternalXMLTVChannels");
static std::string epgStatusCheckMethod("QueryExternalXMLTVSyncStatus");
static std::string epgStatusCheckFlag("SyncInProgress");
switch (m_epgScanState)
{
case EPGSCAN_SHOULD_SCAN:
// find the correct methods for the guide's External XMLTV / Live Signal mode
InitScanningEPG(scanEpgMethod, epgStatusCheckMethod, epgStatusCheckFlag);
case EPGSCAN_SCANNING:
case EPGSCAN_FINISHED:
if (fRetrieveGuide)
{
// check for EPG detection state
GetEpgDetectionState(epgStatusCheckMethod, epgStatusCheckFlag);
// retrieve guide periodically (or when finished)
RetrieveGuide();
// if done detecting EPG - change flag to false
if (m_epgScanState == EPGSCAN_FINISHED)
{
XBMC->QueueNotification(ADDON::QUEUE_INFO, "EPG scanned and synced with guide");
m_epgScanState = EPGSCAN_NO_SCAN;
}
}
}
}
void VBox::RetrieveReminders()
{
// Abort if we're already initialized
if (!m_reminderManager)
{
Log(LOG_INFO, "Loading reminders manager");
m_reminderManager = ReminderManagerPtr(new ReminderManager());
try {
m_reminderManager->Initialize();
}
catch (VBoxException &e)
{
LogException(e);
Log(LOG_INFO, "Failed to load the reminders XML");
return;
}
}
m_reminderManager->Load();
}
ReminderPtr VBox::GetActiveReminder()
{
// check if reminder needed now
return m_reminderManager->GetReminderToPop(time(nullptr));
}
void VBox::DisplayReminder(const ReminderPtr &reminder)
{
GUI->Dialog_OK_ShowAndGetInput("Program reminder", std::string(reminder->GetReminderText()).c_str());
}
void VBox::BackgroundUpdater()
{
// Keep count of how many times the loop has run so we can perform some
// tasks only on some iterations
static unsigned int lapCounter = 1;
// Retrieve everything in order once before starting the loop, without
// triggering the event handlers
RetrieveChannels(false);
RetrieveReminders();
InitializeGenreMapper();
RetrieveRecordings(false);
RetrieveGuide(false);
if (m_settings.m_useExternalXmltv)
{
RetrieveExternalGuide();
InitializeChannelMapper();
// Retrieve the channels again if the user prefers external channel icons
if (m_settings.m_useExternalXmltvIcons)
RetrieveChannels();
}
while (m_active)
{
// check for reminders each iteration
ReminderPtr reminder = GetActiveReminder();
if (reminder)
{
DisplayReminder(reminder);
m_reminderManager->DeleteNextReminder();
}
// Update recordings every 12 iterations = 1 minute
if (lapCounter % 12 == 0)
RetrieveRecordings();
// Update channels every six iterations = 30 seocnds
if (lapCounter % 6 == 0)
RetrieveChannels();
// if supposed to scan EPG - send scan API and get guide every 5 minutes, until done scanning
if (m_epgScanState != EPGSCAN_NO_SCAN)
UpdateEpgScan(lapCounter % (12 * 5) == 0);
// one-time guide retrieval (from PVR manager settings)
else if (m_shouldSyncEpg)
{
if (m_settings.m_useExternalXmltv)
RetrieveExternalGuide();
RetrieveGuide();
m_shouldSyncEpg = false;
}
// if not collecting/syncing user's EPG - update the internal guide data every 12 * 60 iterations = 1 hour
else if (lapCounter % (12 * 60) == 0)
RetrieveGuide();
// Update the external guide data every 12 * 60 * 12 = 12 hours
if (m_settings.m_useExternalXmltv && lapCounter % (12 * 60 * 12) == 0)
RetrieveExternalGuide();
lapCounter++;
usleep(5000 * 1000); // for some infinitely retarded reason, std::thread::sleep_for doesn't work
}
}
bool VBox::ValidateSettings() const
{
// Check connection settings
if (!m_settings.m_internalConnectionParams.AreValid())
return false;
// Check guide settings
if (m_settings.m_useExternalXmltv && m_settings.m_externalXmltvPath.empty())
return false;
// Check timeshift settings
if (m_settings.m_timeshiftEnabled && !XBMC->CanOpenDirectory(m_settings.m_timeshiftBufferPath.c_str()))
return false;
return true;
}
const Settings& VBox::GetSettings() const
{
return m_settings;
}
const ConnectionParameters& VBox::GetConnectionParams() const
{
return m_currentConnectionParameters;
}
StartupStateHandler& VBox::GetStateHandler()
{
return m_stateHandler;
}
std::string VBox::GetBackendName() const
{
if (m_stateHandler.WaitForState(StartupState::INITIALIZED))
return m_backendInformation.name;
return "";
}
std::string VBox::GetBackendHostname() const
{
return m_currentConnectionParameters.hostname;
}
std::string VBox::GetBackendVersion() const
{
if (m_stateHandler.WaitForState(StartupState::INITIALIZED))
return m_backendInformation.version.GetString();
return "";
}
std::string VBox::GetConnectionString() const
{
std::stringstream ss;
ss << GetBackendHostname() << ":" << m_currentConnectionParameters.httpPort;
return ss.str();
}
int VBox::GetChannelsAmount() const
{
m_stateHandler.WaitForState(StartupState::CHANNELS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
return m_channels.size();
}
const std::vector<ChannelPtr>& VBox::GetChannels() const
{
m_stateHandler.WaitForState(StartupState::CHANNELS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
return m_channels;
}
const ChannelPtr VBox::GetChannel(unsigned int uniqueId) const
{
m_stateHandler.WaitForState(StartupState::CHANNELS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
auto it = std::find_if(m_channels.cbegin(), m_channels.cend(), [uniqueId](const ChannelPtr &channel) {
return uniqueId == ContentIdentifier::GetUniqueId(channel);
});
if (it == m_channels.cend())
return nullptr;
return *it;
}
const ChannelPtr VBox::GetCurrentChannel() const
{
return m_currentChannel;
}
void VBox::SetCurrentChannel(const ChannelPtr &channel)
{
m_currentChannel = channel;
}
bool VBox::AddReminder(const ChannelPtr &channel, const ::xmltv::ProgrammePtr &programme)
{
return m_reminderManager->AddReminder(channel, programme, m_settings.m_remindMinsBeforeProg);
}
bool VBox::AddReminder(const ChannelPtr &channel, time_t startTime, std::string &progName)
{
return m_reminderManager->AddReminder(channel, startTime, progName, m_settings.m_remindMinsBeforeProg);
}
bool VBox::DeleteChannelReminders(const ChannelPtr &channel)
{
return m_reminderManager->DeleteChannelReminders(channel);
}
bool VBox::DeleteProgramReminders(unsigned int epgUid)
{
return m_reminderManager->DeleteProgramReminders(epgUid);
}
void VBox::StartEPGScan()
{
m_epgScanState = EPGSCAN_SHOULD_SCAN;
}
void VBox::SyncEPGNow()
{
m_shouldSyncEpg = true;
}
void VBox::SendScanEPG(std::string &rEpgDetectionCheckMethod) const
{
// call method to send EPG detection command
request::ApiRequest request(rEpgDetectionCheckMethod);
request.AddParameter("ChannelID", "All");
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
}
void VBox::GetEpgDetectionState(std::string &methodName, std::string &flagName)
{
// call method to check EPG detection status
request::ApiRequest request(methodName);
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
// set flag using a YES/NO flag
std::string isInlDetection = content.GetString(flagName);
m_epgScanState = (isInlDetection == "YES")? EPGSCAN_SCANNING : EPGSCAN_FINISHED;
}
void VBox::SetChannelStreamingStatus(const ChannelPtr &channel)
{
ChannelStreamingStatus status;
request::ApiRequest request("QueryChannelStreamingStatus");
request.AddParameter("ChannelID", channel->m_xmltvName);
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
// Only attempt to parse the status if streaming is active
std::string active = content.GetString("Active");
if (active == "YES")
{
status.m_active = true;
status.SetServiceId(content.GetUnsignedInteger("SID"));
status.SetTunerId(content.GetString("TunerID"));
status.SetTunerType(content.GetString("TunerType"));
status.m_lockStatus = content.GetString("LockStatus");
status.m_lockedMode = content.GetString("LockedMode");
status.m_modulation = content.GetString("Modulation");
status.m_frequency = content.GetString("Frequency");
status.SetRfLevel(content.GetString("RFLevel"));
status.m_signalQuality = content.GetUnsignedInteger("SignalQuality");
status.SetBer(content.GetString("BER"));
}
m_lastStreamStatus.m_streamStatus = status;
m_lastStreamStatus.m_timestamp = time(nullptr);
}
ChannelStreamingStatus VBox::GetChannelStreamingStatus(const ChannelPtr &channel)
{
time_t lastUpdateTime = m_lastStreamStatus.m_timestamp;
time_t currTime(time(nullptr));
if (currTime - lastUpdateTime >= STREAMING_STATUS_UPDATE_INTERVAL)
SetChannelStreamingStatus(channel);
return m_lastStreamStatus.m_streamStatus;
}
bool VBox::SupportsRecordings() const
{
return m_backendInformation.externalMediaStatus.present;
}
int64_t VBox::GetRecordingTotalSpace() const
{
return m_backendInformation.externalMediaStatus.spaceTotal;
}
int64_t VBox::GetRecordingUsedSpace() const
{
return m_backendInformation.externalMediaStatus.spaceUsed;
}
int VBox::GetRecordingsAmount() const
{
m_stateHandler.WaitForState(StartupState::RECORDINGS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
return std::count_if(m_recordings.begin(), m_recordings.end(), [](const RecordingPtr &recording) {
return recording->IsRecording();
});
}
request::ApiRequest VBox::CreateDeleteRecordingRequest(const RecordingPtr &recording) const
{
RecordingState state = recording->GetState();
unsigned int idToDelete = (recording->m_seriesId > 0)? recording->m_seriesId : recording->m_id;
// Determine the request method to use. If a recording is active we want to
// cancel it instead of deleting it
std::string requestMethod = "DeleteRecord";
if (state == RecordingState::RECORDING)
requestMethod = "CancelRecord";
// Create the request
request::ApiRequest request(requestMethod);
// Determine request parameters
request.AddParameter("RecordID", idToDelete);
if (state == RecordingState::EXTERNAL)
request.AddParameter("FileName", recording->m_filename);
return request;
}
request::ApiRequest VBox::CreateDeleteSeriesRequest(const SeriesRecordingPtr &series) const
{
Log(LOG_DEBUG, "Removing series with ID %d", series->m_id);
// For a series, CancelRecord cancels next episodes, and if there's a current
// episode being recorded, it is stopped
std::string requestMethod = "CancelRecord";
// Create the request
request::ApiRequest request(requestMethod);
// Determine request parameters
request.AddParameter("RecordID", series->m_id);
return request;
}
bool VBox::DeleteRecordingOrTimer(unsigned int id)
{
m_stateHandler.WaitForState(StartupState::RECORDINGS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
// The request fails if the item doesn't exist
try {
// Find the recording/timer - look for a single recording
auto it = std::find_if(m_recordings.begin(), m_recordings.end(),
[id](const RecordingPtr &recording)
{
return id == recording->m_id;
});
// if it matches a single recording - create and send delete request for recording
if (it != m_recordings.cend())
{
request::ApiRequest request = CreateDeleteRecordingRequest(*it);
PerformRequest(request);
// remove recording object from memory
m_recordings.erase(it);
}
// if id doesn't match a recording, it's a series
else
{
// look for a series with that ID and throw exception if not found
auto seriesItr = std::find_if(m_series.begin(), m_series.end(),
[id](const SeriesRecordingPtr &series)
{
return id == series->m_id;
});
if (seriesItr != m_series.end())
{
// create and send cancel request for that series recording
request::ApiRequest request = CreateDeleteSeriesRequest(*seriesItr);
PerformRequest(request);
// remove series object from memory
m_series.erase(seriesItr);
}
else
{
throw vbox::RequestFailedException("Could not find timer's ID in backend");
}
}
// Fire events
OnRecordingsUpdated();
OnTimersUpdated();
return true;
}
catch (VBoxException &e)
{
LogException(e);
}
return false;
}
const RecordingMargins VBox::GetRecordingMargins(bool fBackendSingleMargin) const
{
RecordingMargins margins;
memset(&margins, 0, sizeof(margins));
// get recording margins
request::ApiRequest request("GetRecordingsTimeOffset");
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
// If version < 2.57, there is one margin (for both before & after the program).
// In that case, get the margin for both before/after
if (fBackendSingleMargin)
{
margins.m_beforeMargin = content.GetUnsignedInteger("RecordingsTimeOffset");
margins.m_afterMargin = content.GetUnsignedInteger("RecordingsTimeOffset");
}
// Otherwise - get the matching margins
else
{
margins.m_beforeMargin = content.GetUnsignedInteger("MinutesPaddingBefore");
margins.m_afterMargin = content.GetUnsignedInteger("MinutesPaddingAfter");
}
Log(LOG_DEBUG, "GetRecordingMargins(): Current recording margins: %u and %u", margins.m_beforeMargin, margins.m_afterMargin);
return margins;
}
void VBox::SetRecordingMargins(RecordingMargins margins, bool fBackendSingleMargin)
{
request::ApiRequest request("SetRecordingsTimeOffset");
// If version < 2.57, there is a single margin (for both before & after the program).
// In that case, set either margin (they're the same)
if (fBackendSingleMargin)
{
request.AddParameter("RecordingsTimeOffset", margins.m_beforeMargin);
}
// Otherwise, set the matching margins
else
{
request.AddParameter("MinutesPaddingBefore", margins.m_beforeMargin);
request.AddParameter("MinutesPaddingAfter", margins.m_afterMargin);
}
PerformRequest(request);
}
void VBox::UpdateRecordingMargins(RecordingMargins defaultMargins)
{
// get version from backend
SoftwareVersion version(SoftwareVersion::ParseString(m_backendInformation.version.GetString()) );
RecordingMargins updatedMargins;
bool fBackendSingleMargin = true;
// if version < 2.57 (support only for 1 margin), set updated margin for both
// before + after the program times as the larger margin of the timer margins (before / after)
if (version < SoftwareVersion::ParseString("2.57"))
{
unsigned int maxMargin = std::max<unsigned int>(defaultMargins.m_beforeMargin, defaultMargins.m_afterMargin);
updatedMargins.m_beforeMargin = maxMargin;
updatedMargins.m_afterMargin = maxMargin;
}
// otherwise - set each margin as the matching default margin
else
{
updatedMargins.m_beforeMargin = defaultMargins.m_beforeMargin;
updatedMargins.m_afterMargin = defaultMargins.m_afterMargin;
fBackendSingleMargin = false;
}
const RecordingMargins currMargins = GetRecordingMargins(fBackendSingleMargin);
// set the updated margins in backend, if different from the current ones
if (updatedMargins != currMargins)
g_vbox->SetRecordingMargins(updatedMargins, fBackendSingleMargin);
}
void VBox::AddTimer(const ChannelPtr &channel, const ::xmltv::ProgrammePtr programme)
{
// Add the timer
request::ApiRequest request("ScheduleProgramRecord");
request.AddParameter("ChannelID", channel->m_xmltvName);
request.AddParameter("ProgramTitle", programme->m_title);
request.AddParameter("StartTime", programme->m_startTime);
PerformRequest(request);
// Refresh the recordings and timers
RetrieveRecordings();
}
static void AddWeekdays(request::ApiRequest &rRequest, const unsigned int weekdays)
{
if (weekdays & PVR_WEEKDAY_SUNDAY)
{
rRequest.AddParameter("Day", "Sun");
}
if (weekdays & PVR_WEEKDAY_MONDAY)
{
rRequest.AddParameter("Day", "Mon");
}
if (weekdays & PVR_WEEKDAY_TUESDAY)
{
rRequest.AddParameter("Day", "Tue");
}
if (weekdays & PVR_WEEKDAY_WEDNESDAY)
{
rRequest.AddParameter("Day", "Wed");
}
if (weekdays & PVR_WEEKDAY_THURSDAY)
{
rRequest.AddParameter("Day", "Thu");
}
if (weekdays & PVR_WEEKDAY_FRIDAY)
{
rRequest.AddParameter("Day", "Fri");
}
if (weekdays & PVR_WEEKDAY_SATURDAY)
{
rRequest.AddParameter("Day", "Sat");
}
}
void VBox::AddSeriesTimer(const ChannelPtr &channel, const ::xmltv::ProgrammePtr programme)
{
Log(LOG_DEBUG, "Series timer for channel %s, program %s", channel->m_name.c_str(), programme->m_title.c_str());
// Add the timer
request::ApiRequest request("ScheduleProgramRecord");
request.AddParameter("ChannelID", channel->m_xmltvName);
request.AddParameter("ProgramTitle", programme->m_title);
request.AddParameter("StartTime", programme->m_startTime);
request.AddParameter("SeriesRecording", "YES");
PerformRequest(request);
// Refresh the recordings and timers
RetrieveRecordings();
}
void VBox::AddTimer(const ChannelPtr &channel, time_t startTime, time_t endTime,
const std::string title, const std::string description)
{
Log(LOG_DEBUG, "Adding Manual timer for channel %s", channel->m_name.c_str());
// Add the timer
request::ApiRequest request("ScheduleChannelRecord");
request.AddParameter("ChannelID", channel->m_xmltvName);
request.AddParameter("StartTime", CreateTimestamp(startTime));
request.AddParameter("EndTime", CreateTimestamp(endTime));
// Manually set title
request.AddParameter("ProgramName", title);
PerformRequest(request);
// Refresh the recordings and timers
RetrieveRecordings();
}
// implement timer with rule for manually defined series
void VBox::AddTimer(const ChannelPtr &channel, time_t startTime, time_t endTime,
const std::string title, const std::string description, const unsigned int weekdays)
{
Log(LOG_DEBUG, "Manual series timer for channel %s, weekdays = 0x%x", channel->m_name.c_str(), weekdays);
// Add the timer
request::ApiRequest request("ScheduleChannelRecord");
request.AddParameter("ChannelID", channel->m_xmltvName);
request.AddParameter("Periodic", "YES");
request.AddParameter("FromTime", CreateDailyTime(startTime));
request.AddParameter("ToTime", CreateDailyTime(endTime));
// Manually set title
request.AddParameter("ProgramName", title);
AddWeekdays(request, weekdays);
PerformRequest(request);
// Refresh the recordings and timers
RetrieveRecordings();
}
int VBox::GetTimersAmount() const
{
m_stateHandler.WaitForState(StartupState::RECORDINGS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
int count = std::count_if(m_recordings.begin(), m_recordings.end(), [](const RecordingPtr &recording) {
return recording->IsTimer();
});
count += m_series.size();
return count;
}
const std::vector<RecordingPtr>& VBox::GetRecordingsAndTimers() const
{
m_stateHandler.WaitForState(StartupState::RECORDINGS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
return m_recordings;
}
const std::vector<SeriesRecordingPtr>& VBox::GetSeriesTimers() const
{
m_stateHandler.WaitForState(StartupState::RECORDINGS_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
return m_series;
}
const Schedule VBox::GetSchedule(const ChannelPtr &channel) const
{
// Load the schedule from the internal guide
m_stateHandler.WaitForState(StartupState::GUIDE_LOADED);
std::unique_lock<std::mutex> lock(m_mutex);
Schedule schedule;
schedule.schedule = m_guide.GetSchedule(channel->m_xmltvName);
// Try to use the external guide data if a) it's loaded, b) the user prefers
// it or c) if no schedule was found
if (m_stateHandler.GetState() >= StartupState::EXTERNAL_GUIDE_LOADED &&
(m_settings.m_preferExternalXmltv || !schedule.schedule))
{
// Consult the channel mapper to find the corresponding external channel name
std::string mappedName = m_guideChannelMapper->GetExternalChannelName(channel->m_name);
std::string xmltvName = m_externalGuide.GetChannelId(mappedName);
if (!mappedName.empty() && !xmltvName.empty())
{
Log(LOG_DEBUG, "Using external guide data for channel %s", channel->m_name.c_str());
schedule.schedule = m_externalGuide.GetSchedule(xmltvName);
schedule.origin = Schedule::Origin::EXTERNAL_GUIDE;
}
}
return schedule;
}
std::string VBox::GetApiBaseUrl() const
{
std::stringstream ss;
ss << m_currentConnectionParameters.GetUriScheme() << "://";
ss << m_currentConnectionParameters.GetUriAuthority();
ss << "/cgi-bin/HttpControl/HttpControlApp?OPTION=1";
return ss.str();
}
std::string VBox::CreateTimestamp(const time_t unixTimestamp) const
{
std::string tzOffset = m_backendInformation.timezoneOffset;
return ::xmltv::Utilities::UnixTimeToXmltv(unixTimestamp, tzOffset);
}
std::string VBox::CreateDailyTime(const time_t unixTimestamp) const
{
std::string tzOffset = m_backendInformation.timezoneOffset;
return ::xmltv::Utilities::UnixTimeToDailyTime(unixTimestamp, tzOffset);
}
unsigned int VBox::GetDBVersion(std::string &versionName) const
{
// get the backend's database version
request::ApiRequest request("QueryDataBaseVersion");
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
return content.GetUnsignedInteger(versionName);
}
void VBox::RetrieveChannels(bool triggerEvent/* = true*/)
{
try {
std::string channelsDBVerName("ChannelsDataBaseVersion");
unsigned int newDBversion = GetDBVersion(channelsDBVerName);
// if same as last fetched channels, no need for fetching again
if (newDBversion == m_channelsDBVersion)
return;
int lastChannelIndex;
{
request::ApiRequest request("QueryXmltvNumOfChannels");
response::ResponsePtr response = PerformRequest(request);
response::Content content(response->GetReplyElement());
// get number of channels from backend
std::unique_lock<std::mutex> lock(m_mutex);
lastChannelIndex = content.GetUnsignedInteger("NumOfChannels");
}
std::vector<ChannelPtr> allChannels;
// Get channels in batches of 100
for (int fromIndex = 1; fromIndex <= lastChannelIndex; fromIndex += CHANNELS_PER_CHANNELBATCH)
{
// Abort immediately if the addon just got terminated
if (!m_active)
return;
int toIndex = std::min(fromIndex + (CHANNELS_PER_CHANNELBATCH - 1) , lastChannelIndex);
// Swallow exceptions, we don't want channel loading to fail just because
// one request failed
try
{
request::ApiRequest request("GetXmltvChannelsList");
request.AddParameter("FromChIndex", fromIndex);
request.AddParameter("ToChIndex", toIndex);
response::ResponsePtr response = PerformRequest(request);
response::XMLTVResponseContent content(response->GetReplyElement());
auto channels = content.GetChannels();
// Optionally swap the channel icons for the ones in the external guide
if (m_settings.m_useExternalXmltvIcons &&
m_stateHandler.GetState() >= StartupState::EXTERNAL_GUIDE_LOADED)
{
SwapChannelIcons(channels);
}
// Add the batch to all channels
allChannels.insert(allChannels.end(), channels.begin(), channels.end());
}
catch (VBoxException &e)
{
LogException(e);
}
}
// Swap and notify if the contents have changed
if (!utilities::deref_equals(m_channels, allChannels))
{
std::unique_lock<std::mutex> lock(m_mutex);
m_channels = allChannels;
Log(LOG_INFO, "Channels database version updated to %u", newDBversion);
m_channelsDBVersion = newDBversion;
if (triggerEvent)
OnChannelsUpdated();
}
}
catch (VBoxException &e)
{
LogException(e);
return;
}
if (m_stateHandler.GetState() < StartupState::CHANNELS_LOADED)
m_stateHandler.EnterState(StartupState::CHANNELS_LOADED);
}
void VBox::RetrieveRecordings(bool triggerEvent/* = true*/)
{
// Only attempt to retrieve recordings when external media is present
if (m_backendInformation.externalMediaStatus.present)