-
Notifications
You must be signed in to change notification settings - Fork 147
/
TVController.cs
5920 lines (5399 loc) · 187 KB
/
TVController.cs
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
#region Copyright (C) 2005-2011 Team MediaPortal
// Copyright (C) 2005-2011 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal 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 of the License, or
// (at your option) any later version.
//
// MediaPortal 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 MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
#region usings
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using MediaPortal.Common.Utils;
using MediaPortal.Common.Utils.ExtensionMethods;
using Mediaportal.TV.Server.TVControl;
using Mediaportal.TV.Server.TVControl.Events;
using Mediaportal.TV.Server.TVControl.Interfaces.Events;
using Mediaportal.TV.Server.TVControl.Interfaces.Services;
using Mediaportal.TV.Server.TVDatabase.Entities;
using Mediaportal.TV.Server.TVDatabase.Entities.Enums;
using Mediaportal.TV.Server.TVDatabase.Presentation;
using Mediaportal.TV.Server.TVDatabase.TVBusinessLayer;
using Mediaportal.TV.Server.TVLibrary.CardManagement.CardAllocation;
using Mediaportal.TV.Server.TVLibrary.CardManagement.CardHandler;
using Mediaportal.TV.Server.TVLibrary.CardManagement.CardReservation;
using Mediaportal.TV.Server.TVLibrary.CardManagement.CardReservation.Implementations;
using Mediaportal.TV.Server.TVLibrary.DiskManagement;
using Mediaportal.TV.Server.TVLibrary.Epg;
using Mediaportal.TV.Server.TVLibrary.EventDispatchers;
using Mediaportal.TV.Server.TVLibrary.Implementations;
using Mediaportal.TV.Server.TVLibrary.Implementations.Analog.Graphs.Analog;
using Mediaportal.TV.Server.TVLibrary.Implementations.Hybrid;
using Mediaportal.TV.Server.TVLibrary.Interfaces;
using Mediaportal.TV.Server.TVLibrary.Interfaces.Epg;
using Mediaportal.TV.Server.TVLibrary.Interfaces.Interfaces;
using Mediaportal.TV.Server.TVLibrary.Interfaces.Interfaces.Device;
using Mediaportal.TV.Server.TVLibrary.Interfaces.Logging;
using Mediaportal.TV.Server.TVLibrary.Scheduler;
using Mediaportal.TV.Server.TVLibrary.Services;
using Mediaportal.TV.Server.TVLibrary.Streaming;
using Mediaportal.TV.Server.TVService.Interfaces;
using Mediaportal.TV.Server.TVService.Interfaces.CardHandler;
using Mediaportal.TV.Server.TVService.Interfaces.CardReservation;
using Mediaportal.TV.Server.TVService.Interfaces.Enums;
using Mediaportal.TV.Server.TVService.Interfaces.Services;
using RecordingManagement = Mediaportal.TV.Server.TVDatabase.TVBusinessLayer.RecordingManagement;
#endregion
namespace Mediaportal.TV.Server.TVLibrary
{
/// <summary>
/// This class servers all requests from remote clients
/// and if server is the master it will delegate the requests to the
/// correct slave servers
/// </summary>
public class
TvController : IInternalControllerService, IDisposable, ITvServerEvent, ICiMenuCallbacks
{
#region constants
#endregion
#region variables
private bool _onResumeDone;
private int _rtspStreamingPort;
private string _hostName;
private readonly TvServerEventDispatcher _tvServerEventDispatcher;
private readonly HeartbeatManager _heartbeatManager;
private readonly CiMenuManager _ciMenuManager;
private readonly ICardAllocation _cardAllocation;
private readonly ChannelStates _channelStates;
/// <summary>
/// EPG grabber for DVB
/// </summary>
private EpgGrabber _epgGrabber;
/// <summary>
/// Recording scheduler
/// </summary>
private Scheduler.Scheduler _scheduler;
/// <summary>
/// RTSP Streaming Server
/// </summary>
private RtspStreaming _streamer;
/// <summary>
private TvCardCollection _localCardCollection;
/// <summary>
/// Indicates how many free cards to try for timeshifting
/// </summary>
private int _maxFreeCardsToTry;
/// <summary>
/// Initialized Conditional Access handler
/// </summary>
/// <param name="cardId">id of the card.</param>
/// <returns>true if successful</returns>
public bool InitConditionalAccess(int cardId)
{
bool initConditionalAccess = false;
try
{
if (ValidateTvControllerParams(cardId, false))
{
// Note: this is *far* from ideal. We have no way to actually tell whether the tuner supports
// conditional access unless the tuner graph is initialised. We also have no way to tell if the
// tuner graph is initialised. If we try to initialise the graph and it is already initialised
// then we'll get an exception. We do the best that we can, but we can't guarantee that this
// will work for hybrid tuners - we don't want to interrupt timeshifting and recording.
ITVCard card = _cards[cardId].Card;
if (card.IsConditionalAccessSupported)
{
return true;
}
TvCardBase baseCard = card as TvCardBase;
if (baseCard == null)
{
// Non-initialised HybridCard instances exit here.
return false;
}
try
{
baseCard.BuildGraph();
}
catch (Exception)
{
// If we get here, we assume the graph is already built - not a problem.
}
initConditionalAccess = card.IsConditionalAccessSupported;
}
else
{
this.LogDebug("InitConditionalAccess: ValidateTvControllerParams failed");
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return initConditionalAccess;
}
private Dictionary<int, ITvCardHandler> _cards = new Dictionary<int, ITvCardHandler>();
///
// contains a cached copy of all the channels in the user defined groups (excl. the all channels group)
// used to speedup "mini EPG" channel state creation.
private List<Channel> _tvChannelListGroups;
#endregion
#region events
public event TvServerEventHandler OnTvServerEvent;
#endregion
#region ctor
/// <summary>
/// Initializes a new instance of the <see cref="TvControllerService"/> class.
/// </summary>
public TvController()
{
_tvServerEventDispatcher = new TvServerEventDispatcher();
_heartbeatManager = new HeartbeatManager();
_channelStates = new ChannelStates();
_ciMenuManager = new CiMenuManager();
_cardAllocation = new AdvancedCardAllocation();
_channelStates.OnChannelStatesSet -= new ChannelStates.OnChannelStatesSetDelegate(channelStates_OnChannelStatesSet);
_channelStates.OnChannelStatesSet += new ChannelStates.OnChannelStatesSetDelegate(channelStates_OnChannelStatesSet);
}
public IDictionary<int, ITvCardHandler> CardCollection
{
get { return _cards; }
}
#region CI Menu action functions
/// <summary>
/// Returns if selected card has CI Menu capabilities
/// </summary>
/// <param name="cardId">card</param>
/// <returns>true if supported</returns>
public bool CiMenuSupported(int cardId)
{
bool checkCardPresent = false;
try
{
this.LogDebug("CiMenuSupported called cardid {0}", cardId);
if (ValidateTvControllerParams(cardId, checkCardPresent))
{
this.LogDebug("CiMenuSupported card {0} supported: {1}", _cards[cardId].CardName, _cards[cardId].CiMenuSupported);
checkCardPresent = _cards[cardId].CiMenuSupported;
}
else
{
this.LogDebug("ValidateTvControllerParams failed");
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return checkCardPresent;
}
/// <summary>
/// Enters the card's CI menu
/// </summary>
/// <param name="cardId">card</param>
/// <returns>true if successful</returns>
public bool EnterCiMenu(int cardId)
{
bool checkCardPresent = false;
try
{
this.LogDebug("EnterCiMenu called");
if (ValidateTvControllerParams(cardId, checkCardPresent))
{
if (_cards[cardId].CiMenuActions != null)
{
_ciMenuManager.IsCiMenuInteractive = true; // user action
checkCardPresent = _cards[cardId].CiMenuActions.EnterCIMenu();
}
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return checkCardPresent;
}
/// <summary>
/// SelectMenu selects an ci menu entry;
/// </summary>
/// <param name="cardId">card</param>
/// <param name="choice">choice,0 for "back" action</param>
/// <returns>true if successful</returns>
public bool SelectMenu(int cardId, byte choice)
{
bool checkCardPresent = false;
try
{
this.LogDebug("SelectCiMenu called");
if (ValidateTvControllerParams(cardId, false))
{
checkCardPresent = _cards[cardId].CiMenuActions != null && _cards[cardId].CiMenuActions.SelectMenu(choice);
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return checkCardPresent;
}
/// <summary>
/// CloseMenu closes the menu
/// </summary>
/// <param name="cardId">card</param>
/// <returns>true if successful</returns>
public bool CloseMenu(int cardId)
{
bool closeMenu = false;
try
{
this.LogDebug("CloseMenu called");
if (ValidateTvControllerParams(cardId, false))
{
if (_cards[cardId].CiMenuActions != null)
{
_ciMenuManager.IsCiMenuInteractive = false; // user action ended by wanted close
closeMenu = _cards[cardId].CiMenuActions.CloseCIMenu();
}
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return closeMenu;
}
/// <summary>
/// Sends a menu answer back to CAM
/// </summary>
/// <param name="cardId">card</param>
/// <param name="cancel">true to cancel request</param>
/// <param name="answer">answer string</param>
/// <returns></returns>
public bool SendMenuAnswer(int cardId, bool cancel, string answer)
{
bool sendMenuAnswer = false;
try
{
this.LogDebug("SendMenuAnswer called");
if (ValidateTvControllerParams(cardId, false))
{
sendMenuAnswer = _cards[cardId].CiMenuActions != null && _cards[cardId].CiMenuActions.SendMenuAnswer(cancel, answer);
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return sendMenuAnswer;
}
/// <summary>
/// sets a CI menu callback handler. dummy in this case, because it's an interface member
/// </summary>
/// <param name="cardId">card</param>
/// <param name="callbackHandler">null, not required</param>
/// <returns>true is successful</returns>
public bool SetCiMenuHandler(int cardId, ICiMenuCallbacks callbackHandler)
{
// register tvservice itself as handler
try
{
return EnableCiMenuHandler(cardId);
}
catch (Exception e)
{
HandleControllerException(e);
}
return false;
}
/// <summary>
/// Registers the tvserver as primary CI menu handler on serverside
/// </summary>
/// <param name="cardId">card</param>
/// <returns>true is successful</returns>
public bool EnableCiMenuHandler(int cardId)
{
bool enableCiMenuHandler = false;
this.LogDebug("TvController: EnableCiMenuHandler called");
if (ValidateTvControllerParams(cardId, false))
{
if (_cards[cardId].CiMenuActions != null)
{
_ciMenuManager.ActiveCiMenuCard = cardId;
enableCiMenuHandler = _cards[cardId].CiMenuActions.SetCiMenuHandler(this);
this.LogDebug("TvController: SetCiMenuHandler: result {0}", enableCiMenuHandler);
}
}
return enableCiMenuHandler;
}
#endregion
/// <summary>
/// Determines whether the card is in use
/// </summary>
/// <param name="cardId">The card id.</param>
/// <param name="user">The user which uses the card</param>
/// <returns>
/// <c>true</c> if card is in use; otherwise, <c>false</c>.
/// </returns>
public bool IsCardInUse(int cardId, out IUser user)
{
user = null;
bool isCardInUse = false;
try
{
if (ValidateTvControllerParams(cardId))
{
isCardInUse = _cards[cardId].UserManagement.IsLocked(out user);
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return isCardInUse;
}
/// <summary>
/// Gets the user for card.
/// </summary>
/// <param name="cardId">The card id.</param>
/// <returns></returns>
public IUser GetUserForCard(int cardId)
{
IUser user = null;
if (ValidateTvControllerParams(cardId))
{
_cards[cardId].UserManagement.IsLocked(out user);
}
return user;
}
public void Init()
{
this.LogInfo("Controller: Initializing TVServer");
bool result = false;
Exception ex = null;
for (int i = 0; i < 5 && !result; i++)
{
if (i != 0)
{
//Fresh start
try
{
DeInit();
}
catch (Exception e)
{
ex = e;
this.LogError("Controller: Error while deinit TvServer in Init");
}
Thread.Sleep(3000);
}
this.LogInfo("Controller: {0} init attempt", (i + 1));
try
{
InitController();
}
catch (Exception e)
{
ex = e;
}
result = (ex == null);
}
if (result)
{
this.LogInfo("Controller: TVServer initialized okay");
}
else
{
this.LogInfo("Controller: Failed to initialize TVServer");
if (ex != null)
{
throw ex;
}
}
}
/// <summary>
/// Initalizes the controller.
/// It will update the database with the cards found on this system
/// start the epg grabber and scheduler
/// and check if its supposed to be a master or slave controller
/// </summary>
private void InitController()
{
if (GlobalServiceProvider.Instance.IsRegistered<ITvServerEvent>())
{
GlobalServiceProvider.Instance.Remove<ITvServerEvent>();
}
GlobalServiceProvider.Instance.Add<ITvServerEvent>(this);
try
{
_cards = new Dictionary<int, ITvCardHandler>();
_localCardCollection = new TvCardCollection(this);
//log all local ip adresses, usefull for debugging problems
this.LogDebug("Controller: started at {0}", Dns.GetHostName());
IPHostEntry local = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ipaddress in local.AddressList)
{
// Show only IPv4 family addresses
if (ipaddress.AddressFamily == AddressFamily.InterNetwork)
{
this.LogInfo("Controller: local ip address:{0}", ipaddress.ToString());
}
}
_rtspStreamingPort = SettingsManagement.GetValue("rtspPort", RtspStreaming.DefaultPort);
//enumerate all tv cards in this pc...
_maxFreeCardsToTry = SettingsManagement.GetValue("timeshiftMaxFreeCardsToTry", 0);
IList<Card> allCards = TVDatabase.TVBusinessLayer.CardManagement.ListAllCards(CardIncludeRelationEnum.None);
bool oneOrMoreCardsFound = false;
foreach (ITVCard itvCard in _localCardCollection.Cards)
{
//for each card, check if its already mentioned in the database
bool found = allCards.Any(card => card.DevicePath == itvCard.DevicePath);
if (!found)
{
// card is not yet in the database, so add it
this.LogInfo("Controller: add card:{0}", itvCard.Name);
var newCard = new Card
{
TimeshiftingFolder = "",
RecordingFolder = "",
DevicePath = itvCard.DevicePath,
Name = itvCard.Name,
Priority = 1,
GrabEPG = true,
Enabled = true,
CamType = 0,
DecryptLimit = 0,
NetProvider = (int)DbNetworkProvider.Generic,
MultiChannelDecryptMode = (int)MultiChannelDecryptMode.Disabled,
PidFilterMode = (int)PidFilterMode.Auto,
IdleMode = (int)DeviceIdleMode.Stop
};
oneOrMoreCardsFound = true;
TVDatabase.TVBusinessLayer.CardManagement.SaveCard(newCard);
}
}
if (oneOrMoreCardsFound)
{
allCards = TVDatabase.TVBusinessLayer.CardManagement.ListAllCards(CardIncludeRelationEnum.None);
}
//notify log about cards from the database which are removed from the pc
int cardsInstalled = _localCardCollection.Cards.Count;
foreach (Card dbsCard in allCards)
{
{
bool found = false;
for (int cardNumber = 0; cardNumber < cardsInstalled; ++cardNumber)
{
if (dbsCard.DevicePath == _localCardCollection.Cards[cardNumber].DevicePath)
{
Card cardDB = TVDatabase.TVBusinessLayer.CardManagement.GetCardByDevicePath(_localCardCollection.Cards[cardNumber].DevicePath, CardIncludeRelationEnum.None);
bool cardEnabled = cardDB.Enabled;
bool cardPresent = _localCardCollection.Cards[cardNumber].CardPresent;
if (cardEnabled && cardPresent)
{
ITVCard unknownCard = _localCardCollection.Cards[cardNumber];
if (unknownCard is TvCardBase)
{
TvCardBase card = (TvCardBase)unknownCard;
if (card.PreloadCard)
{
try
{
this.LogInfo("Controller: preloading card :{0}", card.Name);
card.BuildGraph();
if (unknownCard is TvCardAnalog)
{
((TvCardAnalog)unknownCard).ReloadCardConfiguration();
}
}
catch (Exception ex)
{
this.LogError("failed to preload card '{0}', ex = {1}", card.Name, ex);
}
}
else
{
this.LogInfo("Controller: NOT preloading card :{0}", card.Name);
}
}
else
{
this.LogInfo("Controller: NOT preloading card :{0}", unknownCard.Name);
}
}
found = true;
break;
}
}
if (!found)
{
this.LogInfo("Controller: card not found :{0}", dbsCard.Name);
foreach (ITVCard t in _localCardCollection.Cards.Where(t => t.DevicePath == dbsCard.DevicePath))
{
t.CardPresent = false;
break;
}
// Fix mantis 0002790: Bad behavior when card count for IPTV = 0
if (dbsCard.Name.StartsWith("MediaPortal IPTV Source Filter"))
{
CardRemove(dbsCard.IdCard);
}
}
}
}
Dictionary<int, ITVCard> localcards = new Dictionary<int, ITVCard>();
//allCards = TVDatabase.TVBusinessLayer.CardManagement.ListAllCards();
foreach (Card card in allCards)
{
{
foreach (ITVCard t in _localCardCollection.Cards)
{
if (t.DevicePath == card.DevicePath)
{
localcards[card.IdCard] = t;
break;
}
}
}
}
this.LogInfo("Controller: setup hybrid cards");
IList<CardGroup> cardgroups = TVDatabase.TVBusinessLayer.CardManagement.ListAllCardGroups();
foreach (CardGroup group in cardgroups)
{
IList<CardGroupMap> cards = group.CardGroupMaps;
var hybridCardGroup = new HybridCardGroup();
foreach (CardGroupMap card in cards)
{
if (localcards.ContainsKey(card.IdCard))
{
localcards[card.IdCard].IsHybrid = true;
this.LogDebug("Hybrid card: " + localcards[card.IdCard].Name + " (" + group.Name + ")");
HybridCard hybridCard = hybridCardGroup.Add(card.IdCard, localcards[card.IdCard]);
localcards[card.IdCard] = hybridCard;
}
}
}
allCards = TVDatabase.TVBusinessLayer.CardManagement.ListAllCards(CardIncludeRelationEnum.None); //SEB
foreach (Card dbsCard in allCards)
{
if (localcards.ContainsKey(dbsCard.IdCard))
{
ITVCard card = localcards[dbsCard.IdCard];
var tvcard = new TvCardHandler(dbsCard, card);
_cards[dbsCard.IdCard] = tvcard;
}
// remove any old timeshifting TS files
try
{
string timeShiftPath = dbsCard.TimeshiftingFolder;
if (string.IsNullOrEmpty(dbsCard.TimeshiftingFolder))
{
timeShiftPath = Path.Combine(PathManager.GetDataPath, "timeshiftbuffer");
}
if (!Directory.Exists(timeShiftPath))
{
this.LogInfo("Controller: creating timeshifting folder {0} for card \"{1}\"", timeShiftPath, dbsCard.Name);
Directory.CreateDirectory(timeShiftPath);
}
this.LogDebug("Controller: card {0}: current timeshiftpath = {1}", dbsCard.Name, timeShiftPath);
if (timeShiftPath != null)
{
string[] files = Directory.GetFiles(timeShiftPath);
foreach (string file in files)
{
try
{
var fInfo = new FileInfo(file);
bool delFile = (fInfo.Extension.ToUpperInvariant().IndexOf(".TSBUFFER") == 0);
if (!delFile)
{
delFile = (fInfo.Extension.ToUpperInvariant().IndexOf(".TS") == 0) &&
(fInfo.Name.ToUpperInvariant().IndexOf("TSBUFFER") > 0);
}
if (delFile)
{
File.Delete(fInfo.FullName);
}
}
catch (IOException) { }
}
}
}
catch (Exception exd)
{
this.LogInfo("Controller: Error cleaning old ts buffer - {0}", exd.Message);
}
}
this.LogInfo("Controller: setup streaming");
_hostName = Dns.GetHostName();
_hostName = SettingsManagement.GetValue("hostname", _hostName);
_streamer = new RtspStreaming(_hostName, _rtspStreamingPort);
_epgGrabber = new EpgGrabber();
_epgGrabber.Start();
_scheduler = new Scheduler.Scheduler();
_scheduler.Start();
StartHeartbeatManager();
StartTvServerEventDispatcher();
ExecutePendingDeletions();
SynchProgramStatesForAllSchedules();
}
catch (Exception ex)
{
this.LogError("TvControllerException");
throw;
}
this.LogInfo("Controller: initalized");
}
private void SynchProgramStatesForAllSchedules()
{
// Re-evaluate program states
this.LogInfo("Controller: recalculating program states");
ThreadPool.QueueUserWorkItem(
delegate
{
try
{
ProgramManagement.ResetAllStates();
ProgramManagement.SynchProgramStatesForAllSchedules(ScheduleManagement.ListAllSchedules());
}
catch (Exception e)
{
this.LogError(e, "could not sync rogram states for all schedules");
}
})
;
}
private void StartTvServerEventDispatcher()
{
_tvServerEventDispatcher.Start();
}
private void StartHeartbeatManager()
{
_heartbeatManager.Start();
}
#endregion
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// get rid of managed resources
DeInit();
}
// get rid of unmanaged resources
}
/// <summary>
/// Clean up the controller when service is stopped
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~TvController()
{
Dispose(false);
}
/// <summary>
/// Cleans up the controller
/// </summary>
public void DeInit()
{
this.LogInfo("Controller: DeInit.");
try
{
StopHeartbeatManager();
StopTvserverEventDispatcher();
//stop the RTSP streamer server
if (_streamer != null)
{
this.LogInfo("Controller: stop streamer...");
_streamer.Stop();
_streamer = null;
this.LogInfo("Controller: streamer stopped...");
}
//stop the recording scheduler
if (_scheduler != null)
{
this.LogInfo("Controller: stop scheduler...");
_scheduler.Stop();
_scheduler = null;
this.LogInfo("Controller: scheduler stopped...");
}
//stop the epg grabber
StopEPGgrabber();
_epgGrabber.SafeDispose();
_epgGrabber = null;
//clean up the tv cards
FreeCards();
////Gentle.Common.CacheManager.Clear();
if (GlobalServiceProvider.Instance.IsRegistered<ITvServerEvent>())
{
GlobalServiceProvider.Instance.Remove<ITvServerEvent>();
}
}
catch (Exception ex)
{
this.LogError(ex, "TvController: Deinit failed");
}
}
private void StopTvserverEventDispatcher()
{
_tvServerEventDispatcher.Stop();
}
private void StopHeartbeatManager()
{
_heartbeatManager.Stop();
}
#endregion
#region IController Members
#region internal interface
/// <summary>
/// Gets the assembly of tvservice.exe
/// </summary>
/// <value>Returns the AssemblyVersion of tvservice.exe</value>
public string GetAssemblyVersion
{
get { return FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; }
}
/// <summary>
/// Gets the total number of cards installed.
/// </summary>
/// <value>Number which indicates the cards installed</value>
public int Cards
{
get
{
try
{
return _cards.Count;
}
catch(Exception e)
{
HandleControllerException(e);
}
return 0;
}
}
private void HandleControllerException(Exception ex, string errorMsg)
{
this.LogError(errorMsg);
HandleControllerException(ex);
}
private void HandleControllerException(Exception ex)
{
var st = new StackTrace(true);
StackFrame sf = st.GetFrame(0);
string methodName = sf.GetMethod().Name;
this.LogError("exception occurred in TVController: {0} - {1}", methodName, ex);
//throw exception;
}
/// <summary>
/// Gets the card Id for a card
/// </summary>
/// <param name="cardIndex">Index of the card.</param>
/// <value>id of card</value>
public int CardId(int cardIndex)
{
IList<Card> cards = TVDatabase.TVBusinessLayer.CardManagement.ListAllCards(CardIncludeRelationEnum.None); //SEB
return cards != null && cards.Count > cardIndex ? cards[cardIndex].IdCard : -1;
}
/// <summary>
/// returns if the card is enabled or disabled
/// </summary>
/// <param name="cardId">id of the card.</param>
/// <value>true if enabled, otherwise false</value>
public bool IsCardEnabled(int cardId)
{
bool isCardEnabled = false;
if (ValidateTvControllerParams(cardId))
{
isCardEnabled = _cards[cardId].DataBaseCard.Enabled;
}
return isCardEnabled;
}
/// <summary>
/// Gets the type of card.
/// </summary>
/// <param name="cardId">id of card.</param>
/// <value>cardtype (Analog,DvbS,DvbT,DvbC,Atsc)</value>
public CardType Type(int cardId)
{
CardType cardType = CardType.Unknown;
try
{
if (_cards.ContainsKey(cardId))
{
if (ValidateTvControllerParams(cardId))
{
cardType = _cards[cardId].Type;
}
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return cardType;
}
/// <summary>
/// Gets the name for a card.
/// </summary>
/// <param name="cardId">id of card.</param>
/// <returns>name of card</returns>
public string CardName(int cardId)
{
string cardName = "";
try
{
if (ValidateTvControllerParams(cardId))
{
cardName = _cards[cardId].CardName;
}
}
catch (Exception e)
{
HandleControllerException(e);
}
return cardName;
}
/// <summary>
/// Method to check if card can tune to the channel specified
/// </summary>
/// <param name="cardId">id of card.</param>
/// <param name="channel">channel.</param>
/// <returns>true if card can tune to the channel otherwise false</returns>
public bool CanTune(int cardId, IChannel channel)
{
bool canTune = false;
try
{
if (ValidateTvControllerParams(cardId))
{