/
addon.cpp
4897 lines (3789 loc) · 189 KB
/
addon.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) 2016-2022 Michael G. Brehm
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------
#include "stdafx.h"
#include "addon.h"
#include <assert.h>
#include <chrono>
#include <functional>
#include <kodi/Filesystem.h>
#include <kodi/General.h>
#include <kodi/gui/dialogs/OK.h>
#include <kodi/gui/dialogs/FileBrowser.h>
#include <kodi/gui/dialogs/Select.h>
#include <kodi/gui/dialogs/TextViewer.h>
#include <sstream>
#include <version.h>
#ifdef __ANDROID__
#include <android/log.h>
#endif
#if defined(_WINDOWS) || defined(WINAPI_FAMILY)
#include <netlistmgr.h>
#else
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#endif
#include "database.h"
#include "devicestream.h"
#include "httpstream.h"
#include "radiofilter.h"
#include "string_exception.h"
#include "sqlite_exception.h"
#pragma warning(push, 4)
// Addon Entry Points
//
ADDONCREATOR(addon)
// Scheduled Task Names
//
char const* addon::PROXY_CHANGED_TASK = "proxy_changed_task";
char const* addon::PUSH_LISTINGS_TASK = "push_listings_task";
char const* addon::UPDATE_DEVICES_TASK = "update_devices_task";
char const* addon::UPDATE_EPISODES_TASK = "update_episodes_task";
char const* addon::UPDATE_LINEUPS_TASK = "update_lineups_task";
char const* addon::UPDATE_LISTINGS_TASK = "update_listings_task";
char const* addon::UPDATE_RECORDINGRULES_TASK = "update_recordingrules_task";
char const* addon::UPDATE_RECORDINGS_TASK = "update_recordings_task";
//---------------------------------------------------------------------------
// addon Instance Constructor
//
// Arguments:
//
// NONE
addon::addon() : m_discovered_devices{ false },
m_discovered_episodes{ false },
m_discovered_lineups{ false },
m_discovered_listings{ false },
m_discovered_recordingrules{ false },
m_discovered_recordings{ false },
m_epgmaxtime{ EPG_TIMEFRAME_UNLIMITED },
m_randomengine(static_cast<unsigned int>(time(nullptr))),
m_scheduler([&](std::exception const& ex) -> void { handle_stdexception("scheduled task", ex); }),
m_settings{},
m_startup_complete{ false },
m_stream_starttime(0),
m_stream_endtime(0),
m_useproxy{ false } {}
//---------------------------------------------------------------------------
// addon Destructor
addon::~addon()
{
// There is no corresponding "Destroy" method in CAddonBase, only the class
// destructor will be invoked; to keep the implementation pieces near each
// other, perform the tear-down in a helper function
Destroy();
}
//---------------------------------------------------------------------------
// addon::copy_settings (private, inline)
//
// Atomically creates a copy of the member addon_settings structure
//
// Arguments:
//
// NONE
inline struct settings addon::copy_settings(void) const
{
std::unique_lock<std::mutex> settings_lock(m_settings_lock);
return m_settings;
}
//---------------------------------------------------------------------------
// addon::discover_devices (private)
//
// Helper function used to execute a backend device discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_devices(scalar_condition<bool> const& /*cancel*/, bool& changed)
{
changed = false; // Initialize [ref] argument
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
// Create a copy of the current addon settings structure
struct settings settings = copy_settings();
log_info_if(trace, __func__, ": initiated local network device discovery (method: ", settings.use_http_device_discovery ? "http" : "broadcast", ")");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// Clear any invalid device authorization strings present in the existing discovery data
clear_authorization_strings(dbhandle, settings.deviceauth_stale_after);
// Discover the devices on the local network and check for changes
auto caller = __func__;
::discover_devices(dbhandle, settings.use_http_device_discovery, changed);
// Log the device information if starting up or changes were detected
if(trace || changed) {
enumerate_device_names(dbhandle, [&](struct device_name const& device_name) -> void { log_info(caller, ": discovered: ", device_name.name); });
log_warning_if(!has_storage_engine(dbhandle), __func__, ": no storage engine devices were discovered; recording discovery is disabled");
log_warning_if(!has_dvr_authorization(dbhandle), __func__, ": no tuners with a valid DVR authorization were discovered; recording rule and electronic program guide discovery are disabled");
}
// Set the discovery time for the device information
set_discovered(dbhandle, "devices", time(nullptr));
m_discovered_devices = true; // Set the scalar_condition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_devices = true; throw; }
}
//---------------------------------------------------------------------------
// addon::discover_episodes (private)
//
// Helper function used to execute a backend recording rule episode discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_episodes(scalar_condition<bool> const&, bool& changed)
{
changed = false; // Initialize [ref] argument
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated recording rule episode discovery");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// This operation is only available when there is at least one DVR authorized tuner
std::string authorization = get_authorization_strings(dbhandle, true);
// Discover the recording rule episode information associated with all of the authorized devices
if(authorization.length() != 0) ::discover_episodes(dbhandle, authorization.c_str(), changed);
else log_info_if(trace, __func__, ": no tuners with valid DVR authorization were discovered; skipping recording rule episode discovery");
// Set the discovery time for the episode information
set_discovered(dbhandle, "episodes", time(nullptr));
m_discovered_episodes = true; // Set the scalar_condition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_episodes = true; throw; }
}
//---------------------------------------------------------------------------
// addon::discover_lineups (private)
//
// Helper function used to execute a backend channel lineup discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_lineups(scalar_condition<bool> const&, bool& changed)
{
changed = false; // Initialize [ref] argument
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated local tuner device lineup discovery");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// Execute the channel lineup discovery operation
::discover_lineups(dbhandle, changed);
// Set the discovery time for the lineup information
set_discovered(dbhandle, "lineups", time(nullptr));
m_discovered_lineups = true; // Set the scalar_condition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_lineups = true; throw; }
}
//---------------------------------------------------------------------------
// addon::discover_listings (private)
//
// Helper function used to execute a backend listing discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_listings(scalar_condition<bool> const&, bool& changed)
{
changed = true; // Initialize [ref] argument
// Create a copy of the current addon settings structure
struct settings settings = copy_settings();
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated listing discovery");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// This operation is only available when there is at least one DVR authorized tuner, but
// lineup data for any unauthorized tuner(s) can also be retrieved
if(has_dvr_authorization(dbhandle)) {
std::string authorization = get_authorization_strings(dbhandle, false);
if(authorization.length() != 0) ::discover_listings(dbhandle, authorization.c_str(), changed);
}
else log_info_if(trace, __func__, ": no tuners with valid DVR authorization were discovered; skipping listing discovery");
// Set the discovery time for the listing information
set_discovered(dbhandle, "listings", time(nullptr));
m_discovered_listings = true; // Set the scalar_condition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_listings = true; throw; }
}
//---------------------------------------------------------------------------
// addon::discover_mappings (private)
//
// Helper function used to execute a channel mapping discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_mappings(scalar_condition<bool> const&, bool& changed)
{
channelranges_t cable_mappings; // Discovered radio mappings
channelranges_t ota_mappings; // Discovered radio mappings
changed = false; // Initialize [ref] argument
// Create a copy of the current addon settings structure
struct settings settings = copy_settings();
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated channel mapping discovery");
// Ignore the operation if the specified file doesn't exist
if(kodi::vfs::FileExists(settings.radio_channel_mapping_file)) {
kodi::vfs::CFile mappingfile;
if(mappingfile.OpenFile(settings.radio_channel_mapping_file)) {
log_info(__func__, ": processing channel mapping file: ", settings.radio_channel_mapping_file);
std::string line; // Current line of text from the file
int linenumber = 0; // Current line number within the file
while(mappingfile.ReadLine(line)) {
++linenumber; // Increment the line number
union channelid start = {}; // Starting channel identifier
union channelid end = {}; // Ending channel identifier
unsigned int start_channel = 0; // Starting channel number
unsigned int start_subchannel = 0; // Starting subchannel number
unsigned int end_channel = 0; // Ending channel number
unsigned int end_subchannel = 0; // Ending subchannel number
// Scan the line using the OTA range format first
int result = sscanf(line.c_str(), "%u.%u-%u.%u", &start_channel, &start_subchannel, &end_channel, &end_subchannel);
// OTA RANGE: CHANNEL.SUBCHANNEL-CHANNEL.SUBCHANNEL
if(result == 4) {
start.parts.channel = start_channel;
start.parts.subchannel = start_subchannel;
end.parts.channel = end_channel;
end.parts.subchannel = end_channel;
ota_mappings.push_back({ start, end });
}
// OTA: CHANNEL.SUBCHANNEL
else if(result == 2) {
start.parts.channel = start_channel;
start.parts.subchannel = start_subchannel;
ota_mappings.push_back({ start, start });
}
// CABLE
else if(result == 1) {
// Rescan the line to detect if this is a single channel or a range
result = sscanf(line.c_str(), "%u-%u", &start_channel, &end_channel);
// CABLE RANGE: CHANNEL-CHANNEL
if(result == 2) {
start.parts.channel = start_channel;
end.parts.channel = end_channel;
cable_mappings.push_back({ start, end });
}
// CABLE: CHANNEL
else if(result == 1) {
start.parts.channel = start_channel;
cable_mappings.push_back({ start, start });
}
}
// If the line failed to parse log an error with the line number for the user
else log_error(__func__, ": invalid channel mapping entry detected at line #", linenumber);
}
mappingfile.Close();
}
else log_error(__func__, ": unable to open channel mapping file: ", settings.radio_channel_mapping_file);
}
std::unique_lock<std::mutex> lock(m_radiomappings_lock);
// Check each of the new channel mapping ranges against the existing ones and swap them if different
bool cable_changed = ((cable_mappings.size() != m_radiomappings_cable.size()) || (!std::equal(cable_mappings.begin(), cable_mappings.end(), m_radiomappings_cable.begin(),
[](channelrange_t const& lhs, channelrange_t const& rhs) { return lhs.first.value == rhs.first.value && lhs.second.value == rhs.second.value; })));
if(cable_changed) m_radiomappings_cable.swap(cable_mappings);
bool ota_changed = ((ota_mappings.size() != m_radiomappings_ota.size()) || (!std::equal(ota_mappings.begin(), ota_mappings.end(), m_radiomappings_ota.begin(),
[](channelrange_t const& lhs, channelrange_t const& rhs) { return lhs.first.value == rhs.first.value && lhs.second.value == rhs.second.value; })));
if(ota_changed) m_radiomappings_ota.swap(ota_mappings);
// Set the changed flag for the caller if either set of channel mappings changed
changed = (cable_changed || ota_changed);
}
//---------------------------------------------------------------------------
// addon::discover_recordingrules (private)
//
// Helper function used to execute a backend recording rule discovery operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_recordingrules(scalar_condition<bool> const&, bool& changed)
{
changed = false; // Initialize [ref] argument
// Create a copy of the current addon settings structure
struct settings settings = copy_settings();
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated recording rule discovery");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// This operation is only available when there is at least one DVR authorized tuner
std::string authorization = get_authorization_strings(dbhandle, true);
if(authorization.length() != 0) {
// Discover the recording rules associated with all authorized devices
::discover_recordingrules(dbhandle, authorization.c_str(), changed);
// Delete all expired recording rules from the backend as part of the discovery operation
enumerate_expired_recordingruleids(dbhandle, settings.delete_datetime_rules_after, [&](unsigned int const& recordingruleid) -> void
{
try { delete_recordingrule(dbhandle, authorization.c_str(), recordingruleid); changed = true; }
catch(std::exception& ex) { handle_stdexception(__func__, ex); }
catch(...) { handle_generalexception(__func__); }
});
}
else log_info_if(trace, __func__, ": no tuners with valid DVR authorization were discovered; skipping recording rule discovery");
// Set the discovery time for the recordingrule information
set_discovered(dbhandle, "recordingrules", time(nullptr));
m_discovered_recordingrules = true; // Set the scalar_condition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_recordingrules = true; throw; }
}
//---------------------------------------------------------------------------
// addon::discover_recordings (private)
//
// Helper function used to execute a backend recordings operation
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
// changed - Reference to a flag indicating that the discovery information has changed
void addon::discover_recordings(scalar_condition<bool> const&, bool& changed)
{
changed = false; // Initialize [ref] argument
// Only produce trace-level logging if the addon is starting up or the data has changed
bool const trace = (m_startup_complete.load() == false);
log_info_if(trace, __func__, ": initiated local storage device recording discovery");
try {
// Pull a database connection out from the connection pool
connectionpool::handle dbhandle(m_connpool);
// Execute the recording discovery operation
::discover_recordings(dbhandle, changed);
// Set the discovery time for the recording information
set_discovered(dbhandle, "recordings", time(nullptr));
m_discovered_recordings = true; // Set the scalar_codition flag
}
// Set the scalar_condition on exception before re-throwing it
catch(...) { m_discovered_recordings = true; throw; }
}
//---------------------------------------------------------------------------
// addon::handle_generalexception (private)
//
// Handler for thrown generic exceptions
//
// Arguments:
//
// function - Name of the function where the exception was thrown
void addon::handle_generalexception(char const* function) const
{
log_error(function, " failed due to an exception");
}
//---------------------------------------------------------------------------
// addon::handle_generalexception (private)
//
// Handler for thrown generic exceptions
//
// Arguments:
//
// function - Name of the function where the exception was thrown
// result - Result code to return
template<typename _result>
_result addon::handle_generalexception(char const* function, _result result) const
{
handle_generalexception(function);
return result;
}
//---------------------------------------------------------------------------
// addon::handle_stdexception (private)
//
// Handler for thrown std::exceptions
//
// Arguments:
//
// function - Name of the function where the exception was thrown
// exception - std::exception that was thrown
void addon::handle_stdexception(char const* function, std::exception const& ex) const
{
log_error(function, " failed due to an exception: ", ex.what());
}
//---------------------------------------------------------------------------
// addon::handle_stdexception (private)
//
// Handler for thrown std::exceptions
//
// Arguments:
//
// function - Name of the function where the exception was thrown
// exception - std::exception that was thrown
// result - Result code to return
template<typename _result>
_result addon::handle_stdexception(char const* function, std::exception const& ex, _result result) const
{
handle_stdexception(function, ex);
return result;
}
//---------------------------------------------------------------------------
// addon::ipv4_network_available (private)
//
// Determines if IPv4 connectivity has been established on the system
//
// Arguments:
//
// NONE
bool addon::ipv4_network_available(void) const
{
#if defined(_WINDOWS) || defined(WINAPI_FAMILY)
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
INetworkListManager* netlistmgr = nullptr;
NLM_CONNECTIVITY connectivity = NLM_CONNECTIVITY_DISCONNECTED;
// Create an instance of the NetworkListManager object
HRESULT hresult = CoCreateInstance(CLSID_NetworkListManager, nullptr, CLSCTX_INPROC_SERVER, IID_INetworkListManager, reinterpret_cast<void**>(&netlistmgr));
if(FAILED(hresult)) throw string_exception(__func__, ": failed to create NetworkListManager instance (hr=", hresult, ")");
// Interrogate the Network List Manager to determine the current network connectivity status
hresult = netlistmgr->GetConnectivity(&connectivity);
netlistmgr->Release();
// If the NetworkListManager returned an error, throw an exception to that effect
if(FAILED(hresult)) throw string_exception(__func__, ": failed to interrogate NetworkListManager connectivity state (hr=", hresult, ")");
// If the status was successfully interrogated, check for the necessary IPv4 connectivity flags
return ((connectivity & (NLM_CONNECTIVITY_IPV4_SUBNET | NLM_CONNECTIVITY_IPV4_LOCALNETWORK | NLM_CONNECTIVITY_IPV4_INTERNET)) != 0);
#else
// This function cannot currently be implemented on non-desktop Windows platforms
return true;
#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#else
const int MAX_INTERFACES = 128;
// Allocate a buffer to hold the interface address information
std::unique_ptr<struct ifreq[]> ifreqs(new struct ifreq[MAX_INTERFACES]);
memset(&ifreqs[0], 0, sizeof(struct ifreq) * MAX_INTERFACES);
// Create a IPv4 TCP socket instance
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(sock == -1) throw string_exception(__func__, ": failed to create socket instance");
// Initialize an ifconf structure to send into ioctl(SIOCGIFCONF)
struct ifconf ifc;
ifc.ifc_len = sizeof(struct ifreq) * MAX_INTERFACES;
ifc.ifc_req = &ifreqs[0];
// Retrieve the interface address information
if(ioctl(sock, SIOCGIFCONF, &ifc) != 0) { close(sock); throw string_exception(__func__, ": ioctl(SIOCGIFCONF) failed"); }
// If the returned length is equal to (or greater than) the original length, there was an overflow
if(ifc.ifc_len >= static_cast<int>(sizeof(struct ifreq) * MAX_INTERFACES)) { close(sock); throw string_exception(__func__, ": ioctl(SIOCGIFCONF) returned more interfaces than have been allowed for"); }
// Set up the head and tail pointers into the array of ifreq structures
struct ifreq* current = ifc.ifc_req;
struct ifreq* end = reinterpret_cast<struct ifreq*>(&ifc.ifc_buf[ifc.ifc_len]);
// Iterate over each ifreq structure and determine if the interface is running
while(current <= end) {
struct sockaddr_in* addrin = reinterpret_cast<struct sockaddr_in*>(¤t->ifr_addr);
// If the interface has a valid IPv4 address, get the active flag information
uint32_t ipaddr = ntohl(addrin->sin_addr.s_addr);
if((ipaddr != 0) && (ioctl(sock, SIOCGIFFLAGS, current) == 0)) {
// If the flag indicate that the interface is both UP and RUNNING, we're done
unsigned int flags = current->ifr_flags & (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_UP | IFF_RUNNING);
if(flags == (IFF_UP | IFF_RUNNING)) { close(sock); return true; }
}
current++; // Move to the next interface in the list
}
close(sock); // Close the socket instance
return false; // No interfaces were both UP and RUNNING
#endif // defined(_WINDOWS) || defined(WINAPI_FAMILY)
}
//---------------------------------------------------------------------------
// addon::is_channel_radio (private)
//
// Determines if a channel has been mapped as a radio channel
//
// Arguments:
//
// lock - Held lock instance
// channelid - Channel identifier to check against the mappings
bool addon::is_channel_radio(std::unique_lock<std::mutex> const& lock, union channelid const& channelid) const
{
assert(lock.owns_lock());
if(!lock.owns_lock()) throw std::invalid_argument("lock");
// CABLE
if(channelid.parts.subchannel == 0) return std::any_of(m_radiomappings_cable.cbegin(), m_radiomappings_cable.cend(),
[&](channelrange_t const& range) { return ((channelid.value >= range.first.value) && (channelid.value <= range.second.value)); });
// OTA
else return std::any_of(m_radiomappings_ota.cbegin(), m_radiomappings_ota.cend(),
[&](channelrange_t const& range) { return ((channelid.value >= range.first.value) && (channelid.value <= range.second.value)); });
}
//---------------------------------------------------------------------------
// addon::log_debug (private)
//
// Variadic method of writing a LOG_DEBUG entry into the Kodi application log
//
// Arguments:
//
// args - Variadic argument list
template<typename... _args>
void addon::log_debug(_args&&... args) const
{
log_message(ADDON_LOG::ADDON_LOG_DEBUG, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_debug_if (private)
//
// Variadic method of writing a LOG_DEBUG entry into the Kodi application log
//
// Arguments:
//
// flag - Flag indicating if the information should be logged
// args - Variadic argument list
template<typename... _args>
void addon::log_debug_if(bool flag, _args&&... args) const
{
if(flag) log_message(ADDON_LOG::ADDON_LOG_DEBUG, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_error (private)
//
// Variadic method of writing a LOG_ERROR entry into the Kodi application log
//
// Arguments:
//
// args - Variadic argument list
template<typename... _args>
void addon::log_error(_args&&... args) const
{
log_message(ADDON_LOG::ADDON_LOG_ERROR, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_error_if (private)
//
// Variadic method of writing a LOG_ERROR entry into the Kodi application log
//
// Arguments:
//
// flag - Flag indicating if the information should be logged
// args - Variadic argument list
template<typename... _args>
void addon::log_error_if(bool flag, _args&&... args) const
{
if(flag) log_message(ADDON_LOG::ADDON_LOG_ERROR, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_info (private)
//
// Variadic method of writing a LOG_INFO entry into the Kodi application log
//
// Arguments:
//
// args - Variadic argument list
template<typename... _args>
void addon::log_info(_args&&... args) const
{
log_message(ADDON_LOG::ADDON_LOG_INFO, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_info_if (private)
//
// Variadic method of writing a LOG_INFO entry into the Kodi application log
//
// Arguments:
//
// flag - Flag indicating if the information should be logged
// args - Variadic argument list
template<typename... _args>
void addon::log_info_if(bool flag, _args&&... args) const
{
if(flag) log_message(ADDON_LOG::ADDON_LOG_INFO, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_message (private)
//
// Variadic method of writing a log entry into the Kodi application log
//
// Arguments:
//
// args - Variadic argument list
template<typename... _args>
void addon::log_message(ADDON_LOG level, _args&&... args) const
{
const size_t MAX_ERROR_LOG = 10; // Maximum entries to store in error log
std::ostringstream stream;
int unpack[] = { 0, (static_cast<void>(stream << std::boolalpha << args), 0) ... };
(void)unpack;
kodi::Log(level, stream.str().c_str());
// Write ADDON_LOG_ERROR level messages to an appropriate secondary log mechanism
if(level == ADDON_LOG::ADDON_LOG_ERROR) {
#if defined(_WINDOWS) || defined(WINAPI_FAMILY)
std::string message = "ERROR: " + stream.str() + "\r\n";
OutputDebugStringA(message.c_str());
#elif __ANDROID__
__android_log_print(ANDROID_LOG_ERROR, VERSION_PRODUCTNAME_ANSI, "ERROR: %s\n", stream.str().c_str());
#else
fprintf(stderr, "ERROR: %s\r\n", stream.str().c_str());
#endif
// Maintain a list of the last MAX_ERROR_LOG error messages that can be exposed
// to the user without needing to reference the Kodi log file
time_t now = time(nullptr);
std::string nowstring(std::string(asctime(localtime(&now))));
nowstring = nowstring.substr(0, nowstring.length() - 1); // Remove \n
std::unique_lock<std::mutex> lock(m_errorlog_lock);
while(m_errorlog.size() >= MAX_ERROR_LOG) m_errorlog.pop_front();
m_errorlog.push_back(stream.str().append(" [").append(nowstring).append("]"));
}
}
//---------------------------------------------------------------------------
// addon::log_warning (private)
//
// Variadic method of writing a LOG_WARNING entry into the Kodi application log
//
// Arguments:
//
// args - Variadic argument list
template<typename... _args>
void addon::log_warning(_args&&... args) const
{
log_message(ADDON_LOG::ADDON_LOG_WARNING, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::log_warning_if (private)
//
// Variadic method of writing a LOG_WARNING entry into the Kodi application log
//
// Arguments:
//
// flag - Flag indicating if the information should be logged
// args - Variadic argument list
template<typename... _args>
void addon::log_warning_if(bool flag, _args&&... args) const
{
if(flag) log_message(ADDON_LOG::ADDON_LOG_WARNING, std::forward<_args>(args)...);
}
//---------------------------------------------------------------------------
// addon::openlivestream_storage_http (private)
//
// Attempts to open a live stream via HTTP from an available storage engine
//
// Arguments:
//
// dbhandle - Active database connection to use
// channelid - Channel identifier
// vchannel - Virtual channel number
std::unique_ptr<pvrstream> addon::openlivestream_storage_http(connectionpool::handle const& dbhandle, union channelid channelid, char const* vchannel) const
{
assert(vchannel != nullptr);
if((vchannel == nullptr) || (*vchannel == '\0')) throw std::invalid_argument("vchannel");
// Generate a vector<> of possible storage device URLs for the virtual channel
std::vector<std::string> streamurls = get_storage_stream_urls(dbhandle, channelid);
if(streamurls.size() == 0) { log_error(__func__, ": unable to generate storage engine stream url(s) for channel ", vchannel); return nullptr; }
// Attempt to create a stream using the URLs in the order provided, there is currently no way to choose priority here
for(auto const& streamurl : streamurls) {
try {
// Start the new HTTP stream using the parameters currently specified by the settings
std::unique_ptr<pvrstream> stream = httpstream::create(streamurl.c_str());
log_info(__func__, ": streaming channel ", vchannel, " via storage engine url ", streamurl.c_str());
return stream;
}
// If the stream creation failed, log an error; do not stop enumerating the available storage devices
catch(std::exception & ex) { log_error(__func__, ": unable to stream channel ", vchannel, " via storage engine url ", streamurl.c_str(), ": ", ex.what()); }
}
return nullptr;
}
//---------------------------------------------------------------------------
// addon::openlivestream_tuner_device (private)
//
// Attempts to open a live stream via RTP/UDP from an available tuner device
//
// Arguments:
//
// dbhandle - Active database connection to use
// channelid - Channel identifier
// vchannel - Virtual channel number
std::unique_ptr<pvrstream> addon::openlivestream_tuner_device(connectionpool::handle const& dbhandle, union channelid channelid, char const* vchannel) const
{
std::vector<struct devicestream::tuner> tuners; // vector<> of possible device tuners for the channel
assert(vchannel != nullptr);
if((vchannel == nullptr) || (*vchannel == '\0')) throw std::invalid_argument("vchannel");
// Create a collection of all the tuners that can possibly stream the requested channel
enumerate_channeltuners(dbhandle, channelid, [&](struct channel_tuner const& item) -> void { tuners.emplace_back(devicestream::tuner{ item.tunerid, item.frequency, item.program }); });
if(tuners.size() == 0) { log_error(__func__, ": unable to find any possible tuner devices to stream channel ", vchannel); return nullptr; }
try {
// Start the new RTP/UDP stream -- devicestream performs its own tuner selection based on the provided collection
std::unique_ptr<pvrstream> stream = devicestream::create(tuners);
log_info(__func__, ": streaming channel ", vchannel, " via tuner device rtp/udp broadcast");
return stream;
}
// If the stream creation failed, log an error and return a null unique_ptr<> back to the caller, do not throw an exception
catch(std::exception& ex) { log_error(__func__, ": unable to stream channel ", vchannel, " via tuner device rtp/udp broadcast: ", ex.what()); }
return nullptr;
}
//---------------------------------------------------------------------------
// addon::openlivestream_tuner_http (private)
//
// Attempts to open a live stream via HTTP from an available tuner device
//
// Arguments:
//
// dbhandle - Active database connection to use
// channelid - Channel identifier
// vchannel - Virtual channel number
std::unique_ptr<pvrstream> addon::openlivestream_tuner_http(connectionpool::handle const& dbhandle, union channelid channelid, char const* vchannel) const
{
std::vector<std::string> tuners; // vector<> of possible device tuners for the channel
assert(vchannel != nullptr);
if((vchannel == nullptr) || (*vchannel == '\0')) throw std::invalid_argument("vchannel");
// Create a collection of all the tuners that can possibly stream the requested channel
enumerate_channeltuners(dbhandle, channelid, [&](struct channel_tuner const& item) -> void { if(item.islegacy == false) tuners.emplace_back(item.tunerid); });
if(tuners.size() == 0) { log_error(__func__, ": unable to find any possible tuner devices to stream channel ", vchannel); return nullptr; }
// A valid tuner device has to be selected from the available options
std::string selected = select_http_tuner(tuners);
if(selected.length() == 0) { log_error(__func__, ": no tuner devices are available to create the requested stream"); return nullptr; }
// Generate the URL required to stream the channel via the tuner over HTTP
std::string streamurl = get_tuner_stream_url(dbhandle, selected.c_str(), channelid);
if(streamurl.length() == 0) { log_error(__func__, ": unable to generate tuner device stream url for channel ", vchannel); return nullptr; }
try {
// Start the new HTTP stream using the parameters currently specified by the settings
std::unique_ptr<pvrstream> stream = httpstream::create(streamurl.c_str());
log_info(__func__, ": streaming channel ", vchannel, " via tuner device url ", streamurl.c_str());
return stream;
}
// If the stream creation failed, log an error and return a null unique_ptr<> back to the caller, do not throw an exception
catch(std::exception& ex) { log_error(__func__, ": unable to stream channel ", vchannel, " via tuner device url ", streamurl.c_str(), ": ", ex.what()); }
return nullptr;
}
//-----------------------------------------------------------------------------
// addon::proxy_changed_task (private)
//
// Scheduled task implementation to rediscover all backend metadata from a proxy change
//
// Arguments:
//
// cancel - Condition variable used to cancel the operation
void addon::proxy_changed_task(scalar_condition<bool> const& /*cancel*/)
{
using namespace std::chrono;
// Create a copy of the current addon settings structure
struct settings settings = copy_settings();
// If the settings indicate no proxy server and one wasn't already in use do nothing
bool useproxy = (settings.use_proxy_server == true) && (!settings.proxy_server_address.empty());
if((useproxy == false) && (m_useproxy.load() == false)) return;
try {