diff options
Diffstat (limited to 'Emby.Server.Implementations/LiveTv')
19 files changed, 688 insertions, 519 deletions
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 0c7980ca0..327b0181a 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -8,7 +8,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source is infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { - _logger.Info("Opened recording stream from tuner provider"); + _logger.LogInformation("Opened recording stream from tuner provider"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); @@ -86,7 +86,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 167f2a84b..ef96510bd 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -12,7 +12,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -170,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating virtual folder", ex); + _logger.LogError(ex, "Error creating virtual folder"); } pathsAdded.AddRange(pathsToCreate); @@ -196,13 +196,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating recording folders", ex); + _logger.LogError(ex, "Error creating recording folders"); } } private async Task RemovePathFromLibrary(string path) { - _logger.Debug("Removing path from library: {0}", path); + _logger.LogDebug("Removing path from library: {0}", path); var requiresRefresh = false; var virtualFolders = _libraryManager.GetVirtualFolders() @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing virtual folder", ex); + _logger.LogError(ex, "Error removing virtual folder"); } } else @@ -236,14 +236,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing media path", ex); + _logger.LogError(ex, "Error removing media path"); } } } if (requiresRefresh) { - _libraryManager.ValidateMediaLibrary(new SimpleProgress<Double>(), CancellationToken.None); + await _libraryManager.ValidateMediaLibrary(new SimpleProgress<Double>(), CancellationToken.None); } } @@ -342,7 +342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -364,7 +364,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error adding metadata", ex); + _logger.LogError(ex, "Error adding metadata"); } } } @@ -406,7 +406,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var channel in channels) { - _logger.Info("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); + _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); } result = new EpgChannelData(channels); @@ -595,7 +595,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -718,7 +718,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -984,11 +984,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId)) { - _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); continue; } - _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false); @@ -996,7 +996,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (epgChannel == null) { - _logger.Debug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); programs = new List<ProgramInfo>(); } else @@ -1042,7 +1042,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public async Task<ILiveStream> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken) { - _logger.Info("Streaming Channel " + channelId); + _logger.LogInformation("Streaming Channel " + channelId); var result = string.IsNullOrEmpty(streamId) ? null : @@ -1052,7 +1052,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { result.ConsumerCount++; - _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); + _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); return result; } @@ -1067,7 +1067,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV result.OriginalStreamId = streamId; - _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); + _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); return result; } @@ -1174,7 +1174,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var timer = e.Argument; - _logger.Info("Recording timer fired for {0}.", timer.Name); + _logger.LogInformation("Recording timer fired for {0}.", timer.Name); try { @@ -1182,7 +1182,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingEndDate <= DateTime.UtcNow) { - _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); + _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); OnTimerOutOfDate(timer); return; } @@ -1190,7 +1190,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false); if (!registration.IsValid) { - _logger.Warn("Emby Premiere required to use Emby DVR."); + _logger.LogWarning("Emby Premiere required to use Emby DVR."); OnTimerOutOfDate(timer); return; } @@ -1208,7 +1208,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _logger.Info("Skipping RecordStream because it's already in progress."); + _logger.LogInformation("Skipping RecordStream because it's already in progress."); } } catch (OperationCanceledException) @@ -1217,7 +1217,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error recording stream", ex); + _logger.LogError(ex, "Error recording stream"); } } @@ -1342,7 +1342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -1390,9 +1390,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var duration = recordingEndDate - DateTime.UtcNow; - _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); - _logger.Info("Writing file to path: " + recordPath); + _logger.LogInformation("Writing file to path: " + recordPath); Action onStarted = async () => { @@ -1414,16 +1414,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false); recordingStatus = RecordingStatus.Completed; - _logger.Info("Recording completed: {0}", recordPath); + _logger.LogInformation("Recording completed: {recordPath}", recordPath); } catch (OperationCanceledException) { - _logger.Info("Recording stopped: {0}", recordPath); + _logger.LogInformation("Recording stopped: {recordPath}", recordPath); recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { - _logger.ErrorException("Error recording to {0}", ex, recordPath); + _logger.LogError(ex, "Error recording to {recordPath}", recordPath); recordingStatus = RecordingStatus.Error; } @@ -1435,7 +1435,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error closing live stream", ex); + _logger.LogError(ex, "Error closing live stream"); } } @@ -1450,7 +1450,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) { const int retryIntervalSeconds = 60; - _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds); + _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds); timer.Status = RecordingStatus.New; timer.PrePaddingSeconds = 0; @@ -1511,22 +1511,22 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting 0-byte failed recording file {0}", ex, path); + _logger.LogError(ex, "Error deleting 0-byte failed recording file {path}", path); } } } private void TriggerRefresh(string path) { - _logger.Info("Triggering refresh on {0}", path); + _logger.LogInformation("Triggering refresh on {path}", path); var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); if (item != null) { - _logger.Info("Refreshing recording parent {0}", item.Path); + _logger.LogInformation("Refreshing recording parent {path}", item.Path); - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { RefreshPaths = new string[] { @@ -1642,7 +1642,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting item", ex); + _logger.LogError(ex, "Error deleting item"); } } } @@ -1668,7 +1668,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting recording", ex); + _logger.LogError(ex, "Error deleting recording"); } } } @@ -1773,14 +1773,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV UseShellExecute = false }); - _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); process.Exited += Process_Exited; process.Start(); } catch (Exception ex) { - _logger.ErrorException("Error running recording post processor", ex); + _logger.LogError(ex, "Error running recording post processor"); } } @@ -1794,7 +1794,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var process = (IProcess)sender; try { - _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode); + _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); } catch { @@ -1875,7 +1875,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1890,7 +1890,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1903,7 +1903,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1916,7 +1916,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } } @@ -1984,7 +1984,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving nfo", ex); + _logger.LogError(ex, "Error saving nfo"); } } @@ -2790,7 +2790,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase)) { - _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); + _logger.LogInformation("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); configuredDevice.Url = device.Url; await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false); @@ -2807,14 +2807,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var device in discoveredDevices) { - _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url); + _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url); } return discoveredDevices; } catch (Exception ex) { - _logger.ErrorException("Error discovering tuner devices", ex); + _logger.LogError(ex, "Error discovering tuner devices"); return new List<TunerHostInfo>(); } @@ -2827,4 +2827,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata"); } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 9506a82be..4ea83b7ac 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -8,7 +8,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; - using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -18,7 +17,7 @@ using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Library; @@ -78,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false); - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private EncodingOptions GetEncodingOptions() @@ -112,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _process = process; var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - _logger.Info(commandLineLogMessage); + _logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(logFilePath)); @@ -137,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback StartStreamingLog(process.StandardError.BaseStream, _logFileStream); - _logger.Info("ffmpeg recording process started for {0}", _targetPath); + _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); return _taskCompletionSource.Task; } @@ -270,14 +269,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath); //process.Kill(); _process.StandardInput.WriteLine("q"); } catch (Exception ex) { - _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath); } if (_hasExited) @@ -287,7 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath); + _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath); if (_process.WaitForExit(10000)) { @@ -296,7 +295,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath); + _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath); } if (_hasExited) @@ -306,13 +305,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Killing ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath); _process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath); } } } @@ -330,7 +329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var exitCode = process.ExitCode; - _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath); + _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath); if (exitCode == 0) { @@ -338,13 +337,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode))); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode))); } } catch { - _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath); - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath))); + _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath))); } } @@ -358,7 +357,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error disposing recording log stream", ex); + _logger.LogError(ex, "Error disposing recording log stream"); } _logFileStream = null; @@ -388,8 +387,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error reading ffmpeg recording log", ex); + _logger.LogError(ex, "Error reading ffmpeg recording log"); } } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 4ba2269a6..9f179dc2c 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (_items == null) { - Logger.Info("Loading live tv data from {0}", _dataPath); + Logger.LogInformation("Loading live tv data from {0}", _dataPath); _items = GetItemsFromFile(_dataPath); } return _items.ToList(); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - Logger.ErrorException("Error deserializing {0}", ex, jsonFile); + Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile); } return new List<T>(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 63cd26c7e..620ba7650 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using MediaBrowser.Model.IO; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index b5f93b882..5618579f6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Events; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -122,7 +122,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (startDate < now) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = item }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = item }, base.Logger); return; } @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error scheduling wake timer", ex); + _logger.LogError(ex, "Error scheduling wake timer"); } } @@ -153,12 +153,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (_timers.TryAdd(item.Id, timer)) { - _logger.Info("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); } else { timer.Dispose(); - _logger.Warn("Timer already exists for item {0}", item.Id); + _logger.LogWarning("Timer already exists for item {id}", item.Id); } } @@ -178,7 +178,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase)); if (timer != null) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = timer }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = timer }, base.Logger); } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 9021666a3..e8ffd0caa 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -16,8 +16,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Extensions; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.LiveTv.Listings @@ -32,9 +30,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; - private readonly Dictionary<string, Dictionary<string, ScheduleDirect.Station>> _channelPairingCache = - new Dictionary<string, Dictionary<string, ScheduleDirect.Station>>(StringComparer.OrdinalIgnoreCase); - public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost) { _logger = logger; @@ -74,33 +69,29 @@ namespace Emby.Server.Implementations.LiveTv.Listings // Normalize incoming input channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I'); - List<ProgramInfo> programsInfo = new List<ProgramInfo>(); - var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { - _logger.Warn("SchedulesDirect token is empty, returning empty program list"); - return programsInfo; + _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); + + return Enumerable.Empty<ProgramInfo>(); } var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); - string stationID = channelId; - - _logger.Info("Channel Station ID is: " + stationID); - List<ScheduleDirect.RequestScheduleForChannel> requestList = - new List<ScheduleDirect.RequestScheduleForChannel>() + _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId); + var requestList = new List<ScheduleDirect.RequestScheduleForChannel>() + { + new ScheduleDirect.RequestScheduleForChannel() { - new ScheduleDirect.RequestScheduleForChannel() - { - stationID = stationID, - date = dates - } - }; + stationID = channelId, + date = dates + } + }; var requestString = _jsonSerializer.SerializeToString(requestList); - _logger.Debug("Request string for schedules is: " + requestString); + _logger.LogDebug("Request string for schedules is: {RequestString}", requestString); var httpOptions = new HttpRequestOptions() { @@ -109,18 +100,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken = cancellationToken, // The data can be large so give it some extra time TimeoutMs = 60000, - LogErrorResponseBody = true + LogErrorResponseBody = true, + RequestContent = requestString }; httpOptions.RequestHeaders["token"] = token; - httpOptions.RequestContent = requestString; using (var response = await Post(httpOptions, true, info).ConfigureAwait(false)) + using (StreamReader reader = new StreamReader(response.Content)) { - StreamReader reader = new StreamReader(response.Content); - string responseString = reader.ReadToEnd(); - var dailySchedules = _jsonSerializer.DeserializeFromString<List<ScheduleDirect.Day>>(responseString); - _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); + var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(response.Content).ConfigureAwait(false); + _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); httpOptions = new HttpRequestOptions() { @@ -134,22 +124,13 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestHeaders["token"] = token; - List<string> programsID = new List<string>(); - programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList(); - var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]"; - httpOptions.RequestContent = requestBody; - - double wideAspect = 1.77777778; - var primaryImageCategory = "Logo"; + var programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct(); + httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]"; using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false)) + using (StreamReader innerReader = new StreamReader(innerResponse.Content)) { - StreamReader innerReader = new StreamReader(innerResponse.Content); - responseString = innerReader.ReadToEnd(); - - var programDetails = - _jsonSerializer.DeserializeFromString<List<ScheduleDirect.ProgramDetails>>( - responseString); + var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponse.Content).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); var programIdsWithImages = @@ -158,10 +139,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); - var schedules = dailySchedules.SelectMany(d => d.programs); - foreach (ScheduleDirect.Program schedule in schedules) + List<ProgramInfo> programsInfo = new List<ProgramInfo>(); + foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs)) { - //_logger.Debug("Proccesing Schedule for statio ID " + stationID + + //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID + // " which corresponds to channel " + channelNumber + " and program id " + // schedule.programID + " which says it has images? " + // programDict[schedule.programID].hasImageArtwork); @@ -173,15 +154,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings { var programEntry = programDict[schedule.programID]; - var allImages = (images[imageIndex].data ?? new List<ScheduleDirect.ImageData>()).ToList(); - var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList(); - var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)).ToList(); + var allImages = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>(); + var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)); + var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)); - double desiredAspect = 0.666666667; + const double desiredAspect = 0.666666667; programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ?? GetProgramImage(ApiUrl, allImages, true, desiredAspect); + const double wideAspect = 1.77777778; + programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect); // Don't supply the same image twice @@ -201,18 +184,16 @@ namespace Emby.Server.Implementations.LiveTv.Listings programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID])); } + return programsInfo; } } - - return programsInfo; } private int GetSizeOrder(ScheduleDirect.ImageData image) { if (!string.IsNullOrWhiteSpace(image.height)) { - int value; - if (int.TryParse(image.height, out value)) + if (int.TryParse(image.height, out int value)) { return value; } @@ -233,9 +214,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings { channelNumber = map.atscMajor + "." + map.atscMinor; } - channelNumber = channelNumber.TrimStart('0'); - return channelNumber; + return channelNumber.TrimStart('0'); } private bool IsMovie(ScheduleDirect.ProgramDetails programInfo) @@ -390,8 +370,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (details.movie != null) { - int year; - if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out year)) + if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out int year)) { info.ProductionYear = year; } @@ -422,18 +401,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings return date; } - private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect) + private string GetProgramImage(string apiUrl, IEnumerable<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect) { - string url = null; - - var matches = images; - - matches = matches - .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i))) + var match = images + .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) .ThenByDescending(GetSizeOrder) - .ToList(); - - var match = matches.FirstOrDefault(); + .FirstOrDefault(); if (match == null) { @@ -442,22 +415,21 @@ namespace Emby.Server.Implementations.LiveTv.Listings var uri = match.uri; - if (!string.IsNullOrWhiteSpace(uri)) + if (string.IsNullOrWhiteSpace(uri)) { - if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1) - { - url = uri; - } - else - { - url = apiUrl + "/image/" + uri; - } + return null; + } + else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1) + { + return uri; + } + else + { + return apiUrl + "/image/" + uri; } - //_logger.Debug("URL for image is : " + url); - return url; } - private double GetApsectRatio(ScheduleDirect.ImageData i) + private double GetAspectRatio(ScheduleDirect.ImageData i) { int width = 0; int height = 0; @@ -527,7 +499,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.ErrorException("Error getting image info from schedules direct", ex); + _logger.LogError(ex, "Error getting image info from schedules direct"); return new List<ScheduleDirect.ShowImages>(); } @@ -557,35 +529,33 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using (var httpResponse = await Get(options, false, info).ConfigureAwait(false)) + using (Stream responce = httpResponse.Content) { - using (Stream responce = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false); - if (root != null) + if (root != null) + { + foreach (ScheduleDirect.Headends headend in root) { - foreach (ScheduleDirect.Headends headend in root) + foreach (ScheduleDirect.Lineup lineup in headend.lineups) { - foreach (ScheduleDirect.Lineup lineup in headend.lineups) + lineups.Add(new NameIdPair { - lineups.Add(new NameIdPair - { - Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, - Id = lineup.uri.Substring(18) - }); - } + Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, + Id = lineup.uri.Substring(18) + }); } } - else - { - _logger.Info("No lineups available"); - } + } + else + { + _logger.LogInformation("No lineups available"); } } } catch (Exception ex) { - _logger.Error("Error getting headends", ex); + _logger.LogError(ex, "Error getting headends"); } return lineups; @@ -624,8 +594,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value)) { - long ticks; - if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks)) + if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks)) { // If it's under 24 hours old we can still use it if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks) @@ -695,8 +664,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); - options.RequestHeaders["token"] = newToken; + options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);; return await Post(options, false, providerInfo).ConfigureAwait(false); } @@ -734,8 +702,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); - options.RequestHeaders["token"] = newToken; + options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); return await Get(options, false, providerInfo).ConfigureAwait(false); } @@ -750,15 +717,15 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken = cancellationToken, LogErrorResponseBody = true }; - //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + + //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + // httpOptions.RequestContent); - using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false)) + using (var response = await Post(httpOptions, false, null).ConfigureAwait(false)) { - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(responce.Content).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(response.Content).ConfigureAwait(false); if (root.message == "OK") { - _logger.Info("Authenticated with Schedules Direct token: " + root.token); + _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); return root.token; } @@ -780,7 +747,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new ArgumentException("Listings Id required"); } - _logger.Info("Adding new LineUp "); + _logger.LogInformation("Adding new LineUp "); var httpOptions = new HttpRequestOptions() { @@ -823,7 +790,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new Exception("token required"); } - _logger.Info("Headends on account "); + _logger.LogInformation("Headends on account "); var options = new HttpRequestOptions() { @@ -838,13 +805,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using (var httpResponse = await Get(options, false, null).ConfigureAwait(false)) + using (var response = httpResponse.Content) { - using (var response = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false); - return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); - } + return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); } } catch (HttpException ex) @@ -923,54 +888,41 @@ namespace Emby.Server.Implementations.LiveTv.Listings var list = new List<ChannelInfo>(); using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false)) + using (var response = httpResponse.Content) { - using (var response = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false); - _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); - _logger.Info("Mapping Stations to Channel"); - - var allStations = root.stations ?? new List<ScheduleDirect.Station>(); - - foreach (ScheduleDirect.Map map in root.map) - { - var channelNumber = GetChannelNumber(map); + var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false); + _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); + _logger.LogInformation("Mapping Stations to Channel"); - var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); - if (station == null) - { - station = new ScheduleDirect.Station - { - stationID = map.stationID - }; - } + var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>(); - var name = channelNumber; + foreach (ScheduleDirect.Map map in root.map) + { + var channelNumber = GetChannelNumber(map); - var channelInfo = new ChannelInfo + var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); + if (station == null) + { + station = new ScheduleDirect.Station { - Number = channelNumber, - Name = name + stationID = map.stationID }; + } - if (station != null) - { - if (!string.IsNullOrWhiteSpace(station.name)) - { - channelInfo.Name = station.name; - } - - channelInfo.Id = station.stationID; - channelInfo.CallSign = station.callsign; - - if (station.logo != null) - { - channelInfo.ImageUrl = station.logo.URL; - } - } + var channelInfo = new ChannelInfo + { + Id = station.stationID, + CallSign = station.callsign, + Number = channelNumber, + Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name + }; - list.Add(channelInfo); + if (station.logo != null) + { + channelInfo.ImageUrl = station.logo.URL; } + + list.Add(channelInfo); } } @@ -1298,4 +1250,4 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs new file mode 100644 index 000000000..4d7c7fef4 --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Emby.XmlTv.Classes; +using Emby.XmlTv.Entities; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; +using MediaBrowser.Common.Progress; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.LiveTv; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Implementations.LiveTv.Listings +{ + public class XmlTvListingsProvider : IListingsProvider + { + private readonly IServerConfigurationManager _config; + private readonly IHttpClient _httpClient; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + private readonly IZipClient _zipClient; + + public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IFileSystem fileSystem, IZipClient zipClient) + { + _config = config; + _httpClient = httpClient; + _logger = logger; + _fileSystem = fileSystem; + _zipClient = zipClient; + } + + public string Name + { + get { return "XmlTV"; } + } + + public string Type + { + get { return "xmltv"; } + } + + private string GetLanguage(ListingsProviderInfo info) + { + if (!string.IsNullOrWhiteSpace(info.PreferredLanguage)) + { + return info.PreferredLanguage; + } + + return _config.Configuration.PreferredMetadataLanguage; + } + + private async Task<string> GetXml(string path, CancellationToken cancellationToken) + { + _logger.LogInformation("xmltv path: {path}", path); + + if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return UnzipIfNeeded(path, path); + } + + string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; + string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); + if (_fileSystem.FileExists(cacheFile)) + { + return UnzipIfNeeded(path, cacheFile); + } + + _logger.LogInformation("Downloading xmltv listings from {path}", path); + + string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = path, + Progress = new SimpleProgress<Double>(), + DecompressionMethod = CompressionMethod.Gzip, + + // It's going to come back gzipped regardless of this value + // So we need to make sure the decompression method is set to gzip + EnableHttpCompression = true, + + UserAgent = "Emby/3.0" + + }).ConfigureAwait(false); + + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFile)); + + _fileSystem.CopyFile(tempFile, cacheFile, true); + + return UnzipIfNeeded(path, cacheFile); + } + + private string UnzipIfNeeded(string originalUrl, string file) + { + string ext = Path.GetExtension(originalUrl.Split('?')[0]); + + if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase)) + { + try + { + string tempFolder = ExtractGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error extracting from gz file {file}", file); + } + + try + { + string tempFolder = ExtractFirstFileFromGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error extracting from zip file {file}", file); + } + } + + return file; + } + + private string ExtractFirstFileFromGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml"); + + return tempFolder; + } + } + + private string ExtractGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractAllFromGz(stream, tempFolder, true); + + return tempFolder; + } + } + + private string FindXmlFile(string directory) + { + return _fileSystem.GetFiles(directory, true) + .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase)) + .Select(i => i.FullName) + .FirstOrDefault(); + } + + public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(channelId)) + { + throw new ArgumentNullException("channelId"); + } + + /* + if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false)) + { + var length = endDateUtc - startDateUtc; + if (length.TotalDays > 1) + { + endDateUtc = startDateUtc.AddDays(1); + } + }*/ + + _logger.LogDebug("Getting xmltv programs for channel {id}", channelId); + + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + + return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) + .Select(p => GetProgramInfo(p, info)); + } + + private ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) + { + string episodeTitle = program.Episode?.Title; + + var programInfo = new ProgramInfo + { + ChannelId = program.ChannelId, + EndDate = program.EndDate.UtcDateTime, + EpisodeNumber = program.Episode?.Episode, + EpisodeTitle = episodeTitle, + Genres = program.Categories, + StartDate = program.StartDate.UtcDateTime, + Name = program.Title, + Overview = program.Description, + ProductionYear = program.CopyrightDate?.Year, + SeasonNumber = program.Episode?.Series, + IsSeries = program.Episode != null, + IsRepeat = program.IsPreviouslyShown && !program.IsNew, + IsPremiere = program.Premiere != null, + IsKids = program.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + ImageUrl = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null, + HasImage = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source), + OfficialRating = program.Rating != null && !String.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null, + CommunityRating = program.StarRating, + SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N") + }; + + if (string.IsNullOrWhiteSpace(program.ProgramId)) + { + string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/; + + if (programInfo.SeasonNumber.HasValue) + { + uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture); + } + if (programInfo.EpisodeNumber.HasValue) + { + uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture); + } + + programInfo.ShowId = uniqueString.GetMD5().ToString("N"); + + // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped + if (programInfo.IsSeries + && !programInfo.IsRepeat + && (programInfo.EpisodeNumber ?? 0) == 0) + { + programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); + } + } + else + { + programInfo.ShowId = program.ProgramId; + } + + // Construct an id from the channel and start date + programInfo.Id = String.Format("{0}_{1:O}", program.ChannelId, program.StartDate); + + if (programInfo.IsMovie) + { + programInfo.IsSeries = false; + programInfo.EpisodeNumber = null; + programInfo.EpisodeTitle = null; + } + + return programInfo; + } + + public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) + { + // Assume all urls are valid. check files for existence + if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path)) + { + throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); + } + + return Task.CompletedTask; + } + + public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location) + { + // In theory this should never be called because there is always only one lineup + string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + IEnumerable<XmlTvChannel> results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); + } + + public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) + { + // In theory this should never be called because there is always only one lineup + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.LogDebug("Opening XmlTvReader for {path}", path); + var reader = new XmlTvReader(path, GetLanguage(info)); + IEnumerable<XmlTvChannel> results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new ChannelInfo + { + Id = c.Id, + Name = c.DisplayName, + ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null, + Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number + + }).ToList(); + } + } +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index b0ffd057d..6fe578715 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -170,6 +170,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -185,6 +186,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -212,6 +214,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } @@ -230,6 +233,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -260,6 +264,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -275,6 +280,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -333,6 +339,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -376,7 +383,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting image info for {0}", ex, info.Name); + _logger.LogError(ex, "Error getting image info for {name}", info.Name); } return null; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 2e9679678..a4ffbd2fe 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Common; -using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Configuration; @@ -14,13 +13,11 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.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; @@ -29,7 +26,6 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Security; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; @@ -136,9 +132,7 @@ namespace Emby.Server.Implementations.LiveTv { service.DataSourceChanged += service_DataSourceChanged; - var embyTv = service as EmbyTV.EmbyTV; - - if (embyTv != null) + if (service is EmbyTV.EmbyTV embyTv) { embyTv.TimerCreated += EmbyTv_TimerCreated; embyTv.TimerCancelled += EmbyTv_TimerCancelled; @@ -255,18 +249,15 @@ namespace Emby.Server.Implementations.LiveTv mediaSourceId = null; } - MediaSourceInfo info; - bool isVideo; - ILiveTvService service; - ILiveStream liveStream; - var channel = (LiveTvChannel)_libraryManager.GetItemById(id); - isVideo = channel.ChannelType == ChannelType.TV; - service = GetService(channel); - _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); - var supportsManagedStream = service as ISupportsDirectStreamProvider; - if (supportsManagedStream != null) + bool isVideo = channel.ChannelType == ChannelType.TV; + ILiveTvService service = GetService(channel); + _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); + + MediaSourceInfo info; + ILiveStream liveStream; + if (service is ISupportsDirectStreamProvider supportsManagedStream) { liveStream = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(channel.ExternalId, mediaSourceId, currentLiveStreams, cancellationToken).ConfigureAwait(false); info = liveStream.MediaSource; @@ -282,7 +273,7 @@ namespace Emby.Server.Implementations.LiveTv var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - _logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + _logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); } info.RequiresClosing = true; @@ -307,14 +298,12 @@ namespace Emby.Server.Implementations.LiveTv throw new NotImplementedException(); } - var list = sources.ToList(); - - foreach (var source in list) + foreach (var source in sources) { Normalize(source, service, baseItem.ChannelType == ChannelType.TV); } - return list; + return sources; } private ILiveTvService GetService(LiveTvChannel item) @@ -546,13 +535,11 @@ namespace Emby.Server.Implementations.LiveTv { var id = _tvDtoService.GetInternalProgramId(info.Id); - LiveTvProgram item = null; - allExistingPrograms.TryGetValue(id, out item); - var isNew = false; var forceUpdate = false; - if (item == null) + LiveTvProgram item; + if (!allExistingPrograms.TryGetValue(id, out item)) { isNew = true; item = new LiveTvProgram @@ -787,11 +774,9 @@ namespace Emby.Server.Implementations.LiveTv var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user); - var list = new List<Tuple<BaseItemDto, string, string>>(); - - var externalSeriesId = program.ExternalSeriesId; - - list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, externalSeriesId)); + var list = new List<Tuple<BaseItemDto, string, string>>() { + new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId) + }; await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false); @@ -932,13 +917,11 @@ namespace Emby.Server.Implementations.LiveTv programs = programs.Take(query.Limit.Value); } - var result = new QueryResult<BaseItem> - { - Items = programs.ToArray(), - TotalRecordCount = totalCount - }; - - return result; + return new QueryResult<BaseItem> + { + Items = programs.ToArray(), + TotalRecordCount = totalCount + }; } public QueryResult<BaseItemDto> GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken) @@ -952,17 +935,11 @@ namespace Emby.Server.Implementations.LiveTv var internalResult = GetRecommendedProgramsInternal(query, options, cancellationToken); - var user = query.User; - - var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user); - - var result = new QueryResult<BaseItemDto> - { - Items = returnArray, - TotalRecordCount = internalResult.TotalRecordCount - }; - - return result; + return new QueryResult<BaseItemDto> + { + Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User), + TotalRecordCount = internalResult.TotalRecordCount + }; } private int GetRecommendationScore(LiveTvProgram program, User user, bool factorChannelWatchCount) @@ -981,28 +958,26 @@ namespace Emby.Server.Implementations.LiveTv var channel = _libraryManager.GetItemById(program.ChannelId); - if (channel != null) + if (channel == null) { - var channelUserdata = _userDataManager.GetUserData(user, channel); + return score; + } - if (channelUserdata.Likes ?? false) - { - score += 2; - } - else if (!(channelUserdata.Likes ?? true)) - { - score -= 2; - } + var channelUserdata = _userDataManager.GetUserData(user, channel); - if (channelUserdata.IsFavorite) - { - score += 3; - } + if (channelUserdata.Likes.HasValue) + { + score += channelUserdata.Likes.Value ? 2 : -2; + } - if (factorChannelWatchCount) - { - score += channelUserdata.PlayCount; - } + if (channelUserdata.IsFavorite) + { + score += 3; + } + + if (factorChannelWatchCount) + { + score += channelUserdata.PlayCount; } return score; @@ -1093,7 +1068,7 @@ namespace Emby.Server.Implementations.LiveTv { cancellationToken.ThrowIfCancellationRequested(); - _logger.Debug("Refreshing guide from {0}", service.Name); + _logger.LogDebug("Refreshing guide from {name}", service.Name); try { @@ -1112,7 +1087,7 @@ namespace Emby.Server.Implementations.LiveTv catch (Exception ex) { cleanDatabase = false; - _logger.ErrorException("Error refreshing channels for service", ex); + _logger.LogError(ex, "Error refreshing channels for service"); } numComplete++; @@ -1157,7 +1132,6 @@ namespace Emby.Server.Implementations.LiveTv var numComplete = 0; var parentFolder = GetInternalLiveTvFolder(cancellationToken); - var parentFolderId = parentFolder.Id; foreach (var channelInfo in allChannelsList) { @@ -1175,7 +1149,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name); + _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name); } numComplete++; @@ -1193,7 +1167,7 @@ namespace Emby.Server.Implementations.LiveTv var guideDays = GetGuideDays(); - _logger.Info("Refreshing guide with {0} days of guide data", guideDays); + _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays); cancellationToken.ThrowIfCancellationRequested(); @@ -1243,33 +1217,14 @@ namespace Emby.Server.Implementations.LiveTv programs.Add(programItem.Id); - if (program.IsMovie) - { - isMovie = true; - } - - if (program.IsSeries) - { - iSSeries = true; - } - - if (program.IsSports) - { - isSports = true; - } - - if (program.IsNews) - { - isNews = true; - } - - if (program.IsKids) - { - isKids = true; - } + isMovie |= program.IsMovie; + iSSeries |= program.IsSeries; + isSports |= program.IsSports; + isNews |= program.IsNews; + isKids |= program.IsKids; } - _logger.Debug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); + _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); if (newPrograms.Count > 0) { @@ -1292,7 +1247,7 @@ namespace Emby.Server.Implementations.LiveTv } //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken); - await currentChannel.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) + await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true @@ -1304,12 +1259,11 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name); + _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name); } numComplete++; - double percent = numComplete; - percent /= allChannelsList.Count; + double percent = numComplete / allChannelsList.Count; progress.Report(85 * percent + 15); } @@ -1324,7 +1278,6 @@ namespace Emby.Server.Implementations.LiveTv { IncludeItemTypes = validTypes, DtoOptions = new DtoOptions(false) - }); var numComplete = 0; @@ -1355,8 +1308,7 @@ namespace Emby.Server.Implementations.LiveTv } numComplete++; - double percent = numComplete; - percent /= list.Count; + double percent = numComplete / list.Count; progress.Report(100 * percent); } @@ -1418,28 +1370,22 @@ namespace Emby.Server.Implementations.LiveTv excludeItemTypes.Add(typeof(Episode).Name); } } - if (query.IsSports.HasValue) + if (query.IsSports ?? false) { - if (query.IsSports.Value) - { - genres.Add("Sports"); - } + genres.Add("Sports"); } - if (query.IsKids.HasValue) + if (query.IsKids ?? false) { - if (query.IsKids.Value) - { - genres.Add("Kids"); - genres.Add("Children"); - genres.Add("Family"); - } + genres.Add("Kids"); + genres.Add("Children"); + genres.Add("Family"); } var limit = query.Limit; - if ((query.IsInProgress ?? false)) + if (query.IsInProgress ?? false) { - limit = (query.Limit ?? 10) * 2; + // limit = (query.Limit ?? 10) * 2; limit = null; //var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray(); @@ -1471,7 +1417,7 @@ namespace Emby.Server.Implementations.LiveTv DtoOptions = dtoOptions }); - if ((query.IsInProgress ?? false)) + if (query.IsInProgress ?? false) { result.Items = result .Items @@ -1498,60 +1444,33 @@ namespace Emby.Server.Implementations.LiveTv dto.StartDate = program.StartDate; dto.EpisodeTitle = program.EpisodeTitle; - - if (program.IsRepeat) - { - dto.IsRepeat = program.IsRepeat; - } - if (program.IsMovie) - { - dto.IsMovie = program.IsMovie; - } - if (program.IsSeries) - { - dto.IsSeries = program.IsSeries; - } - if (program.IsSports) - { - dto.IsSports = program.IsSports; - } - if (program.IsLive) - { - dto.IsLive = program.IsLive; - } - if (program.IsNews) - { - dto.IsNews = program.IsNews; - } - if (program.IsKids) - { - dto.IsKids = program.IsKids; - } - if (program.IsPremiere) - { - dto.IsPremiere = program.IsPremiere; - } + dto.IsRepeat |= program.IsRepeat; + dto.IsMovie |= program.IsMovie; + dto.IsSeries |= program.IsSeries; + dto.IsSports |= program.IsSports; + dto.IsLive |= program.IsLive; + dto.IsNews |= program.IsNews; + dto.IsKids |= program.IsKids; + dto.IsPremiere |= program.IsPremiere; if (hasChannelInfo || hasChannelImage) { - var channel = _libraryManager.GetItemById(program.ChannelId) as LiveTvChannel; + var channel = _libraryManager.GetItemById(program.ChannelId); - if (channel != null) + if (channel is LiveTvChannel liveChannel) { - dto.ChannelName = channel.Name; - dto.MediaType = channel.MediaType; - dto.ChannelNumber = channel.Number; + dto.ChannelName = liveChannel.Name; + dto.MediaType = liveChannel.MediaType; + dto.ChannelNumber = liveChannel.Number; - if (hasChannelImage && channel.HasImage(ImageType.Primary)) + if (hasChannelImage && liveChannel.HasImage(ImageType.Primary)) { - dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel); + dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(liveChannel); } } } - var externalSeriesId = program.ExternalSeriesId; - - programTuples.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, externalSeriesId)); + programTuples.Add(new Tuple<BaseItemDto, string, string>(dto, program.ExternalId, program.ExternalSeriesId)); } return AddRecordingInfo(programTuples, CancellationToken.None); @@ -1649,7 +1568,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List<Tuple<TimerInfo, ILiveTvService>>(); } }); @@ -1725,7 +1644,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List<Tuple<TimerInfo, ILiveTvService>>(); } }); @@ -1880,7 +1799,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List<Tuple<SeriesTimerInfo, ILiveTvService>>(); } }); @@ -1926,7 +1845,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List<Tuple<SeriesTimerInfo, ILiveTvService>>(); } }); @@ -2041,19 +1960,13 @@ namespace Emby.Server.Implementations.LiveTv private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null) { - var service = program != null ? - GetService(program) : - null; - - if (service == null) - { - service = _services.First(); - } - + ILiveTvService service = null; ProgramInfo programInfo = null; - if (program != null) + if(program != null) { + service = GetService(program); + var channel = _libraryManager.GetItemById(program.ChannelId); programInfo = new ProgramInfo @@ -2081,6 +1994,11 @@ namespace Emby.Server.Implementations.LiveTv Name = program.Name, OfficialRating = program.OfficialRating }; + } + + if (service == null) + { + service = _services.First(); } var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false); @@ -2151,8 +2069,7 @@ namespace Emby.Server.Implementations.LiveTv info.Priority = defaultValues.Priority; string newTimerId = null; - var supportsNewTimerIds = service as ISupportsNewTimerIds; - if (supportsNewTimerIds != null) + if (service is ISupportsNewTimerIds supportsNewTimerIds) { newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false); newTimerId = _tvDtoService.GetInternalTimerId(newTimerId); @@ -2162,7 +2079,7 @@ namespace Emby.Server.Implementations.LiveTv await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false); } - _logger.Info("New recording scheduled"); + _logger.LogInformation("New recording scheduled"); if (!(service is EmbyTV.EmbyTV)) { @@ -2183,7 +2100,7 @@ namespace Emby.Server.Implementations.LiveTv if (!registration.IsValid) { - _logger.Info("Creating series recordings requires an active Emby Premiere subscription."); + _logger.LogInformation("Creating series recordings requires an active Emby Premiere subscription."); return; } @@ -2196,8 +2113,7 @@ namespace Emby.Server.Implementations.LiveTv info.Priority = defaultValues.Priority; string newTimerId = null; - var supportsNewTimerIds = service as ISupportsNewTimerIds; - if (supportsNewTimerIds != null) + if (service is ISupportsNewTimerIds supportsNewTimerIds) { newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false); newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N"); @@ -2358,8 +2274,7 @@ namespace Emby.Server.Implementations.LiveTv throw new ResourceNotFoundException(); } - var configurable = provider as IConfigurableTunerHost; - if (configurable != null) + if (provider is IConfigurableTunerHost configurable) { await configurable.Validate(info).ConfigureAwait(false); } @@ -2392,21 +2307,25 @@ namespace Emby.Server.Implementations.LiveTv public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { + // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider + // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider info = _jsonSerializer.DeserializeFromString<ListingsProviderInfo>(_jsonSerializer.SerializeToString(info)); - var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); + IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); if (provider == null) { - throw new ResourceNotFoundException(); + throw new ResourceNotFoundException( + string.Format("Couldn't find provider of type: '{0}'", info.Type) + ); } await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false); - var config = GetConfiguration(); + LiveTvOptions config = GetConfiguration(); - var list = config.ListingProviders.ToList(); - var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); + List<ListingsProviderInfo> list = config.ListingProviders.ToList(); + int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); if (index == -1 || string.IsNullOrWhiteSpace(info.Id)) { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 26a84a275..d13f08b1b 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -29,14 +29,14 @@ namespace Emby.Server.Implementations.LiveTv private readonly IServerApplicationHost _appHost; private IApplicationPaths _appPaths; - public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) + public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) { _liveTvManager = liveTvManager; _jsonSerializer = jsonSerializer; _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; _appHost = appHost; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _appPaths = appPaths; } @@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); + _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); return list; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index ca5e51971..ef2010ba6 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false); var list = result.ToList(); - //Logger.Info("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); + //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); if (!string.IsNullOrEmpty(key) && list.Count > 0) { @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error getting channel list", ex); + Logger.LogError(ex, "Error getting channel list"); if (enableCache) { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } } @@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } @@ -216,12 +216,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - Logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); return liveStream; } catch (Exception ex) { - Logger.Error("Error opening tuner", ex); + Logger.LogError(ex, "Error opening tuner"); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index e873eb8e9..be090df0c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -303,7 +303,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (Exception ex) { - Logger.ErrorException("Error getting tuner info", ex); + Logger.LogError(ex, "Error getting tuner info"); } } @@ -581,7 +581,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var profile = streamId.Split('_')[0]; - Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); + Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 2bc5a0ed3..0e84622bd 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -6,7 +6,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Controller.LiveTv; using System.Net; @@ -244,7 +244,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private async Task ReleaseLockkey(ISocket tcpClient, uint lockKeyValue) { - _logger.Info("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); + _logger.LogInformation("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 33103979e..c781bccbb 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; @@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); - Logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host); + Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host); var remoteAddress = IPAddress.Parse(uri.Host); var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host); @@ -69,9 +69,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address; tcpSocket.Close(); } - catch (Exception) + catch (Exception ex) { - Logger.Error("Unable to determine local ip address for Legacy HDHomerun stream."); + Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream."); return; } } @@ -87,21 +87,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun catch (Exception ex) { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + if (!(ex is OperationCanceledException)) { - if (!(ex is OperationCanceledException)) - { - Logger.ErrorException("Error opening live stream:", ex); - } - throw; + Logger.LogError(ex, "Error opening live stream:"); } + throw; } } var taskCompletionSource = new TaskCompletionSource<bool>(); - StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); + await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.Path = tempFile; @@ -122,26 +120,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return Task.Run(async () => { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + try { - try - { - await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException ex) - { - Logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); - openTaskCompletionSource.TrySetException(ex); - } - catch (Exception ex) - { - Logger.ErrorException("Error opening live stream:", ex); - openTaskCompletionSource.TrySetException(ex); - } - - EnableStreamSharing = false; + await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException ex) + { + Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); + openTaskCompletionSource.TrySetException(ex); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error opening live stream:"); + openTaskCompletionSource.TrySetException(ex); + } + + EnableStreamSharing = false; } await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false); @@ -166,30 +162,28 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var resolved = false; using (var source = _socketFactory.CreateNetworkStream(udpClient, false)) + using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) - { - var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; + var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; - while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) - { - cancellationToken.ThrowIfCancellationRequested(); + while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) + { + cancellationToken.ThrowIfCancellationRequested(); - currentCancellationToken = cancellationToken; + currentCancellationToken = cancellationToken; - read -= RtpHeaderBytes; + read -= RtpHeaderBytes; - if (read > 0) - { - fileStream.Write(buffer, RtpHeaderBytes, read); - } + if (read > 0) + { + fileStream.Write(buffer, RtpHeaderBytes, read); + } - if (!resolved) - { - resolved = true; - DateOpened = DateTime.UtcNow; - Resolve(openTaskCompletionSource); - } + if (!resolved) + { + resolved = true; + DateOpened = DateTime.UtcNow; + Resolve(openTaskCompletionSource); } } } @@ -346,4 +340,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 7e0ac4131..4a2b4ebb2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; using System.Linq; @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { EnableStreamSharing = false; - Logger.Info("Closing " + GetType().Name); + Logger.LogInformation("Closing " + GetType().Name); LiveStreamCancellationTokenSource.Cancel(); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error closing live stream", ex); + Logger.LogError(ex, "Error closing live stream"); } } @@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { if (retryCount == 0) { - Logger.Info("Deleting temp files {0}", string.Join(", ", paths.ToArray())); + Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray())); } var failedFiles = new List<string>(); @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - //Logger.ErrorException("Error deleting file {0}", ex, path); + Logger.LogError(ex, "Error deleting file {path}", path); failedFiles.Add(path); } } @@ -181,14 +181,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts isLastFile = nextFileInfo.Item2; } - Logger.Info("Live Stream ended."); + Logger.LogInformation("Live Stream ended."); } private Tuple<string, bool> GetNextFile(string currentFile) { var files = GetStreamFilePaths(); - //Logger.Info("Live stream files: {0}", string.Join(", ", files.ToArray())); + //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray())); if (string.IsNullOrEmpty(currentFile)) { @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken) { - //Logger.Info("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); + //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); using (var inputStream = (FileStream)GetInputStream(path, allowAsync)) { @@ -227,7 +227,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private void TrySeek(FileStream stream, long offset) { - //Logger.Info("TrySeek live stream"); + //logger.LogInformation("TrySeek live stream"); try { stream.Seek(offset, SeekOrigin.End); @@ -242,7 +242,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error seeking stream", ex); + Logger.LogError(ex, "Error seeking stream"); } } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index a1bff2b5b..a54bd1613 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -205,4 +205,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return Task.FromResult(new List<TunerHostInfo>()); } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index ca744b615..208225c1e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -12,7 +12,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.LiveTv.TunerHosts @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase)) { extInf = line.Substring(ExtInfPrefix.Length).Trim(); - _logger.Info("Found m3u channel: {0}", extInf); + _logger.LogInformation("Found m3u channel: {0}", extInf); } else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) { @@ -335,4 +335,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return dict; } } -}
\ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 572edb167..9b10daba0 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using System.Globalization; @@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); var typeName = GetType().Name; - Logger.Info("Opening " + typeName + " Live stream from {0}", url); + Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); var httpRequestOptions = new HttpRequestOptions { @@ -125,17 +125,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { try { + Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using (response) + using (var stream = response.Content) + using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var stream = response.Content) - { - Logger.Info("Beginning {0} stream to {1}", GetType().Name, TempFilePath); - - using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) - { - await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); - } - } + await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -143,7 +138,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error copying live stream.", ex); + Logger.LogError(ex, "Error copying live stream."); } EnableStreamSharing = false; await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false); |
