/
LiveTvManager.cs
1901 lines (1480 loc) · 65.8 KB
/
LiveTvManager.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
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Localization;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.LiveTv
{
/// <summary>
/// Class LiveTvManager
/// </summary>
public class LiveTvManager : ILiveTvManager, IDisposable
{
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
private readonly ILogger _logger;
private readonly IItemRepository _itemRepo;
private readonly IUserManager _userManager;
private readonly IUserDataManager _userDataManager;
private readonly ILibraryManager _libraryManager;
private readonly ITaskManager _taskManager;
private readonly IJsonSerializer _jsonSerializer;
private readonly IDtoService _dtoService;
private readonly ILocalizationManager _localization;
private readonly LiveTvDtoService _tvDtoService;
private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
new ConcurrentDictionary<string, LiveStreamData>();
private List<Guid> _channelIdList = new List<Guid>();
private Dictionary<Guid, LiveTvProgram> _programs = new Dictionary<Guid, LiveTvProgram>();
private readonly ConcurrentDictionary<Guid, bool> _refreshedPrograms = new ConcurrentDictionary<Guid, bool>();
private readonly SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(1, 1);
public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer)
{
_config = config;
_fileSystem = fileSystem;
_logger = logger;
_itemRepo = itemRepo;
_userManager = userManager;
_libraryManager = libraryManager;
_taskManager = taskManager;
_localization = localization;
_jsonSerializer = jsonSerializer;
_dtoService = dtoService;
_userDataManager = userDataManager;
_tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost);
}
/// <summary>
/// Gets the services.
/// </summary>
/// <value>The services.</value>
public IReadOnlyList<ILiveTvService> Services
{
get { return _services; }
}
public ILiveTvService ActiveService { get; private set; }
private LiveTvOptions GetConfiguration()
{
return _config.GetConfiguration<LiveTvOptions>("livetv");
}
/// <summary>
/// Adds the parts.
/// </summary>
/// <param name="services">The services.</param>
public void AddParts(IEnumerable<ILiveTvService> services)
{
_services.AddRange(services);
SetActiveService(GetConfiguration().ActiveService);
}
private void SetActiveService(string name)
{
var service = _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)) ??
_services.FirstOrDefault();
SetActiveService(service);
}
private void SetActiveService(ILiveTvService service)
{
if (ActiveService != null)
{
ActiveService.DataSourceChanged -= service_DataSourceChanged;
}
ActiveService = service;
if (service != null)
{
service.DataSourceChanged += service_DataSourceChanged;
}
}
void service_DataSourceChanged(object sender, EventArgs e)
{
_taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
}
public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
{
var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
var channels = _channelIdList.Select(_libraryManager.GetItemById)
.Where(i => i != null)
.OfType<LiveTvChannel>();
if (user != null)
{
// Avoid implicitly captured closure
var currentUser = user;
channels = channels
.Where(i => i.IsParentalAllowed(currentUser))
.OrderBy(i =>
{
double number = 0;
if (!string.IsNullOrEmpty(i.Number))
{
double.TryParse(i.Number, out number);
}
return number;
});
if (query.IsFavorite.HasValue)
{
var val = query.IsFavorite.Value;
channels = channels
.Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val);
}
if (query.IsLiked.HasValue)
{
var val = query.IsLiked.Value;
channels = channels
.Where(i =>
{
var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
return likes.HasValue && likes.Value == val;
});
}
if (query.IsDisliked.HasValue)
{
var val = query.IsDisliked.Value;
channels = channels
.Where(i =>
{
var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes;
return likes.HasValue && likes.Value != val;
});
}
}
var enableFavoriteSorting = query.EnableFavoriteSorting;
channels = channels.OrderBy(i =>
{
if (enableFavoriteSorting)
{
var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey());
if (userData.IsFavorite)
{
return 0;
}
if (userData.Likes.HasValue)
{
if (!userData.Likes.Value)
{
return 3;
}
return 1;
}
}
return 2;
})
.ThenBy(i =>
{
double number = 0;
if (!string.IsNullOrEmpty(i.Number))
{
double.TryParse(i.Number, out number);
}
return number;
}).ThenBy(i => i.Name);
var allChannels = channels.ToList();
IEnumerable<LiveTvChannel> allEnumerable = allChannels;
if (query.StartIndex.HasValue)
{
allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
}
if (query.Limit.HasValue)
{
allEnumerable = allEnumerable.Take(query.Limit.Value);
}
var result = new QueryResult<LiveTvChannel>
{
Items = allEnumerable.ToArray(),
TotalRecordCount = allChannels.Count
};
return result;
}
public async Task<QueryResult<ChannelInfoDto>> GetChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
{
var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
var internalResult = await GetInternalChannels(query, cancellationToken).ConfigureAwait(false);
var returnList = new List<ChannelInfoDto>();
foreach (var channel in internalResult.Items)
{
var currentProgram = await GetCurrentProgram(channel.ExternalId, cancellationToken).ConfigureAwait(false);
returnList.Add(_tvDtoService.GetChannelInfoDto(channel, currentProgram, user));
}
var result = new QueryResult<ChannelInfoDto>
{
Items = returnList.ToArray(),
TotalRecordCount = internalResult.TotalRecordCount
};
return result;
}
public LiveTvChannel GetInternalChannel(string id)
{
return GetInternalChannel(new Guid(id));
}
private LiveTvChannel GetInternalChannel(Guid id)
{
return _libraryManager.GetItemById(id) as LiveTvChannel;
}
public async Task<LiveTvProgram> GetInternalProgram(string id, CancellationToken cancellationToken)
{
var guid = new Guid(id);
LiveTvProgram obj = null;
_programs.TryGetValue(guid, out obj);
if (obj != null)
{
await RefreshIfNeeded(obj, cancellationToken).ConfigureAwait(false);
}
return obj;
}
private Task RefreshIfNeeded(IEnumerable<LiveTvProgram> programs, CancellationToken cancellationToken)
{
var list = programs.ToList();
Task.Run(async () =>
{
foreach (var program in list)
{
await RefreshIfNeeded(program, CancellationToken.None).ConfigureAwait(false);
}
}, cancellationToken);
return Task.FromResult(true);
}
private async Task RefreshIfNeeded(LiveTvProgram program, CancellationToken cancellationToken)
{
if (_refreshedPrograms.ContainsKey(program.Id))
{
return;
}
_refreshedPrograms.TryAdd(program.Id, true);
await program.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken)
{
var service = ActiveService;
var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
var recording = recordings.FirstOrDefault(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
return await GetRecording(recording, service.Name, cancellationToken).ConfigureAwait(false);
}
private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
public async Task<ChannelMediaInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
{
return await GetLiveStream(id, false, cancellationToken).ConfigureAwait(false);
}
public async Task<ChannelMediaInfo> GetChannelStream(string id, CancellationToken cancellationToken)
{
return await GetLiveStream(id, true, cancellationToken).ConfigureAwait(false);
}
private async Task<ChannelMediaInfo> GetLiveStream(string id, bool isChannel, CancellationToken cancellationToken)
{
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var service = ActiveService;
ChannelMediaInfo info;
if (isChannel)
{
var channel = GetInternalChannel(id);
_logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
info = await service.GetChannelStream(channel.ExternalId, cancellationToken).ConfigureAwait(false);
}
else
{
var recordings = await service.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
var recording = recordings.First(i => _tvDtoService.GetInternalRecordingId(service.Name, i.Id) == new Guid(id));
_logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.Id);
info = await service.GetRecordingStream(recording.Id, cancellationToken).ConfigureAwait(false);
}
_logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
Sanitize(info);
var data = new LiveStreamData
{
Info = info,
ConsumerCount = 1,
IsChannel = isChannel,
ItemId = id
};
_openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
return info;
}
catch (Exception ex)
{
_logger.ErrorException("Error getting channel stream", ex);
throw;
}
finally
{
_liveStreamSemaphore.Release();
}
}
private void Sanitize(ChannelMediaInfo info)
{
// Clean some bad data coming from providers
if (info.AudioBitrate.HasValue && info.AudioBitrate <= 0)
{
info.AudioBitrate = null;
}
if (info.VideoBitrate.HasValue && info.VideoBitrate <= 0)
{
info.VideoBitrate = null;
}
if (info.AudioChannels.HasValue && info.AudioChannels <= 0)
{
info.AudioChannels = null;
}
if (info.Framerate.HasValue && info.Framerate <= 0)
{
info.Framerate = null;
}
if (info.Width.HasValue && info.Width <= 0)
{
info.Width = null;
}
if (info.Height.HasValue && info.Height <= 0)
{
info.Height = null;
}
if (info.AudioSampleRate.HasValue && info.AudioSampleRate <= 0)
{
info.AudioSampleRate = null;
}
if (info.VideoLevel.HasValue && info.VideoLevel <= 0)
{
info.VideoLevel = null;
}
}
private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, CancellationToken cancellationToken)
{
var path = Path.Combine(_config.ApplicationPaths.ItemsByNamePath, "tvchannels", _fileSystem.GetValidFilename(channelInfo.Name));
var fileInfo = new DirectoryInfo(path);
var isNew = false;
if (!fileInfo.Exists)
{
_logger.Debug("Creating directory {0}", path);
Directory.CreateDirectory(path);
fileInfo = new DirectoryInfo(path);
if (!fileInfo.Exists)
{
throw new IOException("Path not created: " + path);
}
isNew = true;
}
var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
{
item = new LiveTvChannel
{
Name = channelInfo.Name,
Id = id,
DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
Path = path
};
isNew = true;
}
item.ChannelType = channelInfo.ChannelType;
item.ExternalId = channelInfo.Id;
item.ServiceName = serviceName;
item.Number = channelInfo.Number;
var replaceImages = new List<ImageType>();
if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
{
isNew = true;
replaceImages.Add(ImageType.Primary);
}
if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
{
isNew = true;
replaceImages.Add(ImageType.Primary);
}
item.ProviderImageUrl = channelInfo.ImageUrl;
item.HasProviderImage = channelInfo.HasImage;
item.ProviderImagePath = channelInfo.ImagePath;
if (string.IsNullOrEmpty(item.Name))
{
item.Name = channelInfo.Name;
}
await item.RefreshMetadata(new MetadataRefreshOptions
{
ForceSave = isNew,
ReplaceImages = replaceImages.Distinct().ToList()
}, cancellationToken);
return item;
}
private LiveTvProgram GetProgram(ProgramInfo info, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
{
var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
var item = _itemRepo.RetrieveItem(id) as LiveTvProgram;
if (item == null)
{
item = new LiveTvProgram
{
Name = info.Name,
Id = id,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
}
item.ChannelType = channelType;
item.ServiceName = serviceName;
item.Audio = info.Audio;
item.ExternalChannelId = info.ChannelId;
item.CommunityRating = info.CommunityRating;
item.EndDate = info.EndDate;
item.EpisodeTitle = info.EpisodeTitle;
item.ExternalId = info.Id;
item.Genres = info.Genres;
item.HasProviderImage = info.HasImage;
item.IsHD = info.IsHD;
item.IsKids = info.IsKids;
item.IsLive = info.IsLive;
item.IsMovie = info.IsMovie;
item.IsNews = info.IsNews;
item.IsPremiere = info.IsPremiere;
item.IsRepeat = info.IsRepeat;
item.IsSeries = info.IsSeries;
item.IsSports = info.IsSports;
item.Name = info.Name;
item.OfficialRating = info.OfficialRating;
item.Overview = info.Overview;
item.PremiereDate = info.OriginalAirDate;
item.ProviderImagePath = info.ImagePath;
item.ProviderImageUrl = info.ImageUrl;
item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
item.StartDate = info.StartDate;
return item;
}
private async Task<ILiveTvRecording> GetRecording(RecordingInfo info, string serviceName, CancellationToken cancellationToken)
{
var isNew = false;
var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
var item = _itemRepo.RetrieveItem(id) as ILiveTvRecording;
if (item == null)
{
if (info.ChannelType == ChannelType.TV)
{
item = new LiveTvVideoRecording
{
Name = info.Name,
Id = id,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
VideoType = VideoType.VideoFile
};
}
else
{
item = new LiveTvAudioRecording
{
Name = info.Name,
Id = id,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
}
isNew = true;
}
item.RecordingInfo = info;
item.ServiceName = serviceName;
var originalPath = item.Path;
if (!string.IsNullOrEmpty(info.Path))
{
item.Path = info.Path;
}
else if (!string.IsNullOrEmpty(info.Url))
{
item.Path = info.Url;
}
var pathChanged = !string.Equals(originalPath, item.Path);
await item.RefreshMetadata(new MetadataRefreshOptions
{
ForceSave = isNew || pathChanged
}, cancellationToken);
_libraryManager.RegisterItem((BaseItem)item);
return item;
}
private LiveTvChannel GetChannel(LiveTvProgram program)
{
var programChannelId = program.ExternalChannelId;
if (string.IsNullOrWhiteSpace(programChannelId)) return null;
var internalProgramChannelId = _tvDtoService.GetInternalChannelId(program.ServiceName, programChannelId);
return GetInternalChannel(internalProgramChannelId);
}
public async Task<ProgramInfoDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
{
var program = await GetInternalProgram(id, cancellationToken).ConfigureAwait(false);
var channel = GetChannel(program);
var dto = _tvDtoService.GetProgramInfoDto(program, channel, user);
await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false);
return dto;
}
public async Task<QueryResult<ProgramInfoDto>> GetPrograms(ProgramQuery query, CancellationToken cancellationToken)
{
IEnumerable<LiveTvProgram> programs = _programs.Values;
if (query.MinEndDate.HasValue)
{
var val = query.MinEndDate.Value;
programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value >= val);
}
if (query.MinStartDate.HasValue)
{
var val = query.MinStartDate.Value;
programs = programs.Where(i => i.StartDate >= val);
}
if (query.MaxEndDate.HasValue)
{
var val = query.MaxEndDate.Value;
programs = programs.Where(i => i.EndDate.HasValue && i.EndDate.Value <= val);
}
if (query.MaxStartDate.HasValue)
{
var val = query.MaxStartDate.Value;
programs = programs.Where(i => i.StartDate <= val);
}
if (query.ChannelIdList.Length > 0)
{
var guids = query.ChannelIdList.Select(i => new Guid(i)).ToList();
var serviceName = ActiveService.Name;
programs = programs.Where(i =>
{
var programChannelId = i.ExternalChannelId;
var internalProgramChannelId = _tvDtoService.GetInternalChannelId(serviceName, programChannelId);
return guids.Contains(internalProgramChannelId);
});
}
var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
if (user != null)
{
// Avoid implicitly captured closure
var currentUser = user;
programs = programs.Where(i => i.IsParentalAllowed(currentUser));
}
var programList = programs.ToList();
var returnArray = programList
.Select(i =>
{
var channel = GetChannel(i);
return _tvDtoService.GetProgramInfoDto(i, channel, user);
})
.ToArray();
await RefreshIfNeeded(programList, cancellationToken).ConfigureAwait(false);
await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
var result = new QueryResult<ProgramInfoDto>
{
Items = returnArray,
TotalRecordCount = returnArray.Length
};
return result;
}
public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
{
IEnumerable<LiveTvProgram> programs = _programs.Values;
var user = _userManager.GetUserById(query.UserId);
// Avoid implicitly captured closure
var currentUser = user;
programs = programs.Where(i => i.IsParentalAllowed(currentUser));
if (query.IsAiring.HasValue)
{
var val = query.IsAiring.Value;
programs = programs.Where(i => i.IsAiring == val);
}
if (query.HasAired.HasValue)
{
var val = query.HasAired.Value;
programs = programs.Where(i => i.HasAired == val);
}
var serviceName = ActiveService.Name;
var programList = programs.ToList();
var genres = programList.SelectMany(i => i.Genres)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(i => _libraryManager.GetGenre(i))
.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
.ThenByDescending(i => GetRecommendationScore(i, user.Id, serviceName, genres))
.ThenBy(i => i.StartDate);
if (query.Limit.HasValue)
{
programs = programs.Take(query.Limit.Value)
.OrderBy(i => i.StartDate);
}
programList = programs.ToList();
await RefreshIfNeeded(programList, cancellationToken).ConfigureAwait(false);
var returnArray = programList.ToArray();
var result = new QueryResult<LiveTvProgram>
{
Items = returnArray,
TotalRecordCount = returnArray.Length
};
return result;
}
public async Task<QueryResult<ProgramInfoDto>> GetRecommendedPrograms(RecommendedProgramQuery query, CancellationToken cancellationToken)
{
var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
var user = _userManager.GetUserById(query.UserId);
var returnArray = internalResult.Items
.Select(i =>
{
var channel = GetChannel(i);
return _tvDtoService.GetProgramInfoDto(i, channel, user);
})
.ToArray();
await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false);
var result = new QueryResult<ProgramInfoDto>
{
Items = returnArray,
TotalRecordCount = internalResult.TotalRecordCount
};
return result;
}
private int GetRecommendationScore(LiveTvProgram program, Guid userId, string serviceName, Dictionary<string, Genre> genres)
{
var score = 0;
if (program.IsLive)
{
score++;
}
if (program.IsSeries && !program.IsRepeat)
{
score++;
}
var internalChannelId = _tvDtoService.GetInternalChannelId(serviceName, program.ExternalChannelId);
var channel = GetInternalChannel(internalChannelId);
var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey());
if ((channelUserdata.Likes ?? false))
{
score += 2;
}
else if (!(channelUserdata.Likes ?? true))
{
score -= 2;
}
if (channelUserdata.IsFavorite)
{
score += 3;
}
score += GetGenreScore(program.Genres, userId, genres);
return score;
}
private int GetGenreScore(IEnumerable<string> programGenres, Guid userId, Dictionary<string, Genre> genres)
{
return programGenres.Select(i =>
{
var score = 0;
Genre genre;
if (genres.TryGetValue(i, out genre))
{
var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey());
if ((genreUserdata.Likes ?? false))
{
score++;
}
else if (!(genreUserdata.Likes ?? true))
{
score--;
}
if (genreUserdata.IsFavorite)
{
score += 2;
}
}
return score;
}).Sum();
}
private async Task AddRecordingInfo(IEnumerable<ProgramInfoDto> programs, CancellationToken cancellationToken)
{
var timers = await ActiveService.GetTimersAsync(cancellationToken).ConfigureAwait(false);
var timerList = timers.ToList();
foreach (var program in programs)
{
var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, program.ExternalId, StringComparison.OrdinalIgnoreCase));
if (timer != null)
{
program.TimerId = _tvDtoService.GetInternalTimerId(program.ServiceName, timer.Id)
.ToString("N");
if (!string.IsNullOrEmpty(timer.SeriesTimerId))
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(program.ServiceName, timer.SeriesTimerId)
.ToString("N");
}
}
}
}
internal async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
{
await _refreshSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await RefreshChannelsInternal(progress, cancellationToken).ConfigureAwait(false);
}
finally
{
_refreshSemaphore.Release();
}
}
private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
{
// Avoid implicitly captured closure
var service = ActiveService;
if (service == null)
{
progress.Report(100);
return;
}
progress.Report(10);
var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
var allChannelsList = allChannels.ToList();
var list = new List<LiveTvChannel>();
var numComplete = 0;
foreach (var channelInfo in allChannelsList)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, cancellationToken).ConfigureAwait(false);
list.Add(item);
_libraryManager.RegisterItem(item);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
}
numComplete++;
double percent = numComplete;
percent /= allChannelsList.Count;
progress.Report(5 * percent + 10);
}
_channelIdList = list.Select(i => i.Id).ToList();
progress.Report(15);
numComplete = 0;
var programs = new List<LiveTvProgram>();
var guideDays = GetGuideDays(list.Count);
cancellationToken.ThrowIfCancellationRequested();
foreach (var item in list)
{
cancellationToken.ThrowIfCancellationRequested();
// Avoid implicitly captured closure
var currentChannel = item;
try
{
var start = DateTime.UtcNow.AddHours(-1);
var end = start.AddDays(guideDays);