aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Emby.Drawing/ImageMagick/ImageMagickEncoder.cs5
-rw-r--r--MediaBrowser.Api/ApiEntryPoint.cs60
-rw-r--r--MediaBrowser.Api/ConnectService.cs34
-rw-r--r--MediaBrowser.Api/ItemUpdateService.cs6
-rw-r--r--MediaBrowser.Api/Library/LibraryStructureService.cs46
-rw-r--r--MediaBrowser.Api/LiveTv/LiveTvService.cs226
-rw-r--r--MediaBrowser.Api/Playback/BaseStreamingService.cs149
-rw-r--r--MediaBrowser.Api/Playback/Hls/BaseHlsService.cs60
-rw-r--r--MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs13
-rw-r--r--MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs4
-rw-r--r--MediaBrowser.Api/Playback/Hls/VideoHlsService.cs2
-rw-r--r--MediaBrowser.Api/Playback/MediaInfoService.cs2
-rw-r--r--MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs38
-rw-r--r--MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs9
-rw-r--r--MediaBrowser.Api/Playback/StreamState.cs12
-rw-r--r--MediaBrowser.Api/StartupWizardService.cs6
-rw-r--r--MediaBrowser.Api/Subtitles/SubtitleService.cs2
-rw-r--r--MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs1
-rw-r--r--MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs7
-rw-r--r--MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj6
-rw-r--r--MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs6
-rw-r--r--MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs16
-rw-r--r--MediaBrowser.Common.Implementations/packages.config4
-rw-r--r--MediaBrowser.Controller/Channels/IChannelManager.cs2
-rw-r--r--MediaBrowser.Controller/Collections/ManualCollectionsFolder.cs (renamed from MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs)2
-rw-r--r--MediaBrowser.Controller/Dlna/IDeviceDiscovery.cs14
-rw-r--r--MediaBrowser.Controller/Dlna/ISsdpHandler.cs1
-rw-r--r--MediaBrowser.Controller/Entities/Audio/Audio.cs2
-rw-r--r--MediaBrowser.Controller/Entities/BaseItem.cs24
-rw-r--r--MediaBrowser.Controller/Entities/CollectionFolder.cs31
-rw-r--r--MediaBrowser.Controller/Entities/Folder.cs38
-rw-r--r--MediaBrowser.Controller/Entities/IHasMetadata.cs3
-rw-r--r--MediaBrowser.Controller/Entities/InternalItemsQuery.cs6
-rw-r--r--MediaBrowser.Controller/Entities/UserView.cs3
-rw-r--r--MediaBrowser.Controller/Entities/Video.cs2
-rw-r--r--MediaBrowser.Controller/Library/ILibraryManager.cs10
-rw-r--r--MediaBrowser.Controller/Library/IMediaSourceManager.cs8
-rw-r--r--MediaBrowser.Controller/Library/IMediaSourceProvider.cs3
-rw-r--r--MediaBrowser.Controller/Library/NameExtensions.cs4
-rw-r--r--MediaBrowser.Controller/LiveTv/IHasRegistrationInfo.cs15
-rw-r--r--MediaBrowser.Controller/LiveTv/ILiveTvManager.cs26
-rw-r--r--MediaBrowser.Controller/LiveTv/ITunerHost.cs7
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveStream.cs43
-rw-r--r--MediaBrowser.Controller/LiveTv/LiveTvChannel.cs53
-rw-r--r--MediaBrowser.Controller/LiveTv/ProgramInfo.cs9
-rw-r--r--MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs10
-rw-r--r--MediaBrowser.Controller/LiveTv/TimerInfo.cs37
-rw-r--r--MediaBrowser.Controller/MediaBrowser.Controller.csproj5
-rw-r--r--MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs4
-rw-r--r--MediaBrowser.Controller/Power/IPowerManagement.cs13
-rw-r--r--MediaBrowser.Controller/Providers/BaseItemXmlParser.cs27
-rw-r--r--MediaBrowser.Controller/Providers/MetadataResult.cs4
-rw-r--r--MediaBrowser.Controller/RelatedMedia/IRelatedMediaProvider.cs11
-rw-r--r--MediaBrowser.Controller/Session/AuthenticationRequest.cs1
-rw-r--r--MediaBrowser.Dlna/Main/DlnaEntryPoint.cs113
-rw-r--r--MediaBrowser.Dlna/MediaBrowser.Dlna.csproj14
-rw-r--r--MediaBrowser.Dlna/PlayTo/Device.cs4
-rw-r--r--MediaBrowser.Dlna/PlayTo/PlayToController.cs20
-rw-r--r--MediaBrowser.Dlna/PlayTo/PlayToManager.cs26
-rw-r--r--MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs217
-rw-r--r--MediaBrowser.Dlna/Ssdp/SsdpHandler.cs383
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs86
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs24
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs104
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs15
-rw-r--r--MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj3
-rw-r--r--MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj5
-rw-r--r--MediaBrowser.Model/Configuration/AutoOnOff.cs10
-rw-r--r--MediaBrowser.Model/Configuration/EncodingOptions.cs1
-rw-r--r--MediaBrowser.Model/Configuration/LibraryOptions.cs9
-rw-r--r--MediaBrowser.Model/Configuration/ServerConfiguration.cs9
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs35
-rw-r--r--MediaBrowser.Model/Dlna/StreamInfo.cs17
-rw-r--r--MediaBrowser.Model/Dto/BaseItemDto.cs1
-rw-r--r--MediaBrowser.Model/Dto/ItemCounts.cs1
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceInfo.cs9
-rw-r--r--MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs1
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs36
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvOptions.cs3
-rw-r--r--MediaBrowser.Model/LiveTv/ProgramAudio.cs3
-rw-r--r--MediaBrowser.Model/LiveTv/ProgramQuery.cs8
-rw-r--r--MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs6
-rw-r--r--MediaBrowser.Model/LiveTv/RecordingQuery.cs5
-rw-r--r--MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs12
-rw-r--r--MediaBrowser.Model/MediaBrowser.Model.csproj1
-rw-r--r--MediaBrowser.Model/System/SystemInfo.cs2
-rw-r--r--MediaBrowser.Mono.sln18
-rw-r--r--MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs14
-rw-r--r--MediaBrowser.Providers/Manager/ItemImageProvider.cs24
-rw-r--r--MediaBrowser.Providers/Manager/MetadataService.cs86
-rw-r--r--MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs2
-rw-r--r--MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs4
-rw-r--r--MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs30
-rw-r--r--MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs13
-rw-r--r--MediaBrowser.Providers/Music/AudioMetadataService.cs3
-rw-r--r--MediaBrowser.Providers/Omdb/OmdbItemProvider.cs8
-rw-r--r--MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs3
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs7
-rw-r--r--MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs25
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs12
-rw-r--r--MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs22
-rw-r--r--MediaBrowser.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs2
-rw-r--r--MediaBrowser.Server.Implementations/Channels/ChannelManager.cs31
-rw-r--r--MediaBrowser.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs2
-rw-r--r--MediaBrowser.Server.Implementations/Collections/CollectionsDynamicFolder.cs1
-rw-r--r--MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs2
-rw-r--r--MediaBrowser.Server.Implementations/Connect/ConnectManager.cs24
-rw-r--r--MediaBrowser.Server.Implementations/Dto/DtoService.cs28
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs66
-rw-r--r--MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs6
-rw-r--r--MediaBrowser.Server.Implementations/IO/FileRefresher.cs10
-rw-r--r--MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs58
-rw-r--r--MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs7
-rw-r--r--MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs3
-rw-r--r--MediaBrowser.Server.Implementations/Library/LibraryManager.cs296
-rw-r--r--MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs81
-rw-r--r--MediaBrowser.Server.Implementations/Library/Resolvers/PhotoResolver.cs2
-rw-r--r--MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs5
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs65
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs804
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs119
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs29
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs72
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs163
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs19
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/LiveTvDtoService.cs8
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs519
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs4
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs150
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs9
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs131
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunLiveStream.cs166
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs19
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs11
-rw-r--r--MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs10
-rw-r--r--MediaBrowser.Server.Implementations/Localization/Ratings/de.txt5
-rw-r--r--MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj17
-rw-r--r--MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs20
-rw-r--r--MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs222
-rw-r--r--MediaBrowser.Server.Implementations/Session/SessionManager.cs31
-rw-r--r--MediaBrowser.Server.Implementations/Sync/SyncManager.cs5
-rw-r--r--MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs2
-rw-r--r--MediaBrowser.Server.Implementations/UserViews/CollectionFolderImageProvider.cs62
-rw-r--r--MediaBrowser.Server.Implementations/packages.config5
-rw-r--r--MediaBrowser.Server.Mac/Emby.Server.Mac.csproj59
-rw-r--r--MediaBrowser.Server.Mac/Native/BaseMonoApp.cs10
-rw-r--r--MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj5
-rw-r--r--MediaBrowser.Server.Mono/Native/BaseMonoApp.cs13
-rw-r--r--MediaBrowser.Server.Mono/app.config14
-rw-r--r--MediaBrowser.Server.Startup.Common/ApplicationHost.cs102
-rw-r--r--MediaBrowser.Server.Startup.Common/ApplicationPathHelper.cs8
-rw-r--r--MediaBrowser.Server.Startup.Common/INativeApp.cs9
-rw-r--r--MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj3
-rw-r--r--MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs2
-rw-r--r--MediaBrowser.Server.Startup.Common/Migrations/IVersionMigration.cs5
-rw-r--r--MediaBrowser.Server.Startup.Common/Migrations/MovieDbEpisodeProviderMigration.cs3
-rw-r--r--MediaBrowser.Server.Startup.Common/Migrations/UpdateLevelMigration.cs72
-rw-r--r--MediaBrowser.ServerApplication/MainStartup.cs100
-rw-r--r--MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj9
-rw-r--r--MediaBrowser.ServerApplication/Native/RegisterServer.bat2
-rw-r--r--MediaBrowser.ServerApplication/Native/WindowsApp.cs73
-rw-r--r--MediaBrowser.ServerApplication/Native/WindowsPowerManagement.cs94
-rw-r--r--MediaBrowser.ServerApplication/packages.config2
-rw-r--r--MediaBrowser.WebDashboard/Api/DashboardService.cs128
-rw-r--r--MediaBrowser.WebDashboard/Api/PackageCreator.cs2
-rw-r--r--MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj36
-rw-r--r--MediaBrowser.XbmcMetadata/EntryPoint.cs10
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs7
-rw-r--r--MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs26
-rw-r--r--MediaBrowser.sln32
-rw-r--r--Mono.Nat/AbstractNatDevice.cs97
-rw-r--r--Mono.Nat/AsyncResults/AsyncResult.cs71
-rw-r--r--Mono.Nat/Enums/MapState.cs36
-rw-r--r--Mono.Nat/Enums/ProtocolType.cs36
-rw-r--r--Mono.Nat/EventArgs/DeviceEventArgs.cs45
-rw-r--r--Mono.Nat/Exceptions/MappingException.cs87
-rw-r--r--Mono.Nat/IMapper.cs50
-rw-r--r--Mono.Nat/INatDevice.cs62
-rw-r--r--Mono.Nat/ISearcher.cs51
-rw-r--r--Mono.Nat/Mapping.cs123
-rw-r--r--Mono.Nat/Mono.Nat.csproj104
-rw-r--r--Mono.Nat/NatProtocol.cs9
-rw-r--r--Mono.Nat/NatUtility.cs264
-rw-r--r--Mono.Nat/Pmp/AsyncResults/PortMapAsyncResult.cs52
-rw-r--r--Mono.Nat/Pmp/Mappers/PmpMapper.cs83
-rw-r--r--Mono.Nat/Pmp/Pmp.cs118
-rw-r--r--Mono.Nat/Pmp/PmpConstants.cs56
-rw-r--r--Mono.Nat/Pmp/PmpNatDevice.cs347
-rw-r--r--Mono.Nat/Pmp/Searchers/PmpSearcher.cs149
-rw-r--r--Mono.Nat/Properties/AssemblyInfo.cs31
-rw-r--r--Mono.Nat/Upnp/AsyncResults/GetAllMappingsAsyncResult.cs56
-rw-r--r--Mono.Nat/Upnp/AsyncResults/PortMapAsyncResult.cs75
-rw-r--r--Mono.Nat/Upnp/Mappers/UpnpMapper.cs110
-rw-r--r--Mono.Nat/Upnp/Messages/DiscoverDeviceMessage.cs60
-rw-r--r--Mono.Nat/Upnp/Messages/ErrorMessage.cs63
-rw-r--r--Mono.Nat/Upnp/Messages/GetServicesMessage.cs62
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs75
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/DeletePortMappingMessage.cs57
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/GetExternalIPAddressMessage.cs51
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/GetGenericPortMappingEntry.cs55
-rw-r--r--Mono.Nat/Upnp/Messages/Requests/GetSpecificPortMappingEntryMessage.cs60
-rw-r--r--Mono.Nat/Upnp/Messages/Responses/CreatePortMappingResponseMessage.cs46
-rw-r--r--Mono.Nat/Upnp/Messages/Responses/DeletePortMappingResponseMessage.cs44
-rw-r--r--Mono.Nat/Upnp/Messages/Responses/GetExternalIPAddressResponseMessage.cs53
-rw-r--r--Mono.Nat/Upnp/Messages/Responses/GetGenericPortMappingEntryResponseMessage.cs108
-rw-r--r--Mono.Nat/Upnp/Messages/UpnpMessage.cs132
-rw-r--r--Mono.Nat/Upnp/Searchers/UpnpSearcher.cs287
-rw-r--r--Mono.Nat/Upnp/Upnp.cs83
-rw-r--r--Mono.Nat/Upnp/UpnpNatDevice.cs651
-rw-r--r--Nuget/MediaBrowser.Common.Internal.nuspec8
-rw-r--r--Nuget/MediaBrowser.Common.nuspec2
-rw-r--r--Nuget/MediaBrowser.Server.Core.nuspec4
213 files changed, 8294 insertions, 2424 deletions
diff --git a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs
index 3dbe7239d..c1881895f 100644
--- a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs
+++ b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs
@@ -53,7 +53,10 @@ namespace Emby.Drawing.ImageMagick
"arw",
"webp",
"gif",
- "bmp"
+ "bmp",
+ "erf",
+ "raf",
+ "rw2"
};
}
}
diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs
index 7c5f7cde4..c6e45c61a 100644
--- a/MediaBrowser.Api/ApiEntryPoint.cs
+++ b/MediaBrowser.Api/ApiEntryPoint.cs
@@ -8,6 +8,7 @@ using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Session;
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -15,6 +16,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
+using MediaBrowser.Model.Dto;
namespace MediaBrowser.Api
{
@@ -43,7 +45,13 @@ namespace MediaBrowser.Api
private readonly IFileSystem _fileSystem;
private readonly IMediaSourceManager _mediaSourceManager;
- public readonly SemaphoreSlim TranscodingStartLock = new SemaphoreSlim(1, 1);
+ /// <summary>
+ /// The active transcoding jobs
+ /// </summary>
+ private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
+
+ private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks =
+ new Dictionary<string, SemaphoreSlim>();
/// <summary>
/// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
@@ -66,6 +74,21 @@ namespace MediaBrowser.Api
_sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
}
+ public SemaphoreSlim GetTranscodingLock(string outputPath)
+ {
+ lock (_transcodingLocks)
+ {
+ SemaphoreSlim result;
+ if (!_transcodingLocks.TryGetValue(outputPath, out result))
+ {
+ result = new SemaphoreSlim(1, 1);
+ _transcodingLocks[outputPath] = result;
+ }
+
+ return result;
+ }
+ }
+
private void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
{
if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
@@ -148,11 +171,6 @@ namespace MediaBrowser.Api
}
/// <summary>
- /// The active transcoding jobs
- /// </summary>
- private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
-
- /// <summary>
/// Called when [transcode beginning].
/// </summary>
/// <param name="path">The path.</param>
@@ -187,7 +205,8 @@ namespace MediaBrowser.Api
CancellationTokenSource = cancellationTokenSource,
Id = transcodingJobId,
PlaySessionId = playSessionId,
- LiveStreamId = liveStreamId
+ LiveStreamId = liveStreamId,
+ MediaSource = state.MediaSource
};
_activeTranscodingJobs.Add(job);
@@ -256,6 +275,11 @@ namespace MediaBrowser.Api
}
}
+ lock (_transcodingLocks)
+ {
+ _transcodingLocks.Remove(path);
+ }
+
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
{
_sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
@@ -281,6 +305,14 @@ namespace MediaBrowser.Api
}
}
+ public TranscodingJob GetTranscodingJob(string playSessionId)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
/// <summary>
/// Called when [transcode begin request].
/// </summary>
@@ -487,6 +519,11 @@ namespace MediaBrowser.Api
}
}
+ lock (_transcodingLocks)
+ {
+ _transcodingLocks.Remove(job.Path);
+ }
+
lock (job.ProcessLock)
{
if (job.TranscodingThrottler != null)
@@ -530,7 +567,7 @@ namespace MediaBrowser.Api
{
try
{
- await _mediaSourceManager.CloseLiveStream(job.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
+ await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -656,6 +693,7 @@ namespace MediaBrowser.Api
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
+ public MediaSourceInfo MediaSource { get; set; }
public string Path { get; set; }
/// <summary>
/// Gets or sets the type.
@@ -751,12 +789,12 @@ namespace MediaBrowser.Api
{
if (KillTimer == null)
{
- Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer = new Timer(callback, this, intervalMs, Timeout.Infinite);
}
else
{
- Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer.Change(intervalMs, Timeout.Infinite);
}
}
@@ -775,7 +813,7 @@ namespace MediaBrowser.Api
{
var intervalMs = PingTimeout;
- Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
KillTimer.Change(intervalMs, Timeout.Infinite);
}
}
diff --git a/MediaBrowser.Api/ConnectService.cs b/MediaBrowser.Api/ConnectService.cs
index 4bcd33d9e..494a6e756 100644
--- a/MediaBrowser.Api/ConnectService.cs
+++ b/MediaBrowser.Api/ConnectService.cs
@@ -7,6 +7,7 @@ using ServiceStack;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
+using MediaBrowser.Controller.Session;
namespace MediaBrowser.Api
{
@@ -76,12 +77,12 @@ namespace MediaBrowser.Api
public class ConnectService : BaseApiService
{
private readonly IConnectManager _connectManager;
- private readonly IUserManager _userManager;
+ private readonly ISessionManager _sessionManager;
- public ConnectService(IConnectManager connectManager, IUserManager userManager)
+ public ConnectService(IConnectManager connectManager, ISessionManager sessionManager)
{
_connectManager = connectManager;
- _userManager = userManager;
+ _sessionManager = sessionManager;
}
public object Post(CreateConnectLink request)
@@ -141,10 +142,33 @@ namespace MediaBrowser.Api
throw new ResourceNotFoundException();
}
+ var auth = AuthorizationContext.GetAuthorizationInfo(Request);
+
+ if (string.IsNullOrWhiteSpace(auth.Client))
+ {
+ return ToOptimizedResult(new ConnectAuthenticationExchangeResult
+ {
+ AccessToken = user.ConnectAccessKey,
+ LocalUserId = user.Id.ToString("N")
+ });
+ }
+
+ var session = await _sessionManager.CreateNewSession(new AuthenticationRequest
+ {
+ App = auth.Client,
+ AppVersion = auth.Version,
+ DeviceId = auth.DeviceId,
+ DeviceName = auth.Device,
+ RemoteEndPoint = Request.RemoteIp,
+ Username = user.Name,
+ UserId = user.Id.ToString("N")
+
+ }).ConfigureAwait(false);
+
return ToOptimizedResult(new ConnectAuthenticationExchangeResult
{
- AccessToken = user.ConnectAccessKey,
- LocalUserId = user.Id.ToString("N")
+ AccessToken = session.AccessToken,
+ LocalUserId = session.User.Id
});
}
}
diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs
index cda7ce0c6..64b6b18d6 100644
--- a/MediaBrowser.Api/ItemUpdateService.cs
+++ b/MediaBrowser.Api/ItemUpdateService.cs
@@ -243,11 +243,7 @@ namespace MediaBrowser.Api
hasBudget.Revenue = request.Revenue;
}
- var hasOriginalTitle = item as IHasOriginalTitle;
- if (hasOriginalTitle != null)
- {
- hasOriginalTitle.OriginalTitle = hasOriginalTitle.OriginalTitle;
- }
+ item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;
var hasCriticRating = item as IHasCriticRating;
if (hasCriticRating != null)
diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs
index 72966a7cd..e872061a7 100644
--- a/MediaBrowser.Api/Library/LibraryStructureService.cs
+++ b/MediaBrowser.Api/Library/LibraryStructureService.cs
@@ -112,6 +112,8 @@ namespace MediaBrowser.Api.Library
/// <value>The name.</value>
public string Path { get; set; }
+ public MediaPathInfo PathInfo { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [refresh library].
/// </summary>
@@ -119,6 +121,18 @@ namespace MediaBrowser.Api.Library
public bool RefreshLibrary { get; set; }
}
+ [Route("/Library/VirtualFolders/Paths/Update", "POST")]
+ public class UpdateMediaPath : IReturnVoid
+ {
+ /// <summary>
+ /// Gets or sets the name.
+ /// </summary>
+ /// <value>The name.</value>
+ public string Name { get; set; }
+
+ public MediaPathInfo PathInfo { get; set; }
+ }
+
[Route("/Library/VirtualFolders/Paths", "DELETE")]
public class RemoveMediaPath : IReturnVoid
{
@@ -212,7 +226,12 @@ namespace MediaBrowser.Api.Library
{
var libraryOptions = request.LibraryOptions ?? new LibraryOptions();
- _libraryManager.AddVirtualFolder(request.Name, request.CollectionType, request.Paths, libraryOptions, request.RefreshLibrary);
+ if (request.Paths != null && request.Paths.Length > 0)
+ {
+ libraryOptions.PathInfos = request.Paths.Select(i => new MediaPathInfo { Path = i }).ToArray();
+ }
+
+ _libraryManager.AddVirtualFolder(request.Name, request.CollectionType, libraryOptions, request.RefreshLibrary);
}
/// <summary>
@@ -308,7 +327,16 @@ namespace MediaBrowser.Api.Library
try
{
- _libraryManager.AddMediaPath(request.Name, request.Path);
+ var mediaPath = request.PathInfo;
+
+ if (mediaPath == null)
+ {
+ mediaPath = new MediaPathInfo
+ {
+ Path = request.Path
+ };
+ }
+ _libraryManager.AddMediaPath(request.Name, mediaPath);
}
finally
{
@@ -333,6 +361,20 @@ namespace MediaBrowser.Api.Library
}
/// <summary>
+ /// Posts the specified request.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ public void Post(UpdateMediaPath request)
+ {
+ if (string.IsNullOrWhiteSpace(request.Name))
+ {
+ throw new ArgumentNullException("request");
+ }
+
+ _libraryManager.UpdateMediaPath(request.Name, request.PathInfo);
+ }
+
+ /// <summary>
/// Deletes the specified request.
/// </summary>
/// <param name="request">The request.</param>
diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs
index 545ac162f..ecc17374f 100644
--- a/MediaBrowser.Api/LiveTv/LiveTvService.cs
+++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs
@@ -12,9 +12,13 @@ using ServiceStack;
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using CommonIO;
+using MediaBrowser.Api.Playback.Progressive;
+using MediaBrowser.Controller.Configuration;
namespace MediaBrowser.Api.LiveTv
{
@@ -44,6 +48,21 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? StartIndex { get; set; }
+ [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsMovie { get; set; }
+
+ [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSeries { get; set; }
+
+ [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsNews { get; set; }
+
+ [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsKids { get; set; }
+
+ [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSports { get; set; }
+
/// <summary>
/// The maximum number of items to return
/// </summary>
@@ -85,6 +104,26 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? EnableUserData { get; set; }
+ public string SortBy { get; set; }
+
+ public SortOrder? SortOrder { get; set; }
+
+ /// <summary>
+ /// Gets the order by.
+ /// </summary>
+ /// <returns>IEnumerable{ItemSortBy}.</returns>
+ public string[] GetOrderBy()
+ {
+ var val = SortBy;
+
+ if (string.IsNullOrEmpty(val))
+ {
+ return new string[] { };
+ }
+
+ return val.Split(',');
+ }
+
public GetChannels()
{
AddCurrentProgram = true;
@@ -155,12 +194,73 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? EnableUserData { get; set; }
+ public bool? IsMovie { get; set; }
+ public bool? IsSeries { get; set; }
+ public bool? IsKids { get; set; }
+ public bool? IsSports { get; set; }
+ public bool? IsNews { get; set; }
+
public GetRecordings()
{
EnableTotalRecordCount = true;
}
}
+ [Route("/LiveTv/Recordings/Series", "GET", Summary = "Gets live tv recordings")]
+ [Authenticated]
+ public class GetRecordingSeries : IReturn<QueryResult<BaseItemDto>>, IHasDtoOptions
+ {
+ [ApiMember(Name = "ChannelId", Description = "Optional filter by channel id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public string ChannelId { get; set; }
+
+ [ApiMember(Name = "UserId", Description = "Optional filter by user and attach user data.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public string UserId { get; set; }
+
+ [ApiMember(Name = "GroupId", Description = "Optional filter by recording group.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public string GroupId { get; set; }
+
+ [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
+ public int? StartIndex { get; set; }
+
+ [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
+ public int? Limit { get; set; }
+
+ [ApiMember(Name = "Status", Description = "Optional filter by recording status.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public RecordingStatus? Status { get; set; }
+
+ [ApiMember(Name = "Status", Description = "Optional filter by recordings that are in progress, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
+ public bool? IsInProgress { get; set; }
+
+ [ApiMember(Name = "SeriesTimerId", Description = "Optional filter by recordings belonging to a series timer", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public string SeriesTimerId { get; set; }
+
+ [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
+ public bool? EnableImages { get; set; }
+
+ [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
+ public int? ImageTypeLimit { get; set; }
+
+ [ApiMember(Name = "EnableImageTypes", Description = "Optional. The image types to include in the output.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
+ public string EnableImageTypes { get; set; }
+
+ /// <summary>
+ /// Fields to return within the items, in addition to basic information
+ /// </summary>
+ /// <value>The fields.</value>
+ [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, CriticRatingSummary, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
+ public string Fields { get; set; }
+
+ public bool EnableTotalRecordCount { get; set; }
+
+ [ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
+ public bool? EnableUserData { get; set; }
+
+ public GetRecordingSeries()
+ {
+ EnableTotalRecordCount = true;
+ }
+ }
+
[Route("/LiveTv/Recordings/Groups", "GET", Summary = "Gets live tv recording groups")]
[Authenticated]
public class GetRecordingGroups : IReturn<QueryResult<BaseItemDto>>
@@ -245,6 +345,12 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
public bool? IsMovie { get; set; }
+ [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSeries { get; set; }
+
+ [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsNews { get; set; }
+
[ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
public bool? IsKids { get; set; }
@@ -280,6 +386,8 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "EnableUserData", Description = "Optional, include user data", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? EnableUserData { get; set; }
+ public string SeriesTimerId { get; set; }
+
/// <summary>
/// Fields to return within the items, in addition to basic information
/// </summary>
@@ -316,15 +424,21 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "HasAired", Description = "Optional. Filter by programs that have completed airing, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool? HasAired { get; set; }
- [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
- public bool? IsSports { get; set; }
+ [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSeries { get; set; }
- [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
+ [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
public bool? IsMovie { get; set; }
- [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
+ [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsNews { get; set; }
+
+ [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
public bool? IsKids { get; set; }
+ [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSports { get; set; }
+
[ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? EnableImages { get; set; }
@@ -535,12 +649,6 @@ namespace MediaBrowser.Api.LiveTv
[Authenticated]
public class GetLiveTvRegistrationInfo : IReturn<MBRegistrationRecord>
{
- [ApiMember(Name = "ChannelId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ChannelId { get; set; }
-
- [ApiMember(Name = "ProgramId", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
- public string ProgramId { get; set; }
-
[ApiMember(Name = "Feature", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string Feature { get; set; }
}
@@ -559,16 +667,26 @@ namespace MediaBrowser.Api.LiveTv
}
+ [Route("/LiveTv/LiveStreamFiles/{Id}/stream.{Container}", "GET", Summary = "Gets a live tv channel")]
+ public class GetLiveStreamFile
+ {
+ public string Id { get; set; }
+ public string Container { get; set; }
+ public long T { get; set; }
+ public long S { get; set; }
+ }
+
public class LiveTvService : BaseApiService
{
private readonly ILiveTvManager _liveTvManager;
private readonly IUserManager _userManager;
- private readonly IConfigurationManager _config;
+ private readonly IServerConfigurationManager _config;
private readonly IHttpClient _httpClient;
private readonly ILibraryManager _libraryManager;
private readonly IDtoService _dtoService;
+ private readonly IFileSystem _fileSystem;
- public LiveTvService(ILiveTvManager liveTvManager, IUserManager userManager, IConfigurationManager config, IHttpClient httpClient, ILibraryManager libraryManager, IDtoService dtoService)
+ public LiveTvService(ILiveTvManager liveTvManager, IUserManager userManager, IServerConfigurationManager config, IHttpClient httpClient, ILibraryManager libraryManager, IDtoService dtoService, IFileSystem fileSystem)
{
_liveTvManager = liveTvManager;
_userManager = userManager;
@@ -576,6 +694,49 @@ namespace MediaBrowser.Api.LiveTv
_httpClient = httpClient;
_libraryManager = libraryManager;
_dtoService = dtoService;
+ _fileSystem = fileSystem;
+ }
+
+ public object Get(GetLiveStreamFile request)
+ {
+ var filePath = Path.Combine(_config.ApplicationPaths.TranscodingTempPath, request.Id + ".ts");
+
+ var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+
+ outputHeaders["Content-Type"] = MimeTypes.GetMimeType(filePath);
+
+ long startPosition = 0;
+
+ if (request.T > 0)
+ {
+ var now = DateTime.UtcNow;
+
+ var totalTicks = now.Ticks - request.S;
+
+ if (totalTicks > 0)
+ {
+ double requestedOffset = request.T;
+ requestedOffset = Math.Max(0, requestedOffset - TimeSpan.FromSeconds(10).Ticks);
+
+ var pct = requestedOffset / totalTicks;
+
+ Logger.Info("Live stream offset pct {0}", pct);
+
+ var bytes = new FileInfo(filePath).Length;
+ Logger.Info("Live stream total bytes {0}", bytes);
+ startPosition = Convert.ToInt64(pct * bytes);
+ }
+ }
+
+ Logger.Info("Live stream starting byte position {0}", startPosition);
+
+ var streamSource = new ProgressiveFileCopier(_fileSystem, filePath, outputHeaders, null, Logger, CancellationToken.None)
+ {
+ AllowEndOfFile = false,
+ StartPosition = startPosition
+ };
+
+ return ResultFactory.GetAsyncStreamWriter(streamSource);
}
public object Get(GetDefaultListingProvider request)
@@ -592,7 +753,7 @@ namespace MediaBrowser.Api.LiveTv
public async Task<object> Get(GetLiveTvRegistrationInfo request)
{
- var result = await _liveTvManager.GetRegistrationInfo(request.ChannelId, request.ProgramId, request.Feature).ConfigureAwait(false);
+ var result = await _liveTvManager.GetRegistrationInfo(request.Feature).ConfigureAwait(false);
return ToOptimizedResult(result);
}
@@ -732,6 +893,13 @@ namespace MediaBrowser.Api.LiveTv
IsLiked = request.IsLiked,
IsDisliked = request.IsDisliked,
EnableFavoriteSorting = request.EnableFavoriteSorting,
+ IsMovie = request.IsMovie,
+ IsSeries = request.IsSeries,
+ IsNews = request.IsNews,
+ IsKids = request.IsKids,
+ IsSports = request.IsSports,
+ SortBy = request.GetOrderBy(),
+ SortOrder = request.SortOrder ?? SortOrder.Ascending,
AddCurrentProgram = request.AddCurrentProgram
}, CancellationToken.None).ConfigureAwait(false);
@@ -814,9 +982,12 @@ namespace MediaBrowser.Api.LiveTv
query.Limit = request.Limit;
query.SortBy = (request.SortBy ?? String.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
query.SortOrder = request.SortOrder;
+ query.IsNews = request.IsNews;
query.IsMovie = request.IsMovie;
+ query.IsSeries = request.IsSeries;
query.IsKids = request.IsKids;
query.IsSports = request.IsSports;
+ query.SeriesTimerId = request.SeriesTimerId;
query.Genres = (request.Genres ?? String.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var result = await _liveTvManager.GetPrograms(query, GetDtoOptions(request), CancellationToken.None).ConfigureAwait(false);
@@ -832,8 +1003,10 @@ namespace MediaBrowser.Api.LiveTv
IsAiring = request.IsAiring,
Limit = request.Limit,
HasAired = request.HasAired,
+ IsSeries = request.IsSeries,
IsMovie = request.IsMovie,
IsKids = request.IsKids,
+ IsNews = request.IsNews,
IsSports = request.IsSports,
EnableTotalRecordCount = request.EnableTotalRecordCount
};
@@ -863,6 +1036,33 @@ namespace MediaBrowser.Api.LiveTv
Status = request.Status,
SeriesTimerId = request.SeriesTimerId,
IsInProgress = request.IsInProgress,
+ EnableTotalRecordCount = request.EnableTotalRecordCount,
+ IsMovie = request.IsMovie,
+ IsNews = request.IsNews,
+ IsSeries = request.IsSeries,
+ IsKids = request.IsKids,
+ IsSports = request.IsSports
+
+ }, options, CancellationToken.None).ConfigureAwait(false);
+
+ return ToOptimizedResult(result);
+ }
+
+ public async Task<object> Get(GetRecordingSeries request)
+ {
+ var options = GetDtoOptions(request);
+ options.DeviceId = AuthorizationContext.GetAuthorizationInfo(Request).DeviceId;
+
+ var result = await _liveTvManager.GetRecordingSeries(new RecordingQuery
+ {
+ ChannelId = request.ChannelId,
+ UserId = request.UserId,
+ GroupId = request.GroupId,
+ StartIndex = request.StartIndex,
+ Limit = request.Limit,
+ Status = request.Status,
+ SeriesTimerId = request.SeriesTimerId,
+ IsInProgress = request.IsInProgress,
EnableTotalRecordCount = request.EnableTotalRecordCount
}, options, CancellationToken.None).ConfigureAwait(false);
diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs
index e626d49f4..fb4bd9244 100644
--- a/MediaBrowser.Api/Playback/BaseStreamingService.cs
+++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs
@@ -337,9 +337,9 @@ namespace MediaBrowser.Api.Playback
/// Gets the video bitrate to specify on the command line
/// </summary>
/// <param name="state">The state.</param>
- /// <param name="videoCodec">The video codec.</param>
+ /// <param name="videoEncoder">The video codec.</param>
/// <returns>System.String.</returns>
- protected string GetVideoQualityParam(StreamState state, string videoCodec)
+ protected string GetVideoQualityParam(StreamState state, string videoEncoder)
{
var param = string.Empty;
@@ -348,7 +348,7 @@ namespace MediaBrowser.Api.Playback
var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
- if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrWhiteSpace(encodingOptions.H264Preset))
{
@@ -367,9 +367,11 @@ namespace MediaBrowser.Api.Playback
{
param += " -crf 23";
}
+
+ param += " -tune zerolatency";
}
- else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
{
param += "-preset fast";
@@ -377,20 +379,20 @@ namespace MediaBrowser.Api.Playback
}
// h264 (h264_qsv)
- else if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
{
param += "-preset 7 -look_ahead 0";
}
// h264 (h264_nvenc)
- else if (string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
{
param += "-preset default";
}
// webm
- else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase))
{
// Values 0-3, 0 being highest quality but slower
var profileScore = 0;
@@ -417,23 +419,23 @@ namespace MediaBrowser.Api.Playback
qmax);
}
- else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
{
param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
}
// asf/wmv
- else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase))
{
param += "-qmin 2";
}
- else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
param += "-mbd 2";
}
- param += GetVideoBitrateParam(state, videoCodec);
+ param += GetVideoBitrateParam(state, videoEncoder);
var framerate = GetFramerateParam(state);
if (framerate.HasValue)
@@ -448,8 +450,8 @@ namespace MediaBrowser.Api.Playback
if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
{
- if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
{
// not supported by h264_omx
param += " -profile:v " + state.VideoRequest.Profile;
@@ -458,11 +460,13 @@ namespace MediaBrowser.Api.Playback
if (!string.IsNullOrEmpty(state.VideoRequest.Level))
{
+ var level = NormalizeTranscodingLevel(state.OutputVideoCodec, state.VideoRequest.Level);
+
// h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
- if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
{
- switch (state.VideoRequest.Level)
+ switch (level)
{
case "30":
param += " -level 3";
@@ -492,20 +496,20 @@ namespace MediaBrowser.Api.Playback
param += " -level 5.2";
break;
default:
- param += " -level " + state.VideoRequest.Level;
+ param += " -level " + level;
break;
}
}
- else if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase))
+ else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
{
- param += " -level " + state.VideoRequest.Level;
+ param += " -level " + level;
}
}
- if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
{
param = "-pix_fmt yuv420p " + param;
}
@@ -513,6 +517,25 @@ namespace MediaBrowser.Api.Playback
return param;
}
+ private string NormalizeTranscodingLevel(string videoCodec, string level)
+ {
+ double requestLevel;
+
+ // Clients may direct play higher than level 41, but there's no reason to transcode higher
+ if (double.TryParse(level, NumberStyles.Any, UsCulture, out requestLevel))
+ {
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ if (requestLevel > 41)
+ {
+ return "41";
+ }
+ }
+ }
+
+ return level;
+ }
+
protected string GetAudioFilterParam(StreamState state, bool isHls)
{
var volParam = string.Empty;
@@ -746,7 +769,20 @@ namespace MediaBrowser.Api.Playback
if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
{
outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
- outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
+
+ if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase));
+ }
+ else
+ {
+ outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
+ {
+ outputSizeParam = ",format=nv12|vaapi,hwupload";
}
var videoSizeParam = string.Empty;
@@ -1001,7 +1037,15 @@ namespace MediaBrowser.Api.Playback
var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
if (GetVideoEncoder(state).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
{
- arg = "-hwaccel vaapi -hwaccel_output_format vaapi -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.VideoRequest.SubtitleMethod == SubtitleDeliveryMethod.Encode;
+ var hwOutputFormat = "vaapi";
+
+ if (hasGraphicalSubs)
+ {
+ hwOutputFormat = "yuv420p";
+ }
+
+ arg = "-hwaccel vaapi -hwaccel_output_format " + hwOutputFormat + " -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
}
}
@@ -1176,17 +1220,21 @@ namespace MediaBrowser.Api.Playback
await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
}
- if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive)
+ if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
{
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
- if (state.ReadInputAtNativeFramerate)
+ if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
{
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
}
}
- StartThrottler(state, transcodingJob);
+ if (!transcodingJob.HasExited)
+ {
+ StartThrottler(state, transcodingJob);
+ }
+
ReportUsage(state);
return transcodingJob;
@@ -1194,14 +1242,14 @@ namespace MediaBrowser.Api.Playback
private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
{
- if (EnableThrottling(state) && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
+ if (EnableThrottling(state))
{
transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager);
state.TranscodingThrottler.Start();
}
}
- protected virtual bool EnableThrottling(StreamState state)
+ private bool EnableThrottling(StreamState state)
{
// do not use throttling with hardware encoders
return state.InputProtocol == MediaProtocol.File &&
@@ -1415,7 +1463,8 @@ namespace MediaBrowser.Api.Playback
// Make sure we don't request a bitrate higher than the source
var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
- return request.AudioBitRate.Value;
+ // Don't encode any higher than this
+ return Math.Min(384000, request.AudioBitRate.Value);
//return Math.Min(currentBitrate, request.AudioBitRate.Value);
}
@@ -1786,6 +1835,15 @@ namespace MediaBrowser.Api.Playback
// state.SegmentLength = 6;
//}
+ if (state.VideoRequest != null)
+ {
+ if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
+ {
+ state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
+ state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
+ }
+ }
+
if (!string.IsNullOrWhiteSpace(request.AudioCodec))
{
state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
@@ -1800,18 +1858,30 @@ namespace MediaBrowser.Api.Playback
var archivable = item as IArchivable;
state.IsInputArchive = archivable != null && archivable.IsArchive;
- MediaSourceInfo mediaSource;
+ MediaSourceInfo mediaSource = null;
if (string.IsNullOrWhiteSpace(request.LiveStreamId))
{
- var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
+ TranscodingJob currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
+ ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
+ : null;
- mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
- ? mediaSources.First()
- : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
+ if (currentJob != null)
+ {
+ mediaSource = currentJob.MediaSource;
+ }
- if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
+ if (mediaSource == null)
{
- mediaSource = mediaSources.First();
+ var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
+
+ mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
+ ? mediaSources.First()
+ : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
+
+ if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
+ {
+ mediaSource = mediaSources.First();
+ }
}
}
else
@@ -2028,7 +2098,7 @@ namespace MediaBrowser.Api.Playback
}
// Source and target codecs must match
- if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
+ if (string.IsNullOrEmpty(videoStream.Codec) || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
{
return false;
}
@@ -2532,6 +2602,7 @@ namespace MediaBrowser.Api.Playback
inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
inputModifier = inputModifier.Trim();
+ //inputModifier += " -fflags +genpts+ignidx+igndts";
if (state.VideoRequest != null && genPts)
{
inputModifier += " -fflags +genpts";
diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
index a0ac96b9d..319e4bbb6 100644
--- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
+++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs
@@ -87,7 +87,8 @@ namespace MediaBrowser.Api.Playback.Hls
if (!FileSystem.FileExists(playlist))
{
- await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
+ var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlist);
+ await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
try
{
if (!FileSystem.FileExists(playlist))
@@ -104,13 +105,13 @@ namespace MediaBrowser.Api.Playback.Hls
throw;
}
- var waitForSegments = state.SegmentLength >= 10 ? 2 : 3;
+ var waitForSegments = state.SegmentLength >= 10 ? 2 : (state.SegmentLength > 3 || !isLive ? 3 : 3);
await WaitForMinimumSegmentCount(playlist, waitForSegments, cancellationTokenSource.Token).ConfigureAwait(false);
}
}
finally
{
- ApiEntryPoint.Instance.TranscodingStartLock.Release();
+ transcodingLock.Release();
}
}
@@ -128,10 +129,9 @@ namespace MediaBrowser.Api.Playback.Hls
var audioBitrate = state.OutputAudioBitrate ?? 0;
var videoBitrate = state.OutputVideoBitrate ?? 0;
- var appendBaselineStream = false;
var baselineStreamBitrate = 64000;
- var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate);
+ var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, baselineStreamBitrate);
job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType);
@@ -151,9 +151,10 @@ namespace MediaBrowser.Api.Playback.Hls
{
var text = reader.ReadToEnd();
+ text = text.Replace("#EXTM3U", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT");
+
var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(UsCulture);
- // ffmpeg pads the reported length by a full second
text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(UsCulture), newDuration, StringComparison.OrdinalIgnoreCase);
return text;
@@ -161,7 +162,7 @@ namespace MediaBrowser.Api.Playback.Hls
}
}
- private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
+ private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, int baselineStreamBitrate)
{
var builder = new StringBuilder();
@@ -175,14 +176,6 @@ namespace MediaBrowser.Api.Playback.Hls
var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
builder.AppendLine(playlistUrl);
- // Low bitrate stream
- if (includeBaselineStream)
- {
- builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
- playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
- builder.AppendLine(playlistUrl);
- }
-
return builder.ToString();
}
@@ -190,32 +183,41 @@ namespace MediaBrowser.Api.Playback.Hls
{
Logger.Debug("Waiting for {0} segments in {1}", segmentCount, playlist);
- while (true)
+ while (!cancellationToken.IsCancellationRequested)
{
- // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
- using (var fileStream = GetPlaylistFileStream(playlist))
+ try
{
- using (var reader = new StreamReader(fileStream))
+ // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
+ using (var fileStream = GetPlaylistFileStream(playlist))
{
- var count = 0;
-
- while (!reader.EndOfStream)
+ using (var reader = new StreamReader(fileStream))
{
- var line = await reader.ReadLineAsync().ConfigureAwait(false);
+ var count = 0;
- if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
+ while (!reader.EndOfStream)
{
- count++;
- if (count >= segmentCount)
+ var line = await reader.ReadLineAsync().ConfigureAwait(false);
+
+ if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
{
- Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
- return;
+ count++;
+ if (count >= segmentCount)
+ {
+ Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
+ return;
+ }
}
}
+ await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
- await Task.Delay(100, cancellationToken).ConfigureAwait(false);
}
}
+ catch (IOException)
+ {
+ // May get an error if the file is locked
+ }
+
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
}
}
diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
index 7de309699..51455c141 100644
--- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
+++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs
@@ -171,14 +171,15 @@ namespace MediaBrowser.Api.Playback.Hls
return await GetSegmentResult(state, playlistPath, segmentPath, requestedIndex, job, cancellationToken).ConfigureAwait(false);
}
- await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
+ var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(playlistPath);
+ await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
var released = false;
try
{
if (FileSystem.FileExists(segmentPath))
{
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- ApiEntryPoint.Instance.TranscodingStartLock.Release();
+ transcodingLock.Release();
released = true;
return await GetSegmentResult(state, playlistPath, segmentPath, requestedIndex, job, cancellationToken).ConfigureAwait(false);
}
@@ -242,7 +243,7 @@ namespace MediaBrowser.Api.Playback.Hls
{
if (!released)
{
- ApiEntryPoint.Instance.TranscodingStartLock.Release();
+ transcodingLock.Release();
}
}
@@ -906,6 +907,7 @@ namespace MediaBrowser.Api.Playback.Hls
).Trim();
}
+ // TODO: check libavformat version for 57 50.100 and use -hls_flags split_by_time
return string.Format("{0}{11} {1} -map_metadata -1 -threads {2} {3} {4}{5} {6} -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -hls_time {7} -start_number {8} -hls_list_size {9} -y \"{10}\"",
inputModifier,
GetInputArgument(state),
@@ -922,11 +924,6 @@ namespace MediaBrowser.Api.Playback.Hls
).Trim();
}
- protected override bool EnableThrottling(StreamState state)
- {
- return true;
- }
-
/// <summary>
/// Gets the segment file extension.
/// </summary>
diff --git a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs
index 27deaf25e..976fed3f0 100644
--- a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs
+++ b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs
@@ -68,8 +68,6 @@ namespace MediaBrowser.Api.Playback.Hls
[Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
public class GetHlsVideoSegmentLegacy : VideoStreamRequest
{
- // TODO: Deprecate with new iOS app
-
public string PlaylistId { get; set; }
/// <summary>
@@ -113,7 +111,7 @@ namespace MediaBrowser.Api.Playback.Hls
var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
file = Path.Combine(_config.ApplicationPaths.TranscodingTempPath, file);
- var normalizedPlaylistId = request.PlaylistId.Replace("-low", string.Empty);
+ var normalizedPlaylistId = request.PlaylistId;
var playlistPath = Directory.EnumerateFiles(_config.ApplicationPaths.TranscodingTempPath, "*")
.FirstOrDefault(i => string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1);
diff --git a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs
index 8a14948d2..c7258d72f 100644
--- a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs
+++ b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs
@@ -113,6 +113,8 @@ namespace MediaBrowser.Api.Playback.Hls
args += GetGraphicalSubtitleParam(state, codec);
}
+ args += " -flags -global_header";
+
return args;
}
diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs
index 656b2ee08..761538c83 100644
--- a/MediaBrowser.Api/Playback/MediaInfoService.cs
+++ b/MediaBrowser.Api/Playback/MediaInfoService.cs
@@ -140,7 +140,7 @@ namespace MediaBrowser.Api.Playback
public void Post(CloseMediaSource request)
{
- var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId, CancellationToken.None);
+ var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId);
Task.WaitAll(task);
}
diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
index b8cb6b14f..4adf6fbca 100644
--- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
+++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs
@@ -17,6 +17,7 @@ using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
+using ServiceStack;
namespace MediaBrowser.Api.Playback.Progressive
{
@@ -26,12 +27,10 @@ namespace MediaBrowser.Api.Playback.Progressive
public abstract class BaseProgressiveStreamingService : BaseStreamingService
{
protected readonly IImageProcessor ImageProcessor;
- protected readonly IHttpClient HttpClient;
protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
{
ImageProcessor = imageProcessor;
- HttpClient = httpClient;
}
/// <summary>
@@ -129,6 +128,23 @@ namespace MediaBrowser.Api.Playback.Progressive
using (state)
{
+ if (state.MediaPath.IndexOf("/livestreamfiles/", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ var parts = state.MediaPath.Split('/');
+ var filename = parts[parts.Length - 2] + Path.GetExtension(parts[parts.Length - 1]);
+ var filePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, filename);
+
+ var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+
+ outputHeaders["Content-Type"] = MimeTypes.GetMimeType(filePath);
+
+ var streamSource = new ProgressiveFileCopier(FileSystem, filePath, outputHeaders, null, Logger, CancellationToken.None)
+ {
+ AllowEndOfFile = false
+ };
+ return ResultFactory.GetAsyncStreamWriter(streamSource);
+ }
+
return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource)
.ConfigureAwait(false);
}
@@ -154,6 +170,19 @@ namespace MediaBrowser.Api.Playback.Progressive
using (state)
{
+ if (state.MediaSource.IsInfiniteStream)
+ {
+ var outputHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+
+ outputHeaders["Content-Type"] = contentType;
+
+ var streamSource = new ProgressiveFileCopier(FileSystem, state.MediaPath, outputHeaders, null, Logger, CancellationToken.None)
+ {
+ AllowEndOfFile = false
+ };
+ return ResultFactory.GetAsyncStreamWriter(streamSource);
+ }
+
TimeSpan? cacheDuration = null;
if (!string.IsNullOrEmpty(request.Tag))
@@ -345,7 +374,8 @@ namespace MediaBrowser.Api.Playback.Progressive
return streamResult;
}
- await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
+ var transcodingLock = ApiEntryPoint.Instance.GetTranscodingLock(outputPath);
+ await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
try
{
TranscodingJob job;
@@ -376,7 +406,7 @@ namespace MediaBrowser.Api.Playback.Progressive
}
finally
{
- ApiEntryPoint.Instance.TranscodingStartLock.Release();
+ transcodingLock.Release();
}
}
diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
index 0a9a44641..f601f4aa3 100644
--- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
+++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs
@@ -23,6 +23,8 @@ namespace MediaBrowser.Api.Playback.Progressive
private const int BufferSize = 81920;
private long _bytesWritten = 0;
+ public long StartPosition { get; set; }
+ public bool AllowEndOfFile = true;
public ProgressiveFileCopier(IFileSystem fileSystem, string path, Dictionary<string, string> outputHeaders, TranscodingJob job, ILogger logger, CancellationToken cancellationToken)
{
@@ -50,7 +52,12 @@ namespace MediaBrowser.Api.Playback.Progressive
using (var fs = _fileSystem.GetFileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
{
- while (eofCount < 15)
+ if (StartPosition > 0)
+ {
+ fs.Position = StartPosition;
+ }
+
+ while (eofCount < 15 || !AllowEndOfFile)
{
var bytesRead = await CopyToAsyncInternal(fs, outputStream, BufferSize, _cancellationToken).ConfigureAwait(false);
diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs
index d7d94c69b..019f378c5 100644
--- a/MediaBrowser.Api/Playback/StreamState.cs
+++ b/MediaBrowser.Api/Playback/StreamState.cs
@@ -88,9 +88,17 @@ namespace MediaBrowser.Api.Playback
return 10;
}
+ if (!RunTimeTicks.HasValue)
+ {
+ return 3;
+ }
return 6;
}
+ if (!RunTimeTicks.HasValue)
+ {
+ return 3;
+ }
return 3;
}
}
@@ -112,6 +120,7 @@ namespace MediaBrowser.Api.Playback
public string OutputVideoSync = "-1";
public List<string> SupportedAudioCodecs { get; set; }
+ public List<string> SupportedVideoCodecs { get; set; }
public string UserAgent { get; set; }
public StreamState(IMediaSourceManager mediaSourceManager, ILogger logger)
@@ -119,6 +128,7 @@ namespace MediaBrowser.Api.Playback
_mediaSourceManager = mediaSourceManager;
_logger = logger;
SupportedAudioCodecs = new List<string>();
+ SupportedVideoCodecs = new List<string>();
PlayableStreamFileNames = new List<string>();
RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
@@ -215,7 +225,7 @@ namespace MediaBrowser.Api.Playback
{
try
{
- await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
+ await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
}
catch (Exception ex)
{
diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs
index ef898eb53..176b497d7 100644
--- a/MediaBrowser.Api/StartupWizardService.cs
+++ b/MediaBrowser.Api/StartupWizardService.cs
@@ -148,12 +148,6 @@ namespace MediaBrowser.Api
{
var user = _userManager.Users.First();
- // TODO: This should be handled internally by xbmc metadata
- const string metadataKey = "xbmcmetadata";
- var metadata = _config.GetConfiguration<XbmcMetadataOptions>(metadataKey);
- metadata.UserId = user.Id.ToString("N");
- _config.SaveConfiguration(metadataKey, metadata);
-
user.Name = request.Name;
await _userManager.UpdateUser(user).ConfigureAwait(false);
diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs
index fe13e8b21..b07a31a87 100644
--- a/MediaBrowser.Api/Subtitles/SubtitleService.cs
+++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs
@@ -148,7 +148,7 @@ namespace MediaBrowser.Api.Subtitles
{
var item = (Video)_libraryManager.GetItemById(new Guid(request.Id));
- var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, false).ConfigureAwait(false);
+ var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
var builder = new StringBuilder();
diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs
index 5381f9004..182a92fc8 100644
--- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs
+++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs
@@ -205,6 +205,7 @@ namespace MediaBrowser.Api.UserLibrary
private void SetItemCounts(BaseItemDto dto, ItemCounts counts)
{
dto.ChildCount = counts.ItemCount;
+ dto.ProgramCount = counts.ProgramCount;
dto.SeriesCount = counts.SeriesCount;
dto.EpisodeCount = counts.EpisodeCount;
dto.MovieCount = counts.MovieCount;
diff --git a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs
index 371757f6c..ba5964be5 100644
--- a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs
+++ b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs
@@ -293,12 +293,9 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager
/// </exception>
public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
{
- HttpResponseInfo response;
-
if (options.CacheMode == CacheMode.None)
{
- response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
- return response;
+ return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
}
var url = options.Url;
@@ -306,7 +303,7 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager
var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
- response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
+ var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
if (response != null)
{
return response;
diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj
index ced2dd5a3..7e8823bc0 100644
--- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj
+++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj
@@ -55,7 +55,7 @@
<HintPath>..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
- <HintPath>..\packages\NLog.4.3.6\lib\net45\NLog.dll</HintPath>
+ <HintPath>..\packages\NLog.4.3.8\lib\net45\NLog.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Patterns.Logging">
@@ -65,8 +65,8 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\ThirdParty\SharpCompress\SharpCompress.dll</HintPath>
</Reference>
- <Reference Include="SimpleInjector, Version=3.2.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
- <HintPath>..\packages\SimpleInjector.3.2.0\lib\net45\SimpleInjector.dll</HintPath>
+ <Reference Include="SimpleInjector, Version=3.2.2.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
+ <HintPath>..\packages\SimpleInjector.3.2.2\lib\net45\SimpleInjector.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
index 798e18ef5..ced85780f 100644
--- a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
+++ b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs
@@ -334,7 +334,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
trigger.Stop();
- TaskManager.QueueScheduledTask(ScheduledTask);
+ TaskManager.QueueScheduledTask(ScheduledTask, e.Argument);
await Task.Delay(1000).ConfigureAwait(false);
@@ -390,13 +390,13 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks
try
{
- var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress);
-
if (options != null && options.MaxRuntimeMs.HasValue)
{
CurrentCancellationTokenSource.CancelAfter(options.MaxRuntimeMs.Value);
}
+ var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress);
+
await localTask.ConfigureAwait(false);
status = TaskCompletionStatus.Completed;
diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs
index 6281ab3ed..84c08439e 100644
--- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs
+++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs
@@ -14,16 +14,14 @@ namespace MediaBrowser.Common.Implementations.Updates
{
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
- private TimeSpan _cacheLength;
- public GithubUpdater(IHttpClient httpClient, IJsonSerializer jsonSerializer, TimeSpan cacheLength)
+ public GithubUpdater(IHttpClient httpClient, IJsonSerializer jsonSerializer)
{
_httpClient = httpClient;
_jsonSerializer = jsonSerializer;
- _cacheLength = cacheLength;
}
- public async Task<CheckForUpdateResult> CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken)
+ public async Task<CheckForUpdateResult> CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, TimeSpan cacheLength, CancellationToken cancellationToken)
{
var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository);
@@ -35,10 +33,10 @@ namespace MediaBrowser.Common.Implementations.Updates
UserAgent = "Emby/3.0"
};
- if (_cacheLength.Ticks > 0)
+ if (cacheLength.Ticks > 0)
{
options.CacheMode = CacheMode.Unconditional;
- options.CacheLength = _cacheLength;
+ options.CacheLength = cacheLength;
}
using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
@@ -110,12 +108,6 @@ namespace MediaBrowser.Common.Implementations.Updates
UserAgent = "Emby/3.0"
};
- if (_cacheLength.Ticks > 0)
- {
- options.CacheMode = CacheMode.Unconditional;
- options.CacheLength = _cacheLength;
- }
-
using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
{
var obj = _jsonSerializer.DeserializeFromStream<RootObject[]>(stream);
diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config
index 594b4c7c5..f444a3a05 100644
--- a/MediaBrowser.Common.Implementations/packages.config
+++ b/MediaBrowser.Common.Implementations/packages.config
@@ -2,7 +2,7 @@
<packages>
<package id="CommonIO" version="1.0.0.9" targetFramework="net45" />
<package id="morelinq" version="1.4.0" targetFramework="net45" />
- <package id="NLog" version="4.3.6" targetFramework="net45" />
+ <package id="NLog" version="4.3.8" targetFramework="net45" />
<package id="Patterns.Logging" version="1.0.0.2" targetFramework="net45" />
- <package id="SimpleInjector" version="3.2.0" targetFramework="net45" />
+ <package id="SimpleInjector" version="3.2.2" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs
index e3d2d0440..3c46247a7 100644
--- a/MediaBrowser.Controller/Channels/IChannelManager.cs
+++ b/MediaBrowser.Controller/Channels/IChannelManager.cs
@@ -31,6 +31,8 @@ namespace MediaBrowser.Controller.Channels
/// <returns>ChannelFeatures.</returns>
ChannelFeatures GetChannelFeatures(string id);
+ bool SupportsSync(string channelId);
+
/// <summary>
/// Gets all channel features.
/// </summary>
diff --git a/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs b/MediaBrowser.Controller/Collections/ManualCollectionsFolder.cs
index 3e33066ae..d2d28e504 100644
--- a/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs
+++ b/MediaBrowser.Controller/Collections/ManualCollectionsFolder.cs
@@ -1,6 +1,6 @@
using MediaBrowser.Controller.Entities;
-namespace MediaBrowser.Server.Implementations.Collections
+namespace MediaBrowser.Controller.Collections
{
public class ManualCollectionsFolder : BasePluginFolder, IHiddenFromDisplay
{
diff --git a/MediaBrowser.Controller/Dlna/IDeviceDiscovery.cs b/MediaBrowser.Controller/Dlna/IDeviceDiscovery.cs
index e8083b363..d2c5b9e4e 100644
--- a/MediaBrowser.Controller/Dlna/IDeviceDiscovery.cs
+++ b/MediaBrowser.Controller/Dlna/IDeviceDiscovery.cs
@@ -1,10 +1,20 @@
using System;
+using System.Collections.Generic;
+using System.Net;
+using MediaBrowser.Model.Events;
namespace MediaBrowser.Controller.Dlna
{
public interface IDeviceDiscovery
{
- event EventHandler<SsdpMessageEventArgs> DeviceDiscovered;
- event EventHandler<SsdpMessageEventArgs> DeviceLeft;
+ event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscovered;
+ event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceLeft;
+ }
+
+ public class UpnpDeviceInfo
+ {
+ public Uri Location { get; set; }
+ public Dictionary<string, string> Headers { get; set; }
+ public IPEndPoint LocalEndPoint { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Dlna/ISsdpHandler.cs b/MediaBrowser.Controller/Dlna/ISsdpHandler.cs
index e4126ddcf..ec3a00aad 100644
--- a/MediaBrowser.Controller/Dlna/ISsdpHandler.cs
+++ b/MediaBrowser.Controller/Dlna/ISsdpHandler.cs
@@ -4,6 +4,5 @@ namespace MediaBrowser.Controller.Dlna
{
public interface ISsdpHandler
{
- event EventHandler<SsdpMessageEventArgs> MessageReceived;
}
}
diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs
index 1af55a389..599e72314 100644
--- a/MediaBrowser.Controller/Entities/Audio/Audio.cs
+++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs
@@ -262,7 +262,7 @@ namespace MediaBrowser.Controller.Entities.Audio
Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
MediaStreams = MediaSourceManager.GetMediaStreams(i.Id).ToList(),
Name = i.Name,
- Path = enablePathSubstituion ? GetMappedPath(i.Path, locationType) : i.Path,
+ Path = enablePathSubstituion ? GetMappedPath(i, i.Path, locationType) : i.Path,
RunTimeTicks = i.RunTimeTicks,
Container = i.Container,
Size = i.Size
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index 55aaf04ff..492058f98 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -44,6 +44,7 @@ namespace MediaBrowser.Controller.Entities
ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
LockedFields = new List<MetadataFields>();
ImageInfos = new List<ItemImageInfo>();
+ InheritedTags = new List<string>();
}
public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
@@ -254,6 +255,19 @@ namespace MediaBrowser.Controller.Entities
}
}
+ [IgnoreDataMember]
+ public string ExternalSeriesId { get; set; }
+
+ [IgnoreDataMember]
+ public string ExternalSeriesIdLegacy
+ {
+ get { return this.GetProviderId("ProviderExternalSeriesId"); }
+ set
+ {
+ this.SetProviderId("ProviderExternalSeriesId", value);
+ }
+ }
+
/// <summary>
/// Gets or sets the etag.
/// </summary>
@@ -784,6 +798,9 @@ namespace MediaBrowser.Controller.Entities
[IgnoreDataMember]
public int InheritedParentalRatingValue { get; set; }
+ [IgnoreDataMember]
+ public List<string> InheritedTags { get; set; }
+
/// <summary>
/// Gets or sets the critic rating.
/// </summary>
@@ -2107,14 +2124,11 @@ namespace MediaBrowser.Controller.Entities
return hasChanges;
}
- protected static string GetMappedPath(string path, LocationType locationType)
+ protected static string GetMappedPath(BaseItem item, string path, LocationType locationType)
{
if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
{
- foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
- {
- path = LibraryManager.SubstitutePath(path, map.From, map.To);
- }
+ return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
}
return path;
diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs
index 30ea26eb6..77d7ca7f2 100644
--- a/MediaBrowser.Controller/Entities/CollectionFolder.cs
+++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs
@@ -48,24 +48,14 @@ namespace MediaBrowser.Controller.Entities
private static readonly Dictionary<string, LibraryOptions> LibraryOptions = new Dictionary<string, LibraryOptions>();
public LibraryOptions GetLibraryOptions()
{
- lock (LibraryOptions)
- {
- LibraryOptions options;
- if (!LibraryOptions.TryGetValue(Path, out options))
- {
- options = LoadLibraryOptions();
- LibraryOptions[Path] = options;
- }
-
- return options;
- }
+ return GetLibraryOptions(Path);
}
- private LibraryOptions LoadLibraryOptions()
+ private static LibraryOptions LoadLibraryOptions(string path)
{
try
{
- var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(Path)) as LibraryOptions;
+ var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
if (result == null)
{
@@ -100,6 +90,21 @@ namespace MediaBrowser.Controller.Entities
SaveLibraryOptions(Path, options);
}
+ public static LibraryOptions GetLibraryOptions(string path)
+ {
+ lock (LibraryOptions)
+ {
+ LibraryOptions options;
+ if (!LibraryOptions.TryGetValue(path, out options))
+ {
+ options = LoadLibraryOptions(path);
+ LibraryOptions[path] = options;
+ }
+
+ return options;
+ }
+ }
+
public static void SaveLibraryOptions(string path, LibraryOptions options)
{
lock (LibraryOptions)
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index bf47ada0d..d1e089850 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -1057,11 +1057,21 @@ namespace MediaBrowser.Controller.Entities
/// <returns>IList{BaseItem}.</returns>
public IList<BaseItem> GetRecursiveChildren()
{
- return GetRecursiveChildren(i => true);
+ return GetRecursiveChildren(true);
+ }
+
+ public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
+ {
+ return GetRecursiveChildren(i => true, includeLinkedChildren);
}
public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
{
+ return GetRecursiveChildren(filter, true);
+ }
+
+ public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
+ {
var result = new Dictionary<Guid, BaseItem>();
AddChildrenToList(result, true, true, filter);
@@ -1139,29 +1149,19 @@ namespace MediaBrowser.Controller.Entities
return LinkedChildren
.Select(i =>
{
- var requiresPostFilter = true;
-
- if (!string.IsNullOrWhiteSpace(i.Path))
- {
- requiresPostFilter = false;
-
- if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
- {
- return null;
- }
- }
-
var child = GetLinkedChild(i);
- if (requiresPostFilter && child != null)
+ if (child != null)
{
- if (string.IsNullOrWhiteSpace(child.Path))
+ var childLocationType = child.LocationType;
+ if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
{
- Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
- return child;
+ if (!child.IsVisibleStandalone(user))
+ {
+ return null;
+ }
}
-
- if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
+ else if (childLocationType == LocationType.FileSystem && !locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
{
return null;
}
diff --git a/MediaBrowser.Controller/Entities/IHasMetadata.cs b/MediaBrowser.Controller/Entities/IHasMetadata.cs
index cf2f7db64..aee58b445 100644
--- a/MediaBrowser.Controller/Entities/IHasMetadata.cs
+++ b/MediaBrowser.Controller/Entities/IHasMetadata.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Controller.Entities
{
@@ -62,5 +63,7 @@ namespace MediaBrowser.Controller.Entities
int? GetInheritedParentalRatingValue();
int InheritedParentalRatingValue { get; set; }
+ List<string> GetInheritedTags();
+ List<string> InheritedTags { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
index deea63112..60af2c56a 100644
--- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs
@@ -101,6 +101,8 @@ namespace MediaBrowser.Controller.Entities
public bool? IsMovie { get; set; }
public bool? IsSports { get; set; }
public bool? IsKids { get; set; }
+ public bool? IsNews { get; set; }
+ public bool? IsSeries { get; set; }
public int? MinPlayers { get; set; }
public int? MaxPlayers { get; set; }
@@ -137,6 +139,7 @@ namespace MediaBrowser.Controller.Entities
public DayOfWeek[] AirDays { get; set; }
public SeriesStatus[] SeriesStatuses { get; set; }
public string AlbumArtistStartsWithOrGreater { get; set; }
+ public string ExternalSeriesId { get; set; }
public string[] AlbumNames { get; set; }
public string[] ArtistNames { get; set; }
@@ -149,6 +152,8 @@ namespace MediaBrowser.Controller.Entities
public Dictionary<string, string> ExcludeProviderIds { get; set; }
public bool EnableGroupByMetadataKey { get; set; }
+ public List<Tuple<string, SortOrder>> OrderBy { get; set; }
+
public InternalItemsQuery()
{
GroupByPresentationUniqueKey = true;
@@ -191,6 +196,7 @@ namespace MediaBrowser.Controller.Entities
TrailerTypes = new TrailerType[] { };
AirDays = new DayOfWeek[] { };
SeriesStatuses = new SeriesStatus[] { };
+ OrderBy = new List<Tuple<string, SortOrder>>();
}
public InternalItemsQuery(User user)
diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs
index 194ba0ee4..35375e7e6 100644
--- a/MediaBrowser.Controller/Entities/UserView.cs
+++ b/MediaBrowser.Controller/Entities/UserView.cs
@@ -113,8 +113,7 @@ namespace MediaBrowser.Controller.Entities
{
var standaloneTypes = new List<string>
{
- CollectionType.Playlists,
- CollectionType.BoxSets
+ CollectionType.Playlists
};
var collectionFolder = folder as ICollectionFolder;
diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs
index 8809f155c..1406a05ce 100644
--- a/MediaBrowser.Controller/Entities/Video.cs
+++ b/MediaBrowser.Controller/Entities/Video.cs
@@ -600,7 +600,7 @@ namespace MediaBrowser.Controller.Entities
Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
MediaStreams = mediaStreams,
Name = GetMediaSourceName(i, mediaStreams),
- Path = enablePathSubstitution ? GetMappedPath(i.Path, locationType) : i.Path,
+ Path = enablePathSubstitution ? GetMappedPath(i, i.Path, locationType) : i.Path,
RunTimeTicks = i.RunTimeTicks,
Video3DFormat = i.Video3DFormat,
VideoType = i.VideoType,
diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs
index 0862e3eaf..975c59659 100644
--- a/MediaBrowser.Controller/Library/ILibraryManager.cs
+++ b/MediaBrowser.Controller/Library/ILibraryManager.cs
@@ -506,6 +506,8 @@ namespace MediaBrowser.Controller.Library
/// <returns>QueryResult&lt;BaseItem&gt;.</returns>
QueryResult<BaseItem> QueryItems(InternalItemsQuery query);
+ string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem = null);
+
/// <summary>
/// Substitutes the path.
/// </summary>
@@ -554,9 +556,10 @@ namespace MediaBrowser.Controller.Library
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
bool IgnoreFile(FileSystemMetadata file, BaseItem parent);
- void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, LibraryOptions options, bool refreshLibrary);
+ void AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary);
void RemoveVirtualFolder(string name, bool refreshLibrary);
- void AddMediaPath(string virtualFolderName, string path);
+ void AddMediaPath(string virtualFolderName, MediaPathInfo path);
+ void UpdateMediaPath(string virtualFolderName, MediaPathInfo path);
void RemoveMediaPath(string virtualFolderName, string path);
QueryResult<Tuple<BaseItem, ItemCounts>> GetGenres(InternalItemsQuery query);
@@ -566,5 +569,8 @@ namespace MediaBrowser.Controller.Library
QueryResult<Tuple<BaseItem, ItemCounts>> GetArtists(InternalItemsQuery query);
QueryResult<Tuple<BaseItem, ItemCounts>> GetAlbumArtists(InternalItemsQuery query);
QueryResult<Tuple<BaseItem, ItemCounts>> GetAllArtists(InternalItemsQuery query);
+
+ void RegisterIgnoredPath(string path);
+ void UnRegisterIgnoredPath(string path);
}
} \ No newline at end of file
diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
index a77d88049..c06470c5e 100644
--- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs
+++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
@@ -60,11 +60,8 @@ namespace MediaBrowser.Controller.Library
/// <summary>
/// Gets the static media source.
/// </summary>
- /// <param name="item">The item.</param>
- /// <param name="mediaSourceId">The media source identifier.</param>
- /// <param name="enablePathSubstitution">if set to <c>true</c> [enable path substitution].</param>
/// <returns>MediaSourceInfo.</returns>
- Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, bool enablePathSubstitution);
+ Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, string liveStreamId, bool enablePathSubstitution, CancellationToken cancellationToken);
/// <summary>
/// Opens the media source.
@@ -95,8 +92,7 @@ namespace MediaBrowser.Controller.Library
/// Closes the media source.
/// </summary>
/// <param name="id">The live stream identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task CloseLiveStream(string id, CancellationToken cancellationToken);
+ Task CloseLiveStream(string id);
}
}
diff --git a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
index 5b033af4a..56366e5a8 100644
--- a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
+++ b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs
@@ -28,8 +28,7 @@ namespace MediaBrowser.Controller.Library
/// Closes the media source.
/// </summary>
/// <param name="liveStreamId">The live stream identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken);
+ Task CloseMediaSource(string liveStreamId);
}
}
diff --git a/MediaBrowser.Controller/Library/NameExtensions.cs b/MediaBrowser.Controller/Library/NameExtensions.cs
index 6973dce64..72f036b0a 100644
--- a/MediaBrowser.Controller/Library/NameExtensions.cs
+++ b/MediaBrowser.Controller/Library/NameExtensions.cs
@@ -54,7 +54,7 @@ namespace MediaBrowser.Controller.Library
}
}
- class TextComparer : IComparer<string>, IEqualityComparer<string>
+ public class DistinctNameComparer : IComparer<string>, IEqualityComparer<string>
{
public int Compare(string x, string y)
{
@@ -63,7 +63,7 @@ namespace MediaBrowser.Controller.Library
return 0;
}
- return string.Compare(x, y, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace);
+ return string.Compare(x.RemoveDiacritics(), y.RemoveDiacritics(), StringComparison.OrdinalIgnoreCase);
}
public bool Equals(string x, string y)
diff --git a/MediaBrowser.Controller/LiveTv/IHasRegistrationInfo.cs b/MediaBrowser.Controller/LiveTv/IHasRegistrationInfo.cs
deleted file mode 100644
index 3626c18e5..000000000
--- a/MediaBrowser.Controller/LiveTv/IHasRegistrationInfo.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using MediaBrowser.Model.Entities;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Controller.LiveTv
-{
- public interface IHasRegistrationInfo
- {
- /// <summary>
- /// Gets the registration information.
- /// </summary>
- /// <param name="feature">The feature.</param>
- /// <returns>Task&lt;MBRegistrationRecord&gt;.</returns>
- Task<MBRegistrationRecord> GetRegistrationInfo(string feature);
- }
-}
diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
index ed64127c3..d65d1ae30 100644
--- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
+++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
@@ -37,7 +37,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{SeriesTimerInfoDto}.</returns>
Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken);
-
+
/// <summary>
/// Deletes the recording.
/// </summary>
@@ -51,7 +51,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="recording">The recording.</param>
/// <returns>Task.</returns>
Task DeleteRecording(BaseItem recording);
-
+
/// <summary>
/// Cancels the timer.
/// </summary>
@@ -83,7 +83,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="user">The user.</param>
/// <returns>Task{RecordingInfoDto}.</returns>
Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null);
-
+
/// <summary>
/// Gets the timer.
/// </summary>
@@ -108,6 +108,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>QueryResult{RecordingInfoDto}.</returns>
Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken);
+ Task<QueryResult<BaseItemDto>> GetRecordingSeries(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken);
/// <summary>
/// Gets the timers.
@@ -124,14 +125,14 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{QueryResult{SeriesTimerInfoDto}}.</returns>
Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken);
-
+
/// <summary>
/// Gets the channel.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Channel.</returns>
LiveTvChannel GetInternalChannel(string id);
-
+
/// <summary>
/// Gets the recording.
/// </summary>
@@ -156,7 +157,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{StreamResponseInfo}.</returns>
Task<MediaSourceInfo> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken);
-
+
/// <summary>
/// Gets the program.
/// </summary>
@@ -219,9 +220,8 @@ namespace MediaBrowser.Controller.LiveTv
/// Closes the live stream.
/// </summary>
/// <param name="id">The identifier.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- Task CloseLiveStream(string id, CancellationToken cancellationToken);
+ Task CloseLiveStream(string id);
/// <summary>
/// Gets the guide information.
@@ -330,8 +330,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="fields">The fields.</param>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
- Task AddInfoToProgramDto(List<Tuple<BaseItem,BaseItemDto>> programs, List<ItemFields> fields, User user = null);
-
+ Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> programs, List<ItemFields> fields, User user = null);
+
/// <summary>
/// Saves the tuner host.
/// </summary>
@@ -364,11 +364,9 @@ namespace MediaBrowser.Controller.LiveTv
/// <summary>
/// Gets the registration information.
/// </summary>
- /// <param name="channelId">The channel identifier.</param>
- /// <param name="programId">The program identifier.</param>
/// <param name="feature">The feature.</param>
/// <returns>Task&lt;MBRegistrationRecord&gt;.</returns>
- Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature);
+ Task<MBRegistrationRecord> GetRegistrationInfo(string feature);
/// <summary>
/// Adds the channel information.
@@ -396,7 +394,7 @@ namespace MediaBrowser.Controller.LiveTv
Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken);
Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken);
- List<IListingsProvider> ListingProviders { get;}
+ List<IListingsProvider> ListingProviders { get; }
event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
diff --git a/MediaBrowser.Controller/LiveTv/ITunerHost.cs b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
index 1e7aa3de5..89d035649 100644
--- a/MediaBrowser.Controller/LiveTv/ITunerHost.cs
+++ b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
@@ -22,9 +22,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <summary>
/// Gets the channels.
/// </summary>
- /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task&lt;IEnumerable&lt;ChannelInfo&gt;&gt;.</returns>
- Task<IEnumerable<ChannelInfo>> GetChannels(CancellationToken cancellationToken);
+ Task<IEnumerable<ChannelInfo>> GetChannels(bool enableCache, CancellationToken cancellationToken);
/// <summary>
/// Gets the tuner infos.
/// </summary>
@@ -38,7 +37,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="streamId">The stream identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task&lt;MediaSourceInfo&gt;.</returns>
- Task<Tuple<MediaSourceInfo,SemaphoreSlim>> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken);
+ Task<LiveStream> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken);
/// <summary>
/// Gets the channel stream media sources.
/// </summary>
@@ -46,8 +45,6 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task&lt;List&lt;MediaSourceInfo&gt;&gt;.</returns>
Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken);
-
- string ApplyDuration(string streamPath, TimeSpan duration);
}
public interface IConfigurableTunerHost
{
diff --git a/MediaBrowser.Controller/LiveTv/LiveStream.cs b/MediaBrowser.Controller/LiveTv/LiveStream.cs
new file mode 100644
index 000000000..7d44fbd90
--- /dev/null
+++ b/MediaBrowser.Controller/LiveTv/LiveStream.cs
@@ -0,0 +1,43 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Model.Dto;
+
+namespace MediaBrowser.Controller.LiveTv
+{
+ public class LiveStream
+ {
+ public MediaSourceInfo OriginalMediaSource { get; set; }
+ public MediaSourceInfo OpenedMediaSource { get; set; }
+ public DateTime DateOpened { get; set; }
+ public int ConsumerCount { get; set; }
+ public ITunerHost TunerHost { get; set; }
+ public string OriginalStreamId { get; set; }
+ public bool EnableStreamSharing { get; set; }
+
+ public LiveStream(MediaSourceInfo mediaSource)
+ {
+ OriginalMediaSource = mediaSource;
+ OpenedMediaSource = mediaSource;
+ EnableStreamSharing = true;
+ }
+
+ public async Task Open(CancellationToken cancellationToken)
+ {
+ await OpenInternal(cancellationToken).ConfigureAwait(false);
+ DateOpened = DateTime.UtcNow;
+
+ OpenedMediaSource.DateLiveStreamOpened = DateOpened;
+ }
+
+ protected virtual Task OpenInternal(CancellationToken cancellationToken)
+ {
+ return Task.FromResult(true);
+ }
+
+ public virtual Task Close()
+ {
+ return Task.FromResult(true);
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
index 50aeed27d..69a1c24ea 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs
@@ -9,7 +9,7 @@ using System.Runtime.Serialization;
namespace MediaBrowser.Controller.LiveTv
{
- public class LiveTvChannel : BaseItem, IHasMediaSources
+ public class LiveTvChannel : BaseItem, IHasMediaSources, IHasProgramAttributes
{
public override List<string> GetUserDataKeys()
{
@@ -137,5 +137,56 @@ namespace MediaBrowser.Controller.LiveTv
{
return false;
}
+
+ [IgnoreDataMember]
+ public bool IsMovie { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is sports.
+ /// </summary>
+ /// <value><c>true</c> if this instance is sports; otherwise, <c>false</c>.</value>
+ [IgnoreDataMember]
+ public bool IsSports { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is series.
+ /// </summary>
+ /// <value><c>true</c> if this instance is series; otherwise, <c>false</c>.</value>
+ [IgnoreDataMember]
+ public bool IsSeries { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is live.
+ /// </summary>
+ /// <value><c>true</c> if this instance is live; otherwise, <c>false</c>.</value>
+ [IgnoreDataMember]
+ public bool IsLive { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is news.
+ /// </summary>
+ /// <value><c>true</c> if this instance is news; otherwise, <c>false</c>.</value>
+ [IgnoreDataMember]
+ public bool IsNews { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is kids.
+ /// </summary>
+ /// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
+ [IgnoreDataMember]
+ public bool IsKids { get; set; }
+
+ [IgnoreDataMember]
+ public bool IsPremiere { get; set; }
+
+ [IgnoreDataMember]
+ public bool IsRepeat { get; set; }
+
+ /// <summary>
+ /// Gets or sets the episode title.
+ /// </summary>
+ /// <value>The episode title.</value>
+ [IgnoreDataMember]
+ public string EpisodeTitle { get; set; }
}
}
diff --git a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
index a6a3e6108..d0377fbfd 100644
--- a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
@@ -1,6 +1,7 @@
using MediaBrowser.Model.LiveTv;
using System;
using System.Collections.Generic;
+using MediaBrowser.Model.Entities;
namespace MediaBrowser.Controller.LiveTv
{
@@ -66,6 +67,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
public bool? IsHD { get; set; }
+ public bool? Is3D { get; set; }
+
/// <summary>
/// Gets or sets the audio.
/// </summary>
@@ -84,6 +87,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <value><c>true</c> if this instance is repeat; otherwise, <c>false</c>.</value>
public bool IsRepeat { get; set; }
+ public bool IsSubjectToBlackout { get; set; }
+
/// <summary>
/// Gets or sets the episode title.
/// </summary>
@@ -102,6 +107,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <value>The image URL.</value>
public string ImageUrl { get; set; }
+ public string LogoImageUrl { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance has image.
/// </summary>
@@ -144,6 +151,8 @@ namespace MediaBrowser.Controller.LiveTv
/// <value><c>true</c> if this instance is kids; otherwise, <c>false</c>.</value>
public bool IsKids { get; set; }
+ public bool IsEducational { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether this instance is premiere.
/// </summary>
diff --git a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
index 2d79473f0..5c73ed833 100644
--- a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using MediaBrowser.Model.LiveTv;
namespace MediaBrowser.Controller.LiveTv
{
@@ -26,6 +27,8 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
public string Name { get; set; }
+ public string ServiceName { get; set; }
+
/// <summary>
/// Description of the recording.
/// </summary>
@@ -53,6 +56,11 @@ namespace MediaBrowser.Controller.LiveTv
/// <value><c>true</c> if [record any channel]; otherwise, <c>false</c>.</value>
public bool RecordAnyChannel { get; set; }
+ public int KeepUpTo { get; set; }
+ public KeepUntil KeepUntil { get; set; }
+
+ public bool SkipEpisodesInLibrary { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [record new only].
/// </summary>
@@ -104,6 +112,8 @@ namespace MediaBrowser.Controller.LiveTv
public SeriesTimerInfo()
{
Days = new List<DayOfWeek>();
+ SkipEpisodesInLibrary = true;
+ KeepUntil = KeepUntil.UntilDeleted;
}
}
}
diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
index 5d92a212f..978e9e1a8 100644
--- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
@@ -1,10 +1,17 @@
using MediaBrowser.Model.LiveTv;
using System;
+using System.Collections.Generic;
namespace MediaBrowser.Controller.LiveTv
{
public class TimerInfo
{
+ public TimerInfo()
+ {
+ Genres = new List<string>();
+ KeepUntil = KeepUntil.UntilDeleted;
+ }
+
/// <summary>
/// Id of the recording.
/// </summary>
@@ -15,7 +22,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The series timer identifier.</value>
public string SeriesTimerId { get; set; }
-
+
/// <summary>
/// ChannelId of the recording.
/// </summary>
@@ -26,7 +33,7 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value>The program identifier.</value>
public string ProgramId { get; set; }
-
+
/// <summary>
/// Name of the recording.
/// </summary>
@@ -76,11 +83,35 @@ namespace MediaBrowser.Controller.LiveTv
/// </summary>
/// <value><c>true</c> if this instance is post padding required; otherwise, <c>false</c>.</value>
public bool IsPostPaddingRequired { get; set; }
-
+
/// <summary>
/// Gets or sets the priority.
/// </summary>
/// <value>The priority.</value>
public int Priority { get; set; }
+
+
+ // Program properties
+ public int? SeasonNumber { get; set; }
+ /// <summary>
+ /// Gets or sets the episode number.
+ /// </summary>
+ /// <value>The episode number.</value>
+ public int? EpisodeNumber { get; set; }
+ public bool IsMovie { get; set; }
+ public bool IsKids { get; set; }
+ public bool IsSports { get; set; }
+ public bool IsNews { get; set; }
+ public int? ProductionYear { get; set; }
+ public string EpisodeTitle { get; set; }
+ public DateTime? OriginalAirDate { get; set; }
+ public bool IsProgramSeries { get; set; }
+ public string HomePageUrl { get; set; }
+ public float? CommunityRating { get; set; }
+ public string ShortOverview { get; set; }
+ public string OfficialRating { get; set; }
+ public List<string> Genres { get; set; }
+ public string RecordingPath { get; set; }
+ public KeepUntil KeepUntil { get; set; }
}
}
diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
index e7eaa1dc0..d70fba742 100644
--- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj
+++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
@@ -98,6 +98,7 @@
<Compile Include="Collections\CollectionCreationOptions.cs" />
<Compile Include="Collections\CollectionEvents.cs" />
<Compile Include="Collections\ICollectionManager.cs" />
+ <Compile Include="Collections\ManualCollectionsFolder.cs" />
<Compile Include="Connect\ConnectSupporterSummary.cs" />
<Compile Include="Connect\IConnectManager.cs" />
<Compile Include="Connect\UserLinkResult.cs" />
@@ -198,9 +199,9 @@
<Compile Include="Library\NameExtensions.cs" />
<Compile Include="Library\PlaybackStopEventArgs.cs" />
<Compile Include="Library\UserDataSaveEventArgs.cs" />
- <Compile Include="LiveTv\IHasRegistrationInfo.cs" />
<Compile Include="LiveTv\IListingsProvider.cs" />
<Compile Include="LiveTv\ITunerHost.cs" />
+ <Compile Include="LiveTv\LiveStream.cs" />
<Compile Include="LiveTv\RecordingGroup.cs" />
<Compile Include="LiveTv\RecordingStatusChangedEventArgs.cs" />
<Compile Include="LiveTv\ILiveTvRecording.cs" />
@@ -266,7 +267,6 @@
<Compile Include="Playlists\IPlaylistManager.cs" />
<Compile Include="Playlists\Playlist.cs" />
<Compile Include="Plugins\ILocalizablePlugin.cs" />
- <Compile Include="Power\IPowerManagement.cs" />
<Compile Include="Providers\AlbumInfo.cs" />
<Compile Include="Providers\ArtistInfo.cs" />
<Compile Include="Providers\BookInfo.cs" />
@@ -319,7 +319,6 @@
<Compile Include="Providers\SongInfo.cs" />
<Compile Include="Providers\TrailerInfo.cs" />
<Compile Include="Providers\VideoContentType.cs" />
- <Compile Include="RelatedMedia\IRelatedMediaProvider.cs" />
<Compile Include="Security\AuthenticationInfo.cs" />
<Compile Include="Security\AuthenticationInfoQuery.cs" />
<Compile Include="Security\IAuthenticationRepository.cs" />
diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
index 7fdbf020c..f97fe9560 100644
--- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
@@ -45,9 +45,9 @@ namespace MediaBrowser.Controller.MediaEncoding
/// <param name="offset">The offset.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{Stream}.</returns>
- Task<string> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken);
+ Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken);
- Task<string> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, int? imageStreamIndex, CancellationToken cancellationToken);
+ Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, int? imageStreamIndex, CancellationToken cancellationToken);
/// <summary>
/// Extracts the video images on interval.
diff --git a/MediaBrowser.Controller/Power/IPowerManagement.cs b/MediaBrowser.Controller/Power/IPowerManagement.cs
deleted file mode 100644
index faa289695..000000000
--- a/MediaBrowser.Controller/Power/IPowerManagement.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System;
-
-namespace MediaBrowser.Controller.Power
-{
- public interface IPowerManagement
- {
- /// <summary>
- /// Schedules the wake.
- /// </summary>
- /// <param name="utcTime">The UTC time.</param>
- void ScheduleWake(DateTime utcTime);
- }
-}
diff --git a/MediaBrowser.Controller/Providers/BaseItemXmlParser.cs b/MediaBrowser.Controller/Providers/BaseItemXmlParser.cs
index 4484adb1d..fccbd9211 100644
--- a/MediaBrowser.Controller/Providers/BaseItemXmlParser.cs
+++ b/MediaBrowser.Controller/Providers/BaseItemXmlParser.cs
@@ -790,20 +790,25 @@ namespace MediaBrowser.Controller.Providers
}
default:
- if (_validProviderIds.ContainsKey(reader.Name))
- {
- var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
+ {
+ string readerName = reader.Name;
+ string providerIdValue;
+ if (_validProviderIds.TryGetValue(readerName, out providerIdValue))
{
- item.SetProviderId(_validProviderIds[reader.Name], id);
+ var id = reader.ReadElementContentAsString();
+ if (!string.IsNullOrWhiteSpace(id))
+ {
+ item.SetProviderId(providerIdValue, id);
+ }
+ }
+ else
+ {
+ reader.Skip();
}
- }
- else
- {
- reader.Skip();
- }
- break;
+ break;
+
+ }
}
}
diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs
index 17175f91c..99402a969 100644
--- a/MediaBrowser.Controller/Providers/MetadataResult.cs
+++ b/MediaBrowser.Controller/Providers/MetadataResult.cs
@@ -13,13 +13,15 @@ namespace MediaBrowser.Controller.Providers
public MetadataResult()
{
Images = new List<LocalImageInfo>();
+ ResultLanguage = "en";
}
public List<PersonInfo> People { get; set; }
public bool HasMetadata { get; set; }
public T Item { get; set; }
-
+ public string ResultLanguage { get; set; }
+ public bool QueriedById { get; set; }
public void AddPerson(PersonInfo p)
{
if (People == null)
diff --git a/MediaBrowser.Controller/RelatedMedia/IRelatedMediaProvider.cs b/MediaBrowser.Controller/RelatedMedia/IRelatedMediaProvider.cs
deleted file mode 100644
index bb2a0cd89..000000000
--- a/MediaBrowser.Controller/RelatedMedia/IRelatedMediaProvider.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace MediaBrowser.Controller.RelatedMedia
-{
- public interface IRelatedMediaProvider
- {
- /// <summary>
- /// Gets the name.
- /// </summary>
- /// <value>The name.</value>
- string Name { get; }
- }
-}
diff --git a/MediaBrowser.Controller/Session/AuthenticationRequest.cs b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
index bfd7f928b..362f5b2b9 100644
--- a/MediaBrowser.Controller/Session/AuthenticationRequest.cs
+++ b/MediaBrowser.Controller/Session/AuthenticationRequest.cs
@@ -4,6 +4,7 @@ namespace MediaBrowser.Controller.Session
public class AuthenticationRequest
{
public string Username { get; set; }
+ public string UserId { get; set; }
public string PasswordSha1 { get; set; }
public string PasswordMd5 { get; set; }
public string App { get; set; }
diff --git a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs
index 9f2726b31..51e115cc2 100644
--- a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs
+++ b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs
@@ -14,8 +14,11 @@ using MediaBrowser.Dlna.Ssdp;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Generic;
+using System.Linq;
+using System.Net;
using System.Threading.Tasks;
using MediaBrowser.Controller.MediaEncoding;
+using Rssdp;
namespace MediaBrowser.Dlna.Main
{
@@ -38,12 +41,11 @@ namespace MediaBrowser.Dlna.Main
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder;
- private readonly SsdpHandler _ssdpHandler;
private readonly IDeviceDiscovery _deviceDiscovery;
- private readonly List<string> _registeredServerIds = new List<string>();
private bool _ssdpHandlerStarted;
private bool _dlnaServerStarted;
+ private SsdpDevicePublisher _Publisher;
public DlnaEntryPoint(IServerConfigurationManager config,
ILogManager logManager,
@@ -58,7 +60,7 @@ namespace MediaBrowser.Dlna.Main
IUserDataManager userDataManager,
ILocalizationManager localization,
IMediaSourceManager mediaSourceManager,
- ISsdpHandler ssdpHandler, IDeviceDiscovery deviceDiscovery, IMediaEncoder mediaEncoder)
+ IDeviceDiscovery deviceDiscovery, IMediaEncoder mediaEncoder)
{
_config = config;
_appHost = appHost;
@@ -74,7 +76,6 @@ namespace MediaBrowser.Dlna.Main
_mediaSourceManager = mediaSourceManager;
_deviceDiscovery = deviceDiscovery;
_mediaEncoder = mediaEncoder;
- _ssdpHandler = (SsdpHandler)ssdpHandler;
_logger = logManager.GetLogger("Dlna");
}
@@ -110,18 +111,6 @@ namespace MediaBrowser.Dlna.Main
{
var options = _config.GetDlnaConfiguration();
- if (!options.EnableServer && !options.EnablePlayTo && !_config.Configuration.EnableUPnP)
- {
- if (_ssdpHandlerStarted)
- {
- // Sat/ip live tv depends on device discovery, as well as hd homerun detection
- // In order to allow this to be disabled, we need a modular way of knowing if there are
- // any parts of the system that are dependant on it
- // DisposeSsdpHandler();
- }
- return;
- }
-
if (!_ssdpHandlerStarted)
{
StartSsdpHandler();
@@ -154,7 +143,7 @@ namespace MediaBrowser.Dlna.Main
{
try
{
- _ssdpHandler.Start();
+ StartPublishing();
_ssdpHandlerStarted = true;
StartDeviceDiscovery();
@@ -165,13 +154,16 @@ namespace MediaBrowser.Dlna.Main
}
}
+ private void StartPublishing()
+ {
+ _Publisher = new SsdpDevicePublisher();
+ }
+
private void StartDeviceDiscovery()
{
try
{
- ((DeviceDiscovery)_deviceDiscovery).Start(_ssdpHandler);
-
- //DlnaChannel.Current.Start(() => _registeredServerIds.ToList());
+ ((DeviceDiscovery)_deviceDiscovery).Start();
}
catch (Exception ex)
{
@@ -199,8 +191,6 @@ namespace MediaBrowser.Dlna.Main
{
((DeviceDiscovery)_deviceDiscovery).Dispose();
- _ssdpHandler.Dispose();
-
_ssdpHandlerStarted = false;
}
catch (Exception ex)
@@ -225,7 +215,17 @@ namespace MediaBrowser.Dlna.Main
private async Task RegisterServerEndpoints()
{
- foreach (var address in await _appHost.GetLocalIpAddresses().ConfigureAwait(false))
+ if (!_config.GetDlnaConfiguration().BlastAliveMessages)
+ {
+ return;
+ }
+
+ var cacheLength = _config.GetDlnaConfiguration().BlastAliveMessageIntervalSeconds * 2;
+ _Publisher.SupportPnpRootDevice = false;
+
+ var addresses = (await _appHost.GetLocalIpAddresses().ConfigureAwait(false)).ToList();
+
+ foreach (var address in addresses)
{
//if (IPAddress.IsLoopback(address))
//{
@@ -234,25 +234,46 @@ namespace MediaBrowser.Dlna.Main
//}
var addressString = address.ToString();
- var udn = addressString.GetMD5().ToString("N");
-
- var descriptorURI = "/dlna/" + udn + "/description.xml";
- var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorURI);
+ var udn = (addressString).GetMD5().ToString("N");
var services = new List<string>
{
- "upnp:rootdevice",
"urn:schemas-upnp-org:device:MediaServer:1",
"urn:schemas-upnp-org:service:ContentDirectory:1",
"urn:schemas-upnp-org:service:ConnectionManager:1",
- "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1",
- "uuid:" + udn
+ "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
};
- _ssdpHandler.RegisterNotification(udn, uri, address, services);
+ foreach (var fullService in services)
+ {
+ _logger.Info("Registering publisher for {0} on {1}", fullService, addressString);
+
+ var descriptorURI = "/dlna/" + udn + "/description.xml";
+ var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorURI);
+
+ var service = fullService.Replace("urn:", string.Empty).Replace(":1", string.Empty);
+
+ var serviceParts = service.Split(':');
+
+ var deviceTypeNamespace = serviceParts[0].Replace('.', '-');
- _registeredServerIds.Add(udn);
+ var device = new SsdpRootDevice
+ {
+ CacheLifetime = TimeSpan.FromSeconds(cacheLength), //How long SSDP clients can cache this info.
+ Location = uri, // Must point to the URL that serves your devices UPnP description document.
+ DeviceTypeNamespace = deviceTypeNamespace,
+ DeviceClass = serviceParts[1],
+ DeviceType = serviceParts[2],
+ FriendlyName = "Emby Server",
+ Manufacturer = "Emby",
+ ModelName = "Emby Server",
+ Uuid = udn
+ // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
+ };
+
+ _Publisher.AddDevice(device);
+ }
}
}
@@ -315,19 +336,25 @@ namespace MediaBrowser.Dlna.Main
public void DisposeDlnaServer()
{
- foreach (var id in _registeredServerIds)
+ if (_Publisher != null)
{
- try
- {
- _ssdpHandler.UnregisterNotification(id);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error unregistering server", ex);
- }
- }
+ var devices = _Publisher.Devices.ToList();
+ var tasks = devices.Select(i => _Publisher.RemoveDevice(i)).ToArray();
- _registeredServerIds.Clear();
+ Task.WaitAll(tasks);
+ //foreach (var device in devices)
+ //{
+ // try
+ // {
+ // _Publisher.RemoveDevice(device);
+ // }
+ // catch (Exception ex)
+ // {
+ // _logger.ErrorException("Error sending bye bye", ex);
+ // }
+ //}
+ _Publisher.Dispose();
+ }
_dlnaServerStarted = false;
}
diff --git a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj
index d10a5f7b5..ae2e43a4f 100644
--- a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj
+++ b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -14,6 +14,7 @@
<SchemaVersion>2.0</SchemaVersion>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -23,7 +24,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
@@ -32,7 +33,7 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release Mono|AnyCPU' ">
<Optimize>false</Optimize>
@@ -50,8 +51,15 @@
<Reference Include="Patterns.Logging">
<HintPath>..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll</HintPath>
</Reference>
+ <Reference Include="Rssdp.NetFx40">
+ <HintPath>..\ThirdParty\rssdp\Rssdp.NetFx40.dll</HintPath>
+ </Reference>
+ <Reference Include="Rssdp.Portable">
+ <HintPath>..\ThirdParty\rssdp\Rssdp.Portable.dll</HintPath>
+ </Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
+ <Reference Include="System.Net.Http" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
diff --git a/MediaBrowser.Dlna/PlayTo/Device.cs b/MediaBrowser.Dlna/PlayTo/Device.cs
index 174ca871a..b656bc66e 100644
--- a/MediaBrowser.Dlna/PlayTo/Device.cs
+++ b/MediaBrowser.Dlna/PlayTo/Device.cs
@@ -474,7 +474,7 @@ namespace MediaBrowser.Dlna.PlayTo
if (_disposed)
return;
- _logger.ErrorException("Error updating device info for {0}", ex, Properties.Name);
+ //_logger.ErrorException("Error updating device info for {0}", ex, Properties.Name);
_successiveStopCount++;
_connectFailureCount++;
@@ -483,7 +483,9 @@ namespace MediaBrowser.Dlna.PlayTo
{
if (OnDeviceUnavailable != null)
{
+ _logger.Debug("Disposing device due to loss of connection");
OnDeviceUnavailable();
+ return;
}
}
if (_successiveStopCount >= maxSuccessiveStopReturns)
diff --git a/MediaBrowser.Dlna/PlayTo/PlayToController.cs b/MediaBrowser.Dlna/PlayTo/PlayToController.cs
index 5622885fc..6345e2105 100644
--- a/MediaBrowser.Dlna/PlayTo/PlayToController.cs
+++ b/MediaBrowser.Dlna/PlayTo/PlayToController.cs
@@ -19,6 +19,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Events;
namespace MediaBrowser.Dlna.PlayTo
{
@@ -122,16 +123,18 @@ namespace MediaBrowser.Dlna.PlayTo
}
}
- void _deviceDiscovery_DeviceLeft(object sender, SsdpMessageEventArgs e)
+ void _deviceDiscovery_DeviceLeft(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
+ var info = e.Argument;
+
string nts;
- e.Headers.TryGetValue("NTS", out nts);
+ info.Headers.TryGetValue("NTS", out nts);
string usn;
- if (!e.Headers.TryGetValue("USN", out usn)) usn = String.Empty;
+ if (!info.Headers.TryGetValue("USN", out usn)) usn = String.Empty;
string nt;
- if (!e.Headers.TryGetValue("NT", out nt)) nt = String.Empty;
+ if (!info.Headers.TryGetValue("NT", out nt)) nt = String.Empty;
if (usn.IndexOf(_device.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1 &&
!_disposed)
@@ -653,7 +656,7 @@ namespace MediaBrowser.Dlna.PlayTo
_device.PlaybackProgress -= _device_PlaybackProgress;
_device.PlaybackStopped -= _device_PlaybackStopped;
_device.MediaChanged -= _device_MediaChanged;
- _deviceDiscovery.DeviceLeft -= _deviceDiscovery_DeviceLeft;
+ //_deviceDiscovery.DeviceLeft -= _deviceDiscovery_DeviceLeft;
_device.OnDeviceUnavailable = null;
_device.Dispose();
@@ -824,6 +827,7 @@ namespace MediaBrowser.Dlna.PlayTo
public string DeviceId { get; set; }
public string MediaSourceId { get; set; }
+ public string LiveStreamId { get; set; }
public BaseItem Item { get; set; }
public MediaSourceInfo MediaSource { get; set; }
@@ -907,6 +911,10 @@ namespace MediaBrowser.Dlna.PlayTo
{
request.StartPositionTicks = long.Parse(val, CultureInfo.InvariantCulture);
}
+ else if (i == 22)
+ {
+ request.LiveStreamId = val;
+ }
}
request.Item = string.IsNullOrWhiteSpace(request.ItemId)
@@ -917,7 +925,7 @@ namespace MediaBrowser.Dlna.PlayTo
request.MediaSource = hasMediaSources == null
? null
- : (await mediaSourceManager.GetMediaSource(hasMediaSources, request.MediaSourceId, false).ConfigureAwait(false));
+ : (await mediaSourceManager.GetMediaSource(hasMediaSources, request.MediaSourceId, request.LiveStreamId, false, CancellationToken.None).ConfigureAwait(false));
return request;
}
diff --git a/MediaBrowser.Dlna/PlayTo/PlayToManager.cs b/MediaBrowser.Dlna/PlayTo/PlayToManager.cs
index cd9a7b1f0..6d6986f01 100644
--- a/MediaBrowser.Dlna/PlayTo/PlayToManager.cs
+++ b/MediaBrowser.Dlna/PlayTo/PlayToManager.cs
@@ -12,7 +12,9 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
+using System.Threading.Tasks;
using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Events;
namespace MediaBrowser.Dlna.PlayTo
{
@@ -61,16 +63,17 @@ namespace MediaBrowser.Dlna.PlayTo
_deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
}
- async void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
+ async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
+ var info = e.Argument;
+
string usn;
- if (!e.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
+ if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
string nt;
- if (!e.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
+ if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
- string location;
- if (!e.Headers.TryGetValue("Location", out location)) location = string.Empty;
+ string location = info.Location.ToString();
// It has to report that it's a media renderer
if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 &&
@@ -100,7 +103,7 @@ namespace MediaBrowser.Dlna.PlayTo
}
}
- var uri = new Uri(location);
+ var uri = info.Location;
_logger.Debug("Attempting to create PlayToController from location {0}", location);
var device = await Device.CreateuPnpDeviceAsync(uri, _httpClient, _config, _logger).ConfigureAwait(false);
@@ -121,7 +124,7 @@ namespace MediaBrowser.Dlna.PlayTo
if (controller == null)
{
- var serverAddress = GetServerAddress(e.LocalEndPoint.Address);
+ var serverAddress = await GetServerAddress(info.LocalEndPoint == null ? null : info.LocalEndPoint.Address).ConfigureAwait(false);
string accessToken = null;
sessionInfo.SessionController = controller = new PlayToController(sessionInfo,
@@ -173,9 +176,14 @@ namespace MediaBrowser.Dlna.PlayTo
}
}
- private string GetServerAddress(IPAddress localIp)
+ private Task<string> GetServerAddress(IPAddress localIp)
{
- return _appHost.GetLocalApiUrl(localIp);
+ if (localIp == null)
+ {
+ return _appHost.GetLocalApiUrl();
+ }
+
+ return Task.FromResult(_appHost.GetLocalApiUrl(localIp));
}
public void Dispose()
diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs
index 68768745e..c9bba526a 100644
--- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs
+++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs
@@ -11,6 +11,8 @@ using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
+using MediaBrowser.Model.Events;
+using Rssdp;
namespace MediaBrowser.Dlna.Ssdp
{
@@ -20,211 +22,114 @@ namespace MediaBrowser.Dlna.Ssdp
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
- private SsdpHandler _ssdpHandler;
private readonly CancellationTokenSource _tokenSource;
- private readonly IServerApplicationHost _appHost;
- public event EventHandler<SsdpMessageEventArgs> DeviceDiscovered;
- public event EventHandler<SsdpMessageEventArgs> DeviceLeft;
- private readonly INetworkManager _networkManager;
+ public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscovered;
+ public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceLeft;
- public DeviceDiscovery(ILogger logger, IServerConfigurationManager config, IServerApplicationHost appHost, INetworkManager networkManager)
+ private SsdpDeviceLocator _DeviceLocator;
+
+ public DeviceDiscovery(ILogger logger, IServerConfigurationManager config)
{
_tokenSource = new CancellationTokenSource();
_logger = logger;
_config = config;
- _appHost = appHost;
- _networkManager = networkManager;
}
- private List<IPAddress> GetLocalIpAddresses()
- {
- return _networkManager.GetLocalIpAddresses().ToList();
- }
-
- public void Start(SsdpHandler ssdpHandler)
+ // Call this method from somewhere in your code to start the search.
+ public void BeginSearch()
{
- _ssdpHandler = ssdpHandler;
- _ssdpHandler.MessageReceived += _ssdpHandler_MessageReceived;
-
- foreach (var localIp in GetLocalIpAddresses())
- {
- try
- {
- CreateListener(localIp);
- }
- catch (Exception e)
- {
- _logger.ErrorException("Failed to Initilize Socket", e);
- }
- }
- }
+ _DeviceLocator = new SsdpDeviceLocator();
- async void _ssdpHandler_MessageReceived(object sender, SsdpMessageEventArgs e)
- {
- string nts;
- e.Headers.TryGetValue("NTS", out nts);
+ // (Optional) Set the filter so we only see notifications for devices we care about
+ // (can be any search target value i.e device type, uuid value etc - any value that appears in the
+ // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
+ //_DeviceLocator.NotificationFilter = "upnp:rootdevice";
- if (String.Equals(e.Method, "NOTIFY", StringComparison.OrdinalIgnoreCase) &&
- String.Equals(nts, "ssdp:byebye", StringComparison.OrdinalIgnoreCase) &&
- !_disposed)
- {
- EventHelper.FireEventIfNotNull(DeviceLeft, this, e, _logger);
- return;
- }
+ // Connect our event handler so we process devices as they are found
+ _DeviceLocator.DeviceAvailable += deviceLocator_DeviceAvailable;
+ _DeviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable;
- try
- {
- if (e.LocalEndPoint == null)
- {
- var ip = (await _appHost.GetLocalIpAddresses().ConfigureAwait(false)).FirstOrDefault(i => !IPAddress.IsLoopback(i));
- if (ip != null)
- {
- e.LocalEndPoint = new IPEndPoint(ip, 0);
- }
- }
-
- if (e.LocalEndPoint != null)
- {
- TryCreateDevice(e);
- }
- }
- catch (OperationCanceledException)
- {
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error creating play to controller", ex);
- }
+ // Perform a search so we don't have to wait for devices to broadcast notifications
+ // again to get any results right away (notifications are broadcast periodically).
+ StartAsyncSearch();
}
- private void CreateListener(IPAddress localIp)
+ private void StartAsyncSearch()
{
Task.Factory.StartNew(async (o) =>
{
- try
+ while (!_tokenSource.IsCancellationRequested)
{
- _logger.Info("Creating SSDP listener on {0}", localIp);
-
- var endPoint = new IPEndPoint(localIp, 1900);
-
- using (var socket = GetMulticastSocket(localIp, endPoint))
+ try
{
- var receiveBuffer = new byte[64000];
-
- CreateNotifier(localIp);
-
- while (!_tokenSource.IsCancellationRequested)
- {
- var receivedBytes = await socket.ReceiveAsync(receiveBuffer, 0, 64000);
+ // Enable listening for notifications (optional)
+ _DeviceLocator.StartListeningForNotifications();
- if (receivedBytes > 0)
- {
- var args = SsdpHelper.ParseSsdpResponse(receiveBuffer);
- args.EndPoint = endPoint;
- args.LocalEndPoint = new IPEndPoint(localIp, 0);
-
- _ssdpHandler.LogMessageReceived(args, true);
-
- TryCreateDevice(args);
- }
- }
+ await _DeviceLocator.SearchAsync().ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error searching for devices", ex);
}
- _logger.Info("SSDP listener - Task completed");
- }
- catch (OperationCanceledException)
- {
- }
- catch (Exception e)
- {
- _logger.ErrorException("Error in listener", e);
+ var delay = _config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds * 1000;
+
+ await Task.Delay(delay, _tokenSource.Token).ConfigureAwait(false);
}
- }, _tokenSource.Token, TaskCreationOptions.LongRunning);
+ }, CancellationToken.None, TaskCreationOptions.LongRunning);
}
- private void CreateNotifier(IPAddress localIp)
+ // Process each found device in the event handler
+ void deviceLocator_DeviceAvailable(object sender, DeviceAvailableEventArgs e)
{
- Task.Factory.StartNew(async (o) =>
- {
- try
- {
- while (true)
- {
- _ssdpHandler.SendSearchMessage(new IPEndPoint(localIp, 1900));
+ var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
- var delay = _config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds * 1000;
+ var headerDict = originalHeaders == null ? new Dictionary<string, KeyValuePair<string, IEnumerable<string>>>() : originalHeaders.ToDictionary(i => i.Key, StringComparer.OrdinalIgnoreCase);
- await Task.Delay(delay, _tokenSource.Token).ConfigureAwait(false);
- }
- }
- catch (OperationCanceledException)
- {
- }
- catch (Exception ex)
+ var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
+
+ var args = new GenericEventArgs<UpnpDeviceInfo>
+ {
+ Argument = new UpnpDeviceInfo
{
- _logger.ErrorException("Error in notifier", ex);
+ Location = e.DiscoveredDevice.DescriptionLocation,
+ Headers = headers
}
+ };
- }, _tokenSource.Token, TaskCreationOptions.LongRunning);
+ EventHelper.FireEventIfNotNull(DeviceDiscovered, this, args, _logger);
}
- private Socket GetMulticastSocket(IPAddress localIpAddress, EndPoint localEndpoint)
+ private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
{
- var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIpAddress));
- socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
-
- socket.Bind(localEndpoint);
+ var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
- return socket;
- }
+ var headerDict = originalHeaders == null ? new Dictionary<string, KeyValuePair<string, IEnumerable<string>>>() : originalHeaders.ToDictionary(i => i.Key, StringComparer.OrdinalIgnoreCase);
- private void TryCreateDevice(SsdpMessageEventArgs args)
- {
- string nts;
- args.Headers.TryGetValue("NTS", out nts);
+ var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
- if (String.Equals(nts, "ssdp:byebye", StringComparison.OrdinalIgnoreCase))
+ var args = new GenericEventArgs<UpnpDeviceInfo>
{
- if (String.Equals(args.Method, "NOTIFY", StringComparison.OrdinalIgnoreCase))
+ Argument = new UpnpDeviceInfo
{
- if (!_disposed)
- {
- EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger);
- }
+ Location = e.DiscoveredDevice.DescriptionLocation,
+ Headers = headers
}
+ };
- return;
- }
-
- string usn;
- if (!args.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
-
- string nt;
- if (!args.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
-
- // Need to be able to download device description
- string location;
- if (!args.Headers.TryGetValue("Location", out location) ||
- string.IsNullOrEmpty(location))
- {
- return;
- }
+ EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger);
+ }
- EventHelper.FireEventIfNotNull(DeviceDiscovered, this, args, _logger);
+ public void Start()
+ {
+ BeginSearch();
}
public void Dispose()
{
- if (_ssdpHandler != null)
- {
- _ssdpHandler.MessageReceived -= _ssdpHandler_MessageReceived;
- }
-
if (!_disposed)
{
_disposed = true;
diff --git a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs
index 720ea71a0..0d0ca98a2 100644
--- a/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs
+++ b/MediaBrowser.Dlna/Ssdp/SsdpHandler.cs
@@ -83,90 +83,6 @@ namespace MediaBrowser.Dlna.Ssdp
}
}
- public event EventHandler<SsdpMessageEventArgs> MessageReceived;
-
- private async void OnMessageReceived(SsdpMessageEventArgs args, bool isMulticast)
- {
- if (IgnoreMessage(args, isMulticast))
- {
- return;
- }
-
- LogMessageReceived(args, isMulticast);
-
- var headers = args.Headers;
- string st;
-
- if (string.Equals(args.Method, "M-SEARCH", StringComparison.OrdinalIgnoreCase) && headers.TryGetValue("st", out st))
- {
- TimeSpan delay = GetSearchDelay(headers);
-
- if (_config.GetDlnaConfiguration().EnableDebugLog)
- {
- _logger.Debug("Delaying search response by {0} seconds", delay.TotalSeconds);
- }
-
- await Task.Delay(delay).ConfigureAwait(false);
-
- RespondToSearch(args.EndPoint, st);
- }
-
- EventHelper.FireEventIfNotNull(MessageReceived, this, args, _logger);
- }
-
- internal void LogMessageReceived(SsdpMessageEventArgs args, bool isMulticast)
- {
- var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
-
- if (enableDebugLogging)
- {
- var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
- var headerText = string.Join(",", headerTexts.ToArray());
-
- var protocol = isMulticast ? "Multicast" : "Unicast";
- var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
- _logger.Debug("{0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
- }
- }
-
- internal bool IgnoreMessage(SsdpMessageEventArgs args, bool isMulticast)
- {
- string usn;
- if (args.Headers.TryGetValue("USN", out usn))
- {
- // USN=uuid:b67df29b5c379445fde78c3774ab518d::urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1
- if (RegisteredDevices.Any(i => string.Equals(i.USN, usn, StringComparison.OrdinalIgnoreCase)))
- {
- //var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
- //var headerText = string.Join(",", headerTexts.ToArray());
-
- //var protocol = isMulticast ? "Multicast" : "Unicast";
- //var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
- //_logger.Debug("IGNORING {0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
-
- return true;
- }
- }
-
- string serverId;
- if (args.Headers.TryGetValue("X-EMBY-SERVERID", out serverId))
- {
- if (string.Equals(serverId, _appHost.SystemId, StringComparison.OrdinalIgnoreCase))
- {
- //var headerTexts = args.Headers.Select(i => string.Format("{0}={1}", i.Key, i.Value));
- //var headerText = string.Join(",", headerTexts.ToArray());
-
- //var protocol = isMulticast ? "Multicast" : "Unicast";
- //var localEndPointString = args.LocalEndPoint == null ? "null" : args.LocalEndPoint.ToString();
- //_logger.Debug("IGNORING {0} message received from {1} on {3}. Protocol: {4} Headers: {2}", args.Method, args.EndPoint, headerText, localEndPointString, protocol);
-
- return true;
- }
- }
-
- return false;
- }
-
public IEnumerable<UpnpDevice> RegisteredDevices
{
get
@@ -188,8 +104,6 @@ namespace MediaBrowser.Dlna.Ssdp
RestartSocketListener();
ReloadAliveNotifier();
- CreateUnicastClient();
-
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
}
@@ -202,32 +116,6 @@ namespace MediaBrowser.Dlna.Ssdp
}
}
- public void SendSearchMessage(EndPoint localIp)
- {
- var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- values["HOST"] = "239.255.255.250:1900";
- values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
- values["X-EMBY-SERVERID"] = _appHost.SystemId;
-
- values["MAN"] = "\"ssdp:discover\"";
-
- // Search target
- values["ST"] = "ssdp:all";
-
- // Seconds to delay response
- values["MX"] = "3";
-
- var header = "M-SEARCH * HTTP/1.1";
-
- var msg = new SsdpMessageBuilder().BuildMessage(header, values);
-
- // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
- SendDatagram(msg, _ssdpEndp, localIp, true);
-
- SendUnicastRequest(msg);
- }
-
public async void SendDatagram(string msg,
EndPoint endpoint,
EndPoint localAddress,
@@ -248,75 +136,6 @@ namespace MediaBrowser.Dlna.Ssdp
}
}
- /// <summary>
- /// According to the spec: http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf
- /// Device responses should be delayed a random duration between 0 and this many seconds to balance
- /// load for the control point when it processes responses. In my testing kodi times out after mx
- /// so we will generate from mx - 1
- /// </summary>
- /// <param name="headers">The mx headers</param>
- /// <returns>A timepsan for the amount to delay before returning search result.</returns>
- private TimeSpan GetSearchDelay(Dictionary<string, string> headers)
- {
- string mx;
- headers.TryGetValue("mx", out mx);
- int delaySeconds = 0;
- if (!string.IsNullOrWhiteSpace(mx)
- && int.TryParse(mx, NumberStyles.Any, CultureInfo.InvariantCulture, out delaySeconds)
- && delaySeconds > 1)
- {
- delaySeconds = new Random().Next(delaySeconds - 1);
- }
-
- return TimeSpan.FromSeconds(delaySeconds);
- }
-
- private void RespondToSearch(EndPoint endpoint, string deviceType)
- {
- var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
-
- var isLogged = false;
-
- const string header = "HTTP/1.1 200 OK";
-
- foreach (var d in RegisteredDevices)
- {
- if (string.Equals(deviceType, "ssdp:all", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(deviceType, d.Type, StringComparison.OrdinalIgnoreCase))
- {
- if (!isLogged)
- {
- if (enableDebugLogging)
- {
- _logger.Debug("Responding to search from {0} for {1}", endpoint, deviceType);
- }
- isLogged = true;
- }
-
- var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
-
- values["CACHE-CONTROL"] = "max-age = 600";
- values["DATE"] = DateTime.Now.ToString("R");
- values["EXT"] = "";
- values["LOCATION"] = d.Descriptor.ToString();
- values["SERVER"] = _serverSignature;
- values["ST"] = d.Type;
- values["USN"] = d.USN;
-
- var msg = new SsdpMessageBuilder().BuildMessage(header, values);
-
- SendDatagram(msg, endpoint, null, false, 2);
- SendDatagram(msg, endpoint, new IPEndPoint(d.Address, 0), false, 2);
- //SendDatagram(header, values, endpoint, null, true);
-
- if (enableDebugLogging)
- {
- _logger.Debug("{1} - Responded to a {0} request to {2}", d.Type, endpoint, d.Address.ToString());
- }
- }
- }
- }
-
private void RestartSocketListener()
{
if (_isDisposed)
@@ -329,8 +148,6 @@ namespace MediaBrowser.Dlna.Ssdp
_multicastSocket = CreateMulticastSocket();
_logger.Info("MultiCast socket created");
-
- Receive();
}
catch (Exception ex)
{
@@ -339,74 +156,6 @@ namespace MediaBrowser.Dlna.Ssdp
}
}
- private void Receive()
- {
- try
- {
- var buffer = new byte[1024];
-
- EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
-
- _multicastSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endpoint, ReceiveCallback, buffer);
- }
- catch (ObjectDisposedException)
- {
- if (!_isDisposed)
- {
- //StartSocketRetryTimer();
- }
- }
- catch (Exception ex)
- {
- _logger.Debug("Error in BeginReceiveFrom", ex);
- }
- }
-
- private void ReceiveCallback(IAsyncResult result)
- {
- if (_isDisposed)
- {
- return;
- }
-
- try
- {
- EndPoint endpoint = new IPEndPoint(IPAddress.Any, SSDPPort);
-
- var length = _multicastSocket.EndReceiveFrom(result, ref endpoint);
-
- var received = (byte[])result.AsyncState;
-
- var enableDebugLogging = _config.GetDlnaConfiguration().EnableDebugLog;
-
- if (enableDebugLogging)
- {
- _logger.Debug(Encoding.ASCII.GetString(received));
- }
-
- var args = SsdpHelper.ParseSsdpResponse(received);
- args.EndPoint = endpoint;
-
- OnMessageReceived(args, true);
- }
- catch (ObjectDisposedException)
- {
- if (!_isDisposed)
- {
- //StartSocketRetryTimer();
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Failed to read SSDP message", ex);
- }
-
- if (_multicastSocket != null)
- {
- Receive();
- }
- }
-
public void Dispose()
{
_config.NamedConfigurationUpdated -= _config_ConfigurationUpdated;
@@ -414,7 +163,6 @@ namespace MediaBrowser.Dlna.Ssdp
_isDisposed = true;
- DisposeUnicastClient();
DisposeSocket();
StopAliveNotifier();
}
@@ -523,137 +271,6 @@ namespace MediaBrowser.Dlna.Ssdp
}
}
- private void CreateUnicastClient()
- {
- if (_unicastClient == null)
- {
- try
- {
- _unicastClient = new UdpClient(_unicastPort);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error creating unicast client", ex);
- }
-
- UnicastSetBeginReceive();
- }
- }
-
- private void DisposeUnicastClient()
- {
- if (_unicastClient != null)
- {
- try
- {
- _unicastClient.Close();
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error closing unicast client", ex);
- }
-
- _unicastClient = null;
- }
- }
-
- /// <summary>
- /// Listen for Unicast SSDP Responses
- /// </summary>
- private void UnicastSetBeginReceive()
- {
- try
- {
- var ipRxEnd = new IPEndPoint(IPAddress.Any, _unicastPort);
- var udpListener = new UdpState { EndPoint = ipRxEnd };
-
- udpListener.UdpClient = _unicastClient;
- _unicastClient.BeginReceive(UnicastReceiveCallback, udpListener);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error in UnicastSetBeginReceive", ex);
- }
- }
-
- /// <summary>
- /// The UnicastReceiveCallback receives Http Responses
- /// and Fired the SatIpDeviceFound Event for adding the SatIpDevice
- /// </summary>
- /// <param name="ar"></param>
- private void UnicastReceiveCallback(IAsyncResult ar)
- {
- var udpClient = ((UdpState)(ar.AsyncState)).UdpClient;
- var endpoint = ((UdpState)(ar.AsyncState)).EndPoint;
- if (udpClient.Client != null)
- {
- try
- {
- var responseBytes = udpClient.EndReceive(ar, ref endpoint);
- var args = SsdpHelper.ParseSsdpResponse(responseBytes);
-
- args.EndPoint = endpoint;
-
- OnMessageReceived(args, false);
-
- UnicastSetBeginReceive();
- }
- catch (ObjectDisposedException)
- {
-
- }
- catch (SocketException)
- {
-
- }
- catch (Exception)
- {
- // If called while shutting down, seeing a NullReferenceException inside EndReceive
- }
- }
- }
-
- private void SendUnicastRequest(string request, int sendCount = 3)
- {
- if (_unicastClient == null)
- {
- return;
- }
-
- var ipSsdp = IPAddress.Parse(SSDPAddr);
- var ipTxEnd = new IPEndPoint(ipSsdp, SSDPPort);
-
- SendUnicastRequest(request, ipTxEnd, sendCount);
- }
-
- private async void SendUnicastRequest(string request, IPEndPoint toEndPoint, int sendCount = 3)
- {
- if (_unicastClient == null)
- {
- return;
- }
-
- //_logger.Debug("Sending unicast request");
-
- byte[] req = Encoding.ASCII.GetBytes(request);
-
- try
- {
- for (var i = 0; i < sendCount; i++)
- {
- if (i > 0)
- {
- await Task.Delay(50).ConfigureAwait(false);
- }
- _unicastClient.Send(req, req.Length, toEndPoint);
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error in SendUnicastRequest", ex);
- }
- }
-
private readonly object _notificationTimerSyncLock = new object();
private int _aliveNotifierIntervalMs;
private void ReloadAliveNotifier()
diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
index ce00acb52..e8121d178 100644
--- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
@@ -487,7 +487,15 @@ namespace MediaBrowser.MediaEncoding.Encoder
var videoEncoder = EncodingJobFactory.GetVideoEncoder(MediaEncoder, state, encodingOptions);
if (videoEncoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
{
- arg = "-hwaccel vaapi -hwaccel_output_format vaapi -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
+ var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode;
+ var hwOutputFormat = "vaapi";
+
+ if (hasGraphicalSubs)
+ {
+ hwOutputFormat = "yuv420p";
+ }
+
+ arg = "-hwaccel vaapi -hwaccel_output_format " + hwOutputFormat + " -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
}
}
@@ -565,7 +573,20 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
outputSizeParam = await GetOutputSizeParam(state, outputVideoCodec).ConfigureAwait(false);
outputSizeParam = outputSizeParam.TrimEnd('"');
- outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
+
+ if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase));
+ }
+ else
+ {
+ outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
+ {
+ outputSizeParam = ",format=nv12|vaapi,hwupload";
}
var videoSizeParam = string.Empty;
@@ -595,23 +616,23 @@ namespace MediaBrowser.MediaEncoding.Encoder
/// Gets the video bitrate to specify on the command line
/// </summary>
/// <param name="state">The state.</param>
- /// <param name="videoCodec">The video codec.</param>
+ /// <param name="videoEncoder">The video codec.</param>
/// <returns>System.String.</returns>
- protected string GetVideoQualityParam(EncodingJob state, string videoCodec)
+ protected string GetVideoQualityParam(EncodingJob state, string videoEncoder)
{
var param = string.Empty;
var isVc1 = state.VideoStream != null &&
string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
- if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
{
param = "-preset superfast";
param += " -crf 23";
}
- else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
{
param = "-preset fast";
@@ -619,20 +640,20 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
// h264 (h264_qsv)
- else if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
{
param = "-preset 7 -look_ahead 0";
}
// h264 (h264_nvenc)
- else if (string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
{
param = "-preset llhq";
}
// webm
- else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase))
{
// Values 0-3, 0 being highest quality but slower
var profileScore = 0;
@@ -659,23 +680,23 @@ namespace MediaBrowser.MediaEncoding.Encoder
qmax);
}
- else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
{
param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
}
// asf/wmv
- else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase))
{
param = "-qmin 2";
}
- else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
+ else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{
param = "-mbd 2";
}
- param += GetVideoBitrateParam(state, videoCodec);
+ param += GetVideoBitrateParam(state, videoEncoder);
var framerate = GetFramerateParam(state);
if (framerate.HasValue)
@@ -690,8 +711,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (!string.IsNullOrEmpty(state.Options.Profile))
{
- if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
{
// not supported by h264_omx
param += " -profile:v " + state.Options.Profile;
@@ -702,9 +723,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
if (!string.IsNullOrEmpty(levelString))
{
+ levelString = NormalizeTranscodingLevel(state.OutputVideoCodec, levelString);
+
// h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
- if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
{
switch (levelString)
{
@@ -740,16 +763,16 @@ namespace MediaBrowser.MediaEncoding.Encoder
break;
}
}
- else if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase))
+ else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
{
param += " -level " + levelString;
}
}
- if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
- !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
+ if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
{
param = "-pix_fmt yuv420p " + param;
}
@@ -757,6 +780,25 @@ namespace MediaBrowser.MediaEncoding.Encoder
return param;
}
+ private string NormalizeTranscodingLevel(string videoCodec, string level)
+ {
+ double requestLevel;
+
+ // Clients may direct play higher than level 41, but there's no reason to transcode higher
+ if (double.TryParse(level, NumberStyles.Any, UsCulture, out requestLevel))
+ {
+ if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
+ {
+ if (requestLevel > 41)
+ {
+ return "41";
+ }
+ }
+ }
+
+ return level;
+ }
+
protected string GetVideoBitrateParam(EncodingJob state, string videoCodec)
{
var bitrate = state.OutputVideoBitrate;
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index a450097fd..24de4e77e 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -26,6 +26,30 @@ namespace MediaBrowser.MediaEncoding.Encoder
return new Tuple<List<string>, List<string>>(decoders, encoders);
}
+ public bool ValidateVersion(string encoderAppPath)
+ {
+ string output = string.Empty;
+ try
+ {
+ output = GetProcessOutput(encoderAppPath, "-version");
+ }
+ catch
+ {
+ }
+
+ if (string.IsNullOrWhiteSpace(output))
+ {
+ return false;
+ }
+
+ if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
private List<string> GetDecoders(string encoderAppPath)
{
string output = string.Empty;
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
index 490a51128..d3738d903 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
@@ -140,7 +140,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
try
{
- await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
+ await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
}
catch (Exception ex)
{
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index 75d85cd32..06867969e 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -82,6 +82,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
private readonly bool _hasExternalEncoder;
+ private string _originalFFMpegPath;
+ private string _originalFFProbePath;
public MediaEncoder(ILogger logger, IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, bool hasExternalEncoder, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILiveTvManager liveTvManager, IIsoManager isoManager, ILibraryManager libraryManager, IChannelManager channelManager, ISessionManager sessionManager, Func<ISubtitleEncoder> subtitleEncoder, Func<IMediaSourceManager> mediaSourceManager, IHttpClient httpClient, IZipClient zipClient)
{
@@ -100,6 +102,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
_zipClient = zipClient;
FFProbePath = ffProbePath;
FFMpegPath = ffMpegPath;
+ _originalFFProbePath = ffProbePath;
+ _originalFFMpegPath = ffMpegPath;
_hasExternalEncoder = hasExternalEncoder;
}
@@ -108,11 +112,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
get
{
- if (_hasExternalEncoder)
- {
- return "External";
- }
-
if (string.IsNullOrWhiteSpace(FFMpegPath))
{
return null;
@@ -177,12 +176,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
ConfigureEncoderPaths();
- if (_hasExternalEncoder)
- {
- LogPaths();
- return;
- }
-
// If the path was passed in, save it into config now.
var encodingOptions = GetEncodingOptions();
var appPath = encodingOptions.EncoderAppPath;
@@ -207,11 +200,6 @@ namespace MediaBrowser.MediaEncoding.Encoder
public async Task UpdateEncoderPath(string path, string pathType)
{
- if (_hasExternalEncoder)
- {
- return;
- }
-
Tuple<string, string> newPaths;
if (string.Equals(pathType, "system", StringComparison.OrdinalIgnoreCase))
@@ -247,6 +235,13 @@ namespace MediaBrowser.MediaEncoding.Encoder
throw new ResourceNotFoundException("ffprobe not found");
}
+ path = newPaths.Item1;
+
+ if (!ValidateVersion(path))
+ {
+ throw new ResourceNotFoundException("ffmpeg version 3.0 or greater is required.");
+ }
+
var config = GetEncodingOptions();
config.EncoderAppPath = path;
ConfigurationManager.SaveConfiguration("encoding", config);
@@ -254,13 +249,13 @@ namespace MediaBrowser.MediaEncoding.Encoder
Init();
}
- private void ConfigureEncoderPaths()
+ private bool ValidateVersion(string path)
{
- if (_hasExternalEncoder)
- {
- return;
- }
+ return new EncoderValidator(_logger).ValidateVersion(path);
+ }
+ private void ConfigureEncoderPaths()
+ {
var appPath = GetEncodingOptions().EncoderAppPath;
if (string.IsNullOrWhiteSpace(appPath))
@@ -308,45 +303,22 @@ namespace MediaBrowser.MediaEncoding.Encoder
string encoderPath = null;
string probePath = null;
- if (TestSystemInstalled("ffmpeg"))
- {
- encoderPath = "ffmpeg";
- }
- if (TestSystemInstalled("ffprobe"))
+ if (_hasExternalEncoder && ValidateVersion(_originalFFMpegPath))
{
- probePath = "ffprobe";
+ encoderPath = _originalFFMpegPath;
+ probePath = _originalFFProbePath;
}
- return new Tuple<string, string>(encoderPath, probePath);
- }
-
- private bool TestSystemInstalled(string app)
- {
- try
+ if (string.IsNullOrWhiteSpace(encoderPath))
{
- var startInfo = new ProcessStartInfo
- {
- FileName = app,
- Arguments = "-v",
- UseShellExecute = false,
- CreateNoWindow = true,
- WindowStyle = ProcessWindowStyle.Hidden,
- ErrorDialog = false
- };
-
- using (var process = Process.Start(startInfo))
+ if (ValidateVersion("ffmpeg") && ValidateVersion("ffprobe"))
{
- process.WaitForExit();
+ encoderPath = "ffmpeg";
+ probePath = "ffprobe";
}
-
- _logger.Debug("System app installed: " + app);
- return true;
- }
- catch
- {
- _logger.Debug("System app not installed: " + app);
- return false;
}
+
+ return new Tuple<string, string>(encoderPath, probePath);
}
private Tuple<string, string> GetPathsFromDirectory(string path)
@@ -799,20 +771,20 @@ namespace MediaBrowser.MediaEncoding.Encoder
public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken)
{
- return ExtractImage(new[] { path }, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken);
+ return ExtractImage(new[] { path }, null, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken);
}
- public Task<string> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
+ public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
{
- return ExtractImage(inputFiles, null, protocol, false, threedFormat, offset, cancellationToken);
+ return ExtractImage(inputFiles, container, null, protocol, false, threedFormat, offset, cancellationToken);
}
- public Task<string> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, int? imageStreamIndex, CancellationToken cancellationToken)
+ public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, int? imageStreamIndex, CancellationToken cancellationToken)
{
- return ExtractImage(inputFiles, imageStreamIndex, protocol, false, null, null, cancellationToken);
+ return ExtractImage(inputFiles, container, imageStreamIndex, protocol, false, null, null, cancellationToken);
}
- private async Task<string> ExtractImage(string[] inputFiles, int? imageStreamIndex, MediaProtocol protocol, bool isAudio,
+ private async Task<string> ExtractImage(string[] inputFiles, string container, int? imageStreamIndex, MediaProtocol protocol, bool isAudio,
Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
{
var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
@@ -831,7 +803,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
try
{
- return await ExtractImageInternal(inputArgument, imageStreamIndex, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
+ return await ExtractImageInternal(inputArgument, container, imageStreamIndex, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
}
catch (ArgumentException)
{
@@ -843,10 +815,10 @@ namespace MediaBrowser.MediaEncoding.Encoder
}
}
- return await ExtractImageInternal(inputArgument, imageStreamIndex, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
+ return await ExtractImageInternal(inputArgument, container, imageStreamIndex, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
}
- private async Task<string> ExtractImageInternal(string inputPath, int? imageStreamIndex, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
+ private async Task<string> ExtractImageInternal(string inputPath, string container, int? imageStreamIndex, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(inputPath))
{
@@ -887,8 +859,11 @@ namespace MediaBrowser.MediaEncoding.Encoder
var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
+ var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ var thumbnail = enableThumbnail ? ",thumbnail=30" : string.Empty;
+
// Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
- var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg) :
+ var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) :
string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);
var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);
@@ -931,8 +906,9 @@ namespace MediaBrowser.MediaEncoding.Encoder
var timeoutMs = ConfigurationManager.Configuration.ImageExtractionTimeoutMs;
if (timeoutMs <= 0)
{
- timeoutMs = 10000;
+ timeoutMs = Environment.Is64BitOperatingSystem ? (Environment.ProcessorCount > 2 ? 14000 : 20000) : 40000;
}
+
ranToCompletion = process.WaitForExit(timeoutMs);
if (!ranToCompletion)
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 700af682b..5805127e6 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -393,6 +393,20 @@ namespace MediaBrowser.MediaEncoding.Probing
};
}
+ private string NormalizeSubtitleCodec(string codec)
+ {
+ if ((codec ?? string.Empty).IndexOf("PGS", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ codec = "PGSSUB";
+ }
+ else if ((codec ?? string.Empty).IndexOf("DVD", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ codec = "DVDSUB";
+ }
+
+ return codec;
+ }
+
/// <summary>
/// Converts ffprobe stream info to our MediaStream class
/// </summary>
@@ -474,6 +488,7 @@ namespace MediaBrowser.MediaEncoding.Probing
else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
{
stream.Type = MediaStreamType.Subtitle;
+ stream.Codec = NormalizeSubtitleCodec(stream.Codec);
}
else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
{
diff --git a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj
index 351740e6e..ad7dea0a5 100644
--- a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj
+++ b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj
@@ -175,9 +175,6 @@
<Compile Include="..\MediaBrowser.Model\Configuration\AccessSchedule.cs">
<Link>Configuration\AccessSchedule.cs</Link>
</Compile>
- <Compile Include="..\MediaBrowser.Model\Configuration\AutoOnOff.cs">
- <Link>Configuration\AutoOnOff.cs</Link>
- </Compile>
<Compile Include="..\MediaBrowser.Model\Configuration\BaseApplicationConfiguration.cs">
<Link>Configuration\BaseApplicationConfiguration.cs</Link>
</Compile>
diff --git a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj
index ad3811646..61f2f3f13 100644
--- a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj
+++ b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj
@@ -147,9 +147,6 @@
<Compile Include="..\MediaBrowser.Model\Configuration\AccessSchedule.cs">
<Link>Configuration\AccessSchedule.cs</Link>
</Compile>
- <Compile Include="..\MediaBrowser.Model\Configuration\AutoOnOff.cs">
- <Link>Configuration\AutoOnOff.cs</Link>
- </Compile>
<Compile Include="..\MediaBrowser.Model\Configuration\BaseApplicationConfiguration.cs">
<Link>Configuration\BaseApplicationConfiguration.cs</Link>
</Compile>
@@ -1193,4 +1190,4 @@
<Target Name="AfterBuild">
</Target>
-->
-</Project>
+</Project> \ No newline at end of file
diff --git a/MediaBrowser.Model/Configuration/AutoOnOff.cs b/MediaBrowser.Model/Configuration/AutoOnOff.cs
deleted file mode 100644
index e911a0ff1..000000000
--- a/MediaBrowser.Model/Configuration/AutoOnOff.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-
-namespace MediaBrowser.Model.Configuration
-{
- public enum AutoOnOff
- {
- Auto,
- Enabled,
- Disabled
- }
-}
diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs
index d49816803..9a0b2d35b 100644
--- a/MediaBrowser.Model/Configuration/EncodingOptions.cs
+++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs
@@ -22,7 +22,6 @@ namespace MediaBrowser.Model.Configuration
EncodingThreadCount = -1;
VaapiDevice = "/dev/dri/card0";
H264Crf = 23;
- H264Preset = "superfast";
}
}
}
diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs
index 551363223..460ee0918 100644
--- a/MediaBrowser.Model/Configuration/LibraryOptions.cs
+++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs
@@ -8,11 +8,20 @@
public int SchemaVersion { get; set; }
public bool EnableChapterImageExtraction { get; set; }
public bool ExtractChapterImagesDuringLibraryScan { get; set; }
+ public bool DownloadImagesInAdvance { get; set; }
+ public MediaPathInfo[] PathInfos { get; set; }
public LibraryOptions()
{
EnablePhotos = true;
EnableRealtimeMonitor = true;
+ PathInfos = new MediaPathInfo[] { };
}
}
+
+ public class MediaPathInfo
+ {
+ public string Path { get; set; }
+ public string NetworkPath { get; set; }
+ }
}
diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
index 44a2ae954..1d2928f67 100644
--- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
@@ -73,6 +73,7 @@ namespace MediaBrowser.Model.Configuration
/// </summary>
/// <value>The metadata path.</value>
public string MetadataPath { get; set; }
+ public string MetadataNetworkPath { get; set; }
public string LastVersion { get; set; }
@@ -183,8 +184,6 @@ namespace MediaBrowser.Model.Configuration
public int RemoteClientBitrateLimit { get; set; }
- public AutoOnOff EnableLibraryMonitor { get; set; }
-
public int SharingExpirationDays { get; set; }
public string[] Migrations { get; set; }
@@ -193,8 +192,6 @@ namespace MediaBrowser.Model.Configuration
public int SchemaVersion { get; set; }
public int SqliteCacheSize { get; set; }
- public bool DownloadImagesInAdvance { get; set; }
-
public bool EnableAnonymousUsageReporting { get; set; }
public bool EnableStandaloneMusicKeys { get; set; }
public bool EnableLocalizedGuids { get; set; }
@@ -217,7 +214,7 @@ namespace MediaBrowser.Model.Configuration
Migrations = new string[] { };
CodecsUsed = new string[] { };
SqliteCacheSize = 0;
- ImageExtractionTimeoutMs = 10000;
+ ImageExtractionTimeoutMs = 0;
EnableLocalizedGuids = true;
DisplaySpecialsWithinSeasons = true;
@@ -234,6 +231,7 @@ namespace MediaBrowser.Model.Configuration
EnableAnonymousUsageReporting = true;
EnableAutomaticRestart = true;
+ EnableFolderView = true;
EnableUPnP = true;
SharingExpirationDays = 30;
@@ -243,7 +241,6 @@ namespace MediaBrowser.Model.Configuration
// 5 minutes
MinResumeDurationSeconds = 300;
- EnableLibraryMonitor = AutoOnOff.Auto;
LibraryMonitorDelay = 60;
EnableInternetProviders = true;
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index 13d559773..30d1498bf 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -602,33 +602,20 @@ namespace MediaBrowser.Model.Dlna
private int GetAudioBitrate(string subProtocol, int? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream)
{
- var defaultBitrate = audioStream == null ? 192000 : audioStream.BitRate ?? 192000;
+ int defaultBitrate = audioStream == null ? 192000 : audioStream.BitRate ?? 192000;
// Reduce the bitrate if we're downmixing
if (targetAudioChannels.HasValue && audioStream != null && audioStream.Channels.HasValue && targetAudioChannels.Value < audioStream.Channels.Value)
{
defaultBitrate = StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3") ? 192000 : 128000;
}
- if (targetAudioChannels.HasValue)
+ if (StringHelper.EqualsIgnoreCase(subProtocol, "hls"))
{
- if (targetAudioChannels.Value >= 5 && (maxTotalBitrate ?? 0) >= 1200000)
- {
- if (StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3"))
- {
- if (string.Equals(subProtocol, "hls", StringComparison.OrdinalIgnoreCase))
- {
- defaultBitrate = Math.Max(384000, defaultBitrate);
- }
- else
- {
- defaultBitrate = Math.Max(448000, defaultBitrate);
- }
- }
- else
- {
- defaultBitrate = Math.Max(320000, defaultBitrate);
- }
- }
+ defaultBitrate = Math.Min(384000, defaultBitrate);
+ }
+ else
+ {
+ defaultBitrate = Math.Min(448000, defaultBitrate);
}
int encoderAudioBitrateLimit = int.MaxValue;
@@ -647,6 +634,14 @@ namespace MediaBrowser.Model.Dlna
}
}
+ if (maxTotalBitrate.HasValue)
+ {
+ if (maxTotalBitrate.Value < 640000)
+ {
+ defaultBitrate = Math.Min(128000, defaultBitrate);
+ }
+ }
+
return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
}
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index ac024f00b..f7dc893c8 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -215,13 +215,26 @@ namespace MediaBrowser.Model.Dlna
list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxWidth.Value) : string.Empty));
list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxHeight.Value) : string.Empty));
- if (StringHelper.EqualsIgnoreCase(item.SubProtocol, "hls"))
+ var forceStartPosition = false;
+ long startPositionTicks = item.StartPositionTicks;
+ //if (item.MediaSource.DateLiveStreamOpened.HasValue && startPositionTicks == 0)
+ //{
+ // var elapsed = DateTime.UtcNow - item.MediaSource.DateLiveStreamOpened.Value;
+ // elapsed -= TimeSpan.FromSeconds(20);
+ // if (elapsed.TotalSeconds >= 0)
+ // {
+ // startPositionTicks = elapsed.Ticks + startPositionTicks;
+ // forceStartPosition = true;
+ // }
+ //}
+
+ if (StringHelper.EqualsIgnoreCase(item.SubProtocol, "hls") && !forceStartPosition)
{
list.Add(new NameValuePair("StartTimeTicks", string.Empty));
}
else
{
- list.Add(new NameValuePair("StartTimeTicks", StringHelper.ToStringCultureInvariant(item.StartPositionTicks)));
+ list.Add(new NameValuePair("StartTimeTicks", StringHelper.ToStringCultureInvariant(startPositionTicks)));
}
list.Add(new NameValuePair("Level", item.VideoLevel.HasValue ? StringHelper.ToStringCultureInvariant(item.VideoLevel.Value) : string.Empty));
diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs
index 348a781ae..9434ab03a 100644
--- a/MediaBrowser.Model/Dto/BaseItemDto.cs
+++ b/MediaBrowser.Model/Dto/BaseItemDto.cs
@@ -826,6 +826,7 @@ namespace MediaBrowser.Model.Dto
/// </summary>
/// <value>The series count.</value>
public int? SeriesCount { get; set; }
+ public int? ProgramCount { get; set; }
/// <summary>
/// Gets or sets the episode count.
/// </summary>
diff --git a/MediaBrowser.Model/Dto/ItemCounts.cs b/MediaBrowser.Model/Dto/ItemCounts.cs
index 66c3dfebc..8ceb3a86b 100644
--- a/MediaBrowser.Model/Dto/ItemCounts.cs
+++ b/MediaBrowser.Model/Dto/ItemCounts.cs
@@ -26,6 +26,7 @@
/// <value>The game count.</value>
public int GameCount { get; set; }
public int ArtistCount { get; set; }
+ public int ProgramCount { get; set; }
/// <summary>
/// Gets or sets the game system count.
/// </summary>
diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
index bb07d9cb6..1c7875890 100644
--- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
@@ -1,4 +1,5 @@
-using MediaBrowser.Model.Entities;
+using System;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.MediaInfo;
using System.Collections.Generic;
@@ -26,7 +27,7 @@ namespace MediaBrowser.Model.Dto
public bool SupportsTranscoding { get; set; }
public bool SupportsDirectStream { get; set; }
public bool SupportsDirectPlay { get; set; }
-
+ public bool IsInfiniteStream { get; set; }
public bool RequiresOpening { get; set; }
public string OpenToken { get; set; }
public bool RequiresClosing { get; set; }
@@ -52,7 +53,9 @@ namespace MediaBrowser.Model.Dto
public string TranscodingUrl { get; set; }
public string TranscodingSubProtocol { get; set; }
public string TranscodingContainer { get; set; }
-
+
+ public DateTime? DateLiveStreamOpened { get; set; }
+
public MediaSourceInfo()
{
Formats = new List<string>();
diff --git a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
index 4d863c6eb..0ceed70c0 100644
--- a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs
@@ -105,5 +105,6 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value><c>true</c> if this instance is post padding required; otherwise, <c>false</c>.</value>
public bool IsPostPaddingRequired { get; set; }
+ public KeepUntil KeepUntil { get; set; }
}
} \ No newline at end of file
diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
index 0ece1e4a0..4505b80a0 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
@@ -1,4 +1,5 @@
-
+using MediaBrowser.Model.Entities;
+
namespace MediaBrowser.Model.LiveTv
{
/// <summary>
@@ -61,9 +62,42 @@ namespace MediaBrowser.Model.LiveTv
public bool AddCurrentProgram { get; set; }
public bool EnableUserData { get; set; }
+ /// <summary>
+ /// Used to specific whether to return news or not
+ /// </summary>
+ /// <remarks>If set to null, all programs will be returned</remarks>
+ public bool? IsNews { get; set; }
+
+ /// <summary>
+ /// Used to specific whether to return movies or not
+ /// </summary>
+ /// <remarks>If set to null, all programs will be returned</remarks>
+ public bool? IsMovie { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is kids.
+ /// </summary>
+ /// <value><c>null</c> if [is kids] contains no value, <c>true</c> if [is kids]; otherwise, <c>false</c>.</value>
+ public bool? IsKids { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is sports.
+ /// </summary>
+ /// <value><c>null</c> if [is sports] contains no value, <c>true</c> if [is sports]; otherwise, <c>false</c>.</value>
+ public bool? IsSports { get; set; }
+ public bool? IsSeries { get; set; }
+
+ public string[] SortBy { get; set; }
+
+ /// <summary>
+ /// The sort order to return results with
+ /// </summary>
+ /// <value>The sort order.</value>
+ public SortOrder? SortOrder { get; set; }
+
public LiveTvChannelQuery()
{
EnableUserData = true;
+ SortBy = new string[] { };
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
index 242a2d24e..a6240afe6 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs
@@ -13,6 +13,7 @@ namespace MediaBrowser.Model.LiveTv
public string SeriesRecordingPath { get; set; }
public bool EnableAutoOrganize { get; set; }
public bool EnableRecordingEncoding { get; set; }
+ public string RecordingEncodingFormat { get; set; }
public bool EnableRecordingSubfolders { get; set; }
public bool EnableOriginalAudioWithEncodedRecordings { get; set; }
@@ -31,6 +32,7 @@ namespace MediaBrowser.Model.LiveTv
TunerHosts = new List<TunerHostInfo>();
ListingProviders = new List<ListingsProviderInfo>();
MediaLocationsCreated = new string[] { };
+ RecordingEncodingFormat = "mp4";
}
}
@@ -58,7 +60,6 @@ namespace MediaBrowser.Model.LiveTv
public TunerHostInfo()
{
IsEnabled = true;
- AllowHWTranscoding = true;
}
}
diff --git a/MediaBrowser.Model/LiveTv/ProgramAudio.cs b/MediaBrowser.Model/LiveTv/ProgramAudio.cs
index 902079b9a..9a272492c 100644
--- a/MediaBrowser.Model/LiveTv/ProgramAudio.cs
+++ b/MediaBrowser.Model/LiveTv/ProgramAudio.cs
@@ -6,6 +6,7 @@
Stereo,
Dolby,
DolbyDigital,
- Thx
+ Thx,
+ Atmos
}
} \ No newline at end of file
diff --git a/MediaBrowser.Model/LiveTv/ProgramQuery.cs b/MediaBrowser.Model/LiveTv/ProgramQuery.cs
index bf459237a..ad57d1473 100644
--- a/MediaBrowser.Model/LiveTv/ProgramQuery.cs
+++ b/MediaBrowser.Model/LiveTv/ProgramQuery.cs
@@ -41,6 +41,7 @@ namespace MediaBrowser.Model.LiveTv
/// </summary>
/// <value>The user identifier.</value>
public string UserId { get; set; }
+ public string SeriesTimerId { get; set; }
/// <summary>
/// The earliest date for which a program starts to return
@@ -63,6 +64,12 @@ namespace MediaBrowser.Model.LiveTv
public DateTime? MaxEndDate { get; set; }
/// <summary>
+ /// Used to specific whether to return news or not
+ /// </summary>
+ /// <remarks>If set to null, all programs will be returned</remarks>
+ public bool? IsNews { get; set; }
+
+ /// <summary>
/// Used to specific whether to return movies or not
/// </summary>
/// <remarks>If set to null, all programs will be returned</remarks>
@@ -83,6 +90,7 @@ namespace MediaBrowser.Model.LiveTv
/// Skips over a given number of items within the results. Use for paging.
/// </summary>
public int? StartIndex { get; set; }
+ public bool? IsSeries { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance has aired.
diff --git a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs b/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs
index 0e6d081a1..4bc506bf6 100644
--- a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs
+++ b/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs
@@ -49,7 +49,13 @@ namespace MediaBrowser.Model.LiveTv
/// Gets or sets a value indicating whether this instance is movie.
/// </summary>
/// <value><c>null</c> if [is movie] contains no value, <c>true</c> if [is movie]; otherwise, <c>false</c>.</value>
+ public bool? IsNews { get; set; }
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is movie.
+ /// </summary>
+ /// <value><c>null</c> if [is movie] contains no value, <c>true</c> if [is movie]; otherwise, <c>false</c>.</value>
public bool? IsMovie { get; set; }
+ public bool? IsSeries { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is kids.
/// </summary>
diff --git a/MediaBrowser.Model/LiveTv/RecordingQuery.cs b/MediaBrowser.Model/LiveTv/RecordingQuery.cs
index 923d303f8..265aad335 100644
--- a/MediaBrowser.Model/LiveTv/RecordingQuery.cs
+++ b/MediaBrowser.Model/LiveTv/RecordingQuery.cs
@@ -68,6 +68,11 @@ namespace MediaBrowser.Model.LiveTv
/// <value>The fields.</value>
public ItemFields[] Fields { get; set; }
public bool? EnableImages { get; set; }
+ public bool? IsNews { get; set; }
+ public bool? IsMovie { get; set; }
+ public bool? IsSeries { get; set; }
+ public bool? IsKids { get; set; }
+ public bool? IsSports { get; set; }
public int? ImageTypeLimit { get; set; }
public ImageType[] EnableImageTypes { get; set; }
diff --git a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
index 4b88e42f3..ce65cc7bf 100644
--- a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
+++ b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs
@@ -18,12 +18,16 @@ namespace MediaBrowser.Model.LiveTv
/// <value><c>true</c> if [record any time]; otherwise, <c>false</c>.</value>
public bool RecordAnyTime { get; set; }
+ public bool SkipEpisodesInLibrary { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [record any channel].
/// </summary>
/// <value><c>true</c> if [record any channel]; otherwise, <c>false</c>.</value>
public bool RecordAnyChannel { get; set; }
+ public int KeepUpTo { get; set; }
+
/// <summary>
/// Gets or sets a value indicating whether [record new only].
/// </summary>
@@ -64,4 +68,12 @@ namespace MediaBrowser.Model.LiveTv
Days = new List<DayOfWeek>();
}
}
+
+ public enum KeepUntil
+ {
+ UntilDeleted,
+ UntilSpaceNeeded,
+ UntilWatched,
+ UntilDate
+ }
}
diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj
index db70b8606..c1a01680d 100644
--- a/MediaBrowser.Model/MediaBrowser.Model.csproj
+++ b/MediaBrowser.Model/MediaBrowser.Model.csproj
@@ -89,7 +89,6 @@
<Compile Include="Chapters\RemoteChapterResult.cs" />
<Compile Include="Collections\CollectionCreationResult.cs" />
<Compile Include="Configuration\AccessSchedule.cs" />
- <Compile Include="Configuration\AutoOnOff.cs" />
<Compile Include="Configuration\ChannelOptions.cs" />
<Compile Include="Configuration\ChapterOptions.cs" />
<Compile Include="Configuration\CinemaModeConfiguration.cs" />
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index 3d1de5b37..c4d056a61 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -8,6 +8,8 @@ namespace MediaBrowser.Model.System
/// </summary>
public class SystemInfo : PublicSystemInfo
{
+ public PackageVersionClass SystemUpdateLevel { get; set; }
+
/// <summary>
/// Gets or sets the display name of the operating system.
/// </summary>
diff --git a/MediaBrowser.Mono.sln b/MediaBrowser.Mono.sln
index 3d9677fa8..6300a9559 100644
--- a/MediaBrowser.Mono.sln
+++ b/MediaBrowser.Mono.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2013
-VisualStudioVersion = 12.0.30723.0
+# Visual Studio 14
+VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Model", "MediaBrowser.Model\MediaBrowser.Model.csproj", "{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}"
EndProject
@@ -35,6 +35,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Server.Startup
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Nat", "Mono.Nat\Mono.Nat.csproj", "{D7453B88-2266-4805-B39B-2B5A2A33E1BA}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -203,6 +205,18 @@ Global
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.ActiveCfg = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.Build.0 = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x86.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Any CPU.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x86.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
index cdaa38366..2f534c12e 100644
--- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
+++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using CommonIO;
+using MediaBrowser.Controller.Collections;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
@@ -21,4 +22,17 @@ namespace MediaBrowser.Providers.Folders
{
}
}
+
+ public class ManualCollectionsFolderMetadataService : MetadataService<ManualCollectionsFolder, ItemLookupInfo>
+ {
+ protected override void MergeData(MetadataResult<ManualCollectionsFolder> source, MetadataResult<ManualCollectionsFolder> target, List<MetadataFields> lockedFields, bool replaceData, bool mergeMetadataSettings)
+ {
+ ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings);
+ }
+
+ public ManualCollectionsFolderMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager)
+ {
+ }
+ }
+
}
diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
index 97dd1ed4c..1d8ba85f8 100644
--- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs
+++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
@@ -56,7 +56,7 @@ namespace MediaBrowser.Providers.Manager
return hasChanges;
}
- public async Task<RefreshResult> RefreshImages(IHasImages item, IEnumerable<IImageProvider> imageProviders, ImageRefreshOptions refreshOptions, MetadataOptions savedOptions, CancellationToken cancellationToken)
+ public async Task<RefreshResult> RefreshImages(IHasImages item, LibraryOptions libraryOptions, IEnumerable<IImageProvider> imageProviders, ImageRefreshOptions refreshOptions, MetadataOptions savedOptions, CancellationToken cancellationToken)
{
if (refreshOptions.IsReplacingImage(ImageType.Backdrop))
{
@@ -84,7 +84,7 @@ namespace MediaBrowser.Providers.Manager
if (remoteProvider != null)
{
- await RefreshFromProvider(item, remoteProvider, refreshOptions, savedOptions, backdropLimit, screenshotLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false);
+ await RefreshFromProvider(item, libraryOptions, remoteProvider, refreshOptions, savedOptions, backdropLimit, screenshotLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false);
providerIds.Add(provider.GetType().FullName.GetMD5());
continue;
}
@@ -249,7 +249,7 @@ namespace MediaBrowser.Providers.Manager
/// <param name="result">The result.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
- private async Task RefreshFromProvider(IHasImages item,
+ private async Task RefreshFromProvider(IHasImages item, LibraryOptions libraryOptions,
IRemoteImageProvider provider,
ImageRefreshOptions refreshOptions,
MetadataOptions savedOptions,
@@ -293,7 +293,7 @@ namespace MediaBrowser.Providers.Manager
if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
{
minWidth = savedOptions.GetMinWidth(imageType);
- var downloaded = await DownloadImage(item, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);
+ var downloaded = await DownloadImage(item, libraryOptions, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);
if (downloaded)
{
@@ -305,7 +305,7 @@ namespace MediaBrowser.Providers.Manager
if (!item.LockedFields.Contains(MetadataFields.Backdrops))
{
minWidth = savedOptions.GetMinWidth(ImageType.Backdrop);
- await DownloadBackdrops(item, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
+ await DownloadBackdrops(item, libraryOptions, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
}
if (!item.LockedFields.Contains(MetadataFields.Screenshots))
@@ -314,7 +314,7 @@ namespace MediaBrowser.Providers.Manager
if (hasScreenshots != null)
{
minWidth = savedOptions.GetMinWidth(ImageType.Screenshot);
- await DownloadBackdrops(item, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
+ await DownloadBackdrops(item, libraryOptions, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -472,7 +472,7 @@ namespace MediaBrowser.Providers.Manager
return changed;
}
- private async Task<bool> DownloadImage(IHasImages item,
+ private async Task<bool> DownloadImage(IHasImages item, LibraryOptions libraryOptions,
IRemoteImageProvider provider,
RefreshResult result,
IEnumerable<RemoteImageInfo> images,
@@ -484,7 +484,7 @@ namespace MediaBrowser.Providers.Manager
.Where(i => i.Type == type && !(i.Width.HasValue && i.Width.Value < minWidth))
.ToList();
- if (EnableImageStub(item, type) && eligibleImages.Count > 0)
+ if (EnableImageStub(item, type, libraryOptions) && eligibleImages.Count > 0)
{
SaveImageStub(item, type, eligibleImages.Select(i => i.Url));
result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
@@ -518,14 +518,14 @@ namespace MediaBrowser.Providers.Manager
return false;
}
- private bool EnableImageStub(IHasImages item, ImageType type)
+ private bool EnableImageStub(IHasImages item, ImageType type, LibraryOptions libraryOptions)
{
if (item is LiveTvProgram)
{
return true;
}
- if (_config.Configuration.DownloadImagesInAdvance)
+ if (libraryOptions.DownloadImagesInAdvance)
{
return false;
}
@@ -585,7 +585,7 @@ namespace MediaBrowser.Providers.Manager
}, newIndex);
}
- private async Task DownloadBackdrops(IHasImages item, ImageType imageType, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken)
+ private async Task DownloadBackdrops(IHasImages item, LibraryOptions libraryOptions, ImageType imageType, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken)
{
foreach (var image in images.Where(i => i.Type == imageType))
{
@@ -601,7 +601,7 @@ namespace MediaBrowser.Providers.Manager
var url = image.Url;
- if (EnableImageStub(item, imageType))
+ if (EnableImageStub(item, imageType, libraryOptions))
{
SaveImageStub(item, imageType, new[] { url });
result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index a610df427..9bbba73e0 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -11,6 +11,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
+using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Providers;
namespace MediaBrowser.Providers.Manager
@@ -120,6 +121,8 @@ namespace MediaBrowser.Providers.Manager
}
}
+ LibraryOptions libraryOptions = null;
+
// Next run remote image providers, but only if local image providers didn't throw an exception
if (!localImagesFailed && refreshOptions.ImageRefreshMode != ImageRefreshMode.ValidationOnly)
{
@@ -127,7 +130,12 @@ namespace MediaBrowser.Providers.Manager
if (providers.Count > 0)
{
- var result = await itemImageProvider.RefreshImages(itemOfType, providers, refreshOptions, config, cancellationToken).ConfigureAwait(false);
+ if (libraryOptions == null)
+ {
+ libraryOptions = LibraryManager.GetLibraryOptions((BaseItem)item);
+ }
+
+ var result = await itemImageProvider.RefreshImages(itemOfType, libraryOptions, providers, refreshOptions, config, cancellationToken).ConfigureAwait(false);
updateType = updateType | result.UpdateType;
if (result.Failures == 0)
@@ -180,8 +188,13 @@ namespace MediaBrowser.Providers.Manager
item.DateLastRefreshed = default(DateTime);
}
+ if (libraryOptions == null)
+ {
+ libraryOptions = LibraryManager.GetLibraryOptions((BaseItem)item);
+ }
+
// Save to database
- await SaveItem(metadataResult, updateType, cancellationToken).ConfigureAwait(false);
+ await SaveItem(metadataResult, libraryOptions, updateType, cancellationToken).ConfigureAwait(false);
}
await AfterMetadataRefresh(itemOfType, refreshOptions, cancellationToken).ConfigureAwait(false);
@@ -196,17 +209,19 @@ namespace MediaBrowser.Providers.Manager
lookupInfo.Year = result.ProductionYear;
}
- protected async Task SaveItem(MetadataResult<TItemType> result, ItemUpdateType reason, CancellationToken cancellationToken)
+ protected async Task SaveItem(MetadataResult<TItemType> result, LibraryOptions libraryOptions, ItemUpdateType reason, CancellationToken cancellationToken)
{
if (result.Item.SupportsPeople && result.People != null)
{
- await LibraryManager.UpdatePeople(result.Item as BaseItem, result.People.ToList());
- await SavePeopleMetadata(result.People, cancellationToken).ConfigureAwait(false);
+ var baseItem = result.Item as BaseItem;
+
+ await LibraryManager.UpdatePeople(baseItem, result.People.ToList());
+ await SavePeopleMetadata(result.People, libraryOptions, cancellationToken).ConfigureAwait(false);
}
await result.Item.UpdateToRepository(reason, cancellationToken).ConfigureAwait(false);
}
- private async Task SavePeopleMetadata(List<PersonInfo> people, CancellationToken cancellationToken)
+ private async Task SavePeopleMetadata(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken)
{
foreach (var person in people)
{
@@ -229,7 +244,7 @@ namespace MediaBrowser.Providers.Manager
if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
{
- await AddPersonImage(personEntity, person.ImageUrl, cancellationToken).ConfigureAwait(false);
+ await AddPersonImage(personEntity, libraryOptions, person.ImageUrl, cancellationToken).ConfigureAwait(false);
saveEntity = true;
updateType = updateType | ItemUpdateType.ImageUpdate;
@@ -243,9 +258,9 @@ namespace MediaBrowser.Providers.Manager
}
}
- private async Task AddPersonImage(Person personEntity, string imageUrl, CancellationToken cancellationToken)
+ private async Task AddPersonImage(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken)
{
- if (ServerConfigurationManager.Configuration.DownloadImagesInAdvance)
+ if (libraryOptions.DownloadImagesInAdvance)
{
try
{
@@ -301,6 +316,13 @@ namespace MediaBrowser.Providers.Manager
updateType |= ItemUpdateType.MetadataImport;
}
+ var inheritedTags = item.GetInheritedTags();
+ if (!inheritedTags.SequenceEqual(item.InheritedTags, StringComparer.Ordinal))
+ {
+ item.InheritedTags = inheritedTags;
+ updateType |= ItemUpdateType.MetadataImport;
+ }
+
return updateType;
}
@@ -532,8 +554,6 @@ namespace MediaBrowser.Providers.Manager
}
catch (Exception ex)
{
- refreshResult.Failures++;
-
Logger.ErrorException("Error in {0}", ex, provider.Name);
// If a local provider fails, consider that a failure
@@ -631,6 +651,8 @@ namespace MediaBrowser.Providers.Manager
{
var refreshResult = new RefreshResult();
+ var results = new List<MetadataResult<TItemType>>();
+
foreach (var provider in providers)
{
var providerName = provider.GetType().Name;
@@ -647,7 +669,7 @@ namespace MediaBrowser.Providers.Manager
if (result.HasMetadata)
{
- MergeData(result, temp, new List<MetadataFields>(), false, false);
+ results.Add(result);
refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataDownload;
}
@@ -668,9 +690,49 @@ namespace MediaBrowser.Providers.Manager
}
}
+ var orderedResults = new List<MetadataResult<TItemType>>();
+ var preferredLanguage = NormalizeLanguage(id.MetadataLanguage);
+
+ // prioritize results with matching ResultLanguage
+ foreach (var result in results)
+ {
+ if (!result.QueriedById)
+ {
+ break;
+ }
+
+ if (string.Equals(NormalizeLanguage(result.ResultLanguage), preferredLanguage, StringComparison.OrdinalIgnoreCase) && result.QueriedById)
+ {
+ orderedResults.Add(result);
+ }
+ }
+
+ // add all other results
+ foreach (var result in results)
+ {
+ if (!orderedResults.Contains(result))
+ {
+ orderedResults.Add(result);
+ }
+ }
+
+ foreach (var result in results)
+ {
+ MergeData(result, temp, new List<MetadataFields>(), false, false);
+ }
+
return refreshResult;
}
+ private string NormalizeLanguage(string language)
+ {
+ if (string.IsNullOrWhiteSpace(language))
+ {
+ return "en";
+ }
+ return language;
+ }
+
private void MergeNewData(TItemType source, TIdType lookupInfo)
{
// Copy new provider id's that may have been obtained
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
index f64b7b792..024171f40 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs
@@ -117,7 +117,7 @@ namespace MediaBrowser.Providers.MediaInfo
{
get
{
- return new[] { ".srt", ".ssa", ".ass", ".sub" };
+ return new[] { ".srt", ".ssa", ".ass", ".sub", ".smi", ".sami" };
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
index 2ad02da2e..6a934240a 100644
--- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs
@@ -134,7 +134,7 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, protocol, videoIndex, cancellationToken).ConfigureAwait(false);
+ extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, videoIndex, cancellationToken).ConfigureAwait(false);
}
else
{
@@ -145,7 +145,7 @@ namespace MediaBrowser.Providers.MediaInfo
? TimeSpan.FromTicks(Convert.ToInt64(item.RunTimeTicks.Value * .1))
: TimeSpan.FromSeconds(10);
- extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, protocol, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
+ extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false);
}
return new DynamicImageResponse
diff --git a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs b/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs
index 18f177932..2a40e4d85 100644
--- a/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs
+++ b/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs
@@ -20,6 +20,7 @@ using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
+using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Providers.TV;
namespace MediaBrowser.Providers.Movies
@@ -59,30 +60,13 @@ namespace MediaBrowser.Providers.Movies
public bool Supports(IHasImages item)
{
- //var channelItem = item as IChannelMediaItem;
-
- //if (channelItem != null)
- //{
- // if (channelItem.ContentType == ChannelMediaContentType.Movie)
- // {
- // return true;
- // }
- // if (channelItem.ContentType == ChannelMediaContentType.MovieExtra)
- // {
- // if (channelItem.ExtraType == ExtraType.Trailer)
- // {
- // return true;
- // }
- // }
- //}
-
// Supports images for tv movies
- //var tvProgram = item as LiveTvProgram;
- //if (tvProgram != null && tvProgram.IsMovie)
- //{
- // return true;
- //}
-
+ var tvProgram = item as LiveTvProgram;
+ if (tvProgram != null && tvProgram.IsMovie)
+ {
+ return true;
+ }
+
return item is Movie || item is BoxSet || item is MusicVideo;
}
diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
index 1bf4ed6c0..41a061467 100644
--- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
+++ b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs
@@ -14,6 +14,7 @@ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
+using MediaBrowser.Model.Extensions;
namespace MediaBrowser.Providers.Movies
{
@@ -125,11 +126,7 @@ namespace MediaBrowser.Providers.Movies
movie.Name = movieData.GetTitle() ?? movie.Name;
- var hasOriginalTitle = movie as IHasOriginalTitle;
- if (hasOriginalTitle != null)
- {
- hasOriginalTitle.OriginalTitle = movieData.GetOriginalTitle();
- }
+ movie.OriginalTitle = movieData.GetOriginalTitle();
// Bug in Mono: WebUtility.HtmlDecode should return null if the string is null but in Mono it generate an System.ArgumentNullException.
movie.Overview = movieData.overview != null ? WebUtility.HtmlDecode(movieData.overview) : null;
@@ -203,7 +200,11 @@ namespace MediaBrowser.Providers.Movies
if (ourRelease != null)
{
var ratingPrefix = string.Equals(preferredCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? "" : preferredCountryCode + "-";
- movie.OfficialRating = ratingPrefix + ourRelease.certification;
+ var newRating = ratingPrefix + ourRelease.certification;
+
+ newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);
+
+ movie.OfficialRating = newRating;
}
else if (usRelease != null)
{
diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs
index 532128186..67ddd8981 100644
--- a/MediaBrowser.Providers/Music/AudioMetadataService.cs
+++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs
@@ -6,6 +6,7 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Providers.Manager;
using System.Collections.Generic;
+using System.Linq;
using CommonIO;
namespace MediaBrowser.Providers.Music
@@ -21,7 +22,7 @@ namespace MediaBrowser.Providers.Music
if (replaceData || targetItem.Artists.Count == 0)
{
- targetItem.Artists = sourceItem.Artists;
+ targetItem.Artists = sourceItem.Artists.ToList();
}
if (replaceData || string.IsNullOrEmpty(targetItem.Album))
diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
index 914b775af..428bde2f2 100644
--- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
+++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs
@@ -212,13 +212,15 @@ namespace MediaBrowser.Providers.Omdb
{
var result = new MetadataResult<Series>
{
- Item = new Series()
+ Item = new Series(),
+ QueriedById = true
};
var imdbId = info.GetProviderId(MetadataProviders.Imdb);
if (string.IsNullOrWhiteSpace(imdbId))
{
imdbId = await GetSeriesImdbId(info, cancellationToken).ConfigureAwait(false);
+ result.QueriedById = false;
}
if (!string.IsNullOrEmpty(imdbId))
@@ -251,13 +253,15 @@ namespace MediaBrowser.Providers.Omdb
{
var result = new MetadataResult<T>
{
- Item = new T()
+ Item = new T(),
+ QueriedById = true
};
var imdbId = info.GetProviderId(MetadataProviders.Imdb);
if (string.IsNullOrWhiteSpace(imdbId))
{
imdbId = await GetMovieImdbId(info, cancellationToken).ConfigureAwait(false);
+ result.QueriedById = false;
}
if (!string.IsNullOrEmpty(imdbId))
diff --git a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
index 621f66514..78bce241f 100644
--- a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs
@@ -43,7 +43,8 @@ namespace MediaBrowser.Providers.TV
{
var result = new MetadataResult<Episode>()
{
- Item = new Episode()
+ Item = new Episode(),
+ QueriedById = true
};
// Allowing this will dramatically increase scan times
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
index bc9842b73..748124c03 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs
@@ -91,6 +91,13 @@ namespace MediaBrowser.Providers.TV
var response = await GetEpisodeInfo(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
result.HasMetadata = true;
+ result.QueriedById = true;
+
+ if (!string.IsNullOrEmpty(response.overview))
+ {
+ // if overview is non-empty, we can assume that localized data was returned
+ result.ResultLanguage = info.MetadataLanguage;
+ }
var item = new Episode();
result.Item = item;
diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
index 3245a2c85..fb0678029 100644
--- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
+++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs
@@ -119,6 +119,7 @@ namespace MediaBrowser.Providers.TV
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
{
var result = new MetadataResult<Series>();
+ result.QueriedById = true;
var tmdbId = info.GetProviderId(MetadataProviders.Tmdb);
@@ -154,6 +155,7 @@ namespace MediaBrowser.Providers.TV
if (string.IsNullOrEmpty(tmdbId))
{
+ result.QueriedById = false;
var searchResults = await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetSearchResults(info, cancellationToken).ConfigureAwait(false);
var searchResult = searchResults.FirstOrDefault();
@@ -168,7 +170,7 @@ namespace MediaBrowser.Providers.TV
{
cancellationToken.ThrowIfCancellationRequested();
- result.Item = await FetchSeriesData(tmdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
+ result = await FetchMovieData(tmdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
result.HasMetadata = result.Item != null;
}
@@ -176,7 +178,7 @@ namespace MediaBrowser.Providers.TV
return result;
}
- private async Task<Series> FetchSeriesData(string tmdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
+ private async Task<MetadataResult<Series>> FetchMovieData(string tmdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
{
string dataFilePath = null;
RootObject seriesInfo = null;
@@ -194,16 +196,18 @@ namespace MediaBrowser.Providers.TV
tmdbId = seriesInfo.id.ToString(_usCulture);
dataFilePath = GetDataFilePath(tmdbId, language);
- _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));
+ _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));
_jsonSerializer.SerializeToFile(seriesInfo, dataFilePath);
await EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
- var item = new Series();
+ var result = new MetadataResult<Series>();
+ result.Item = new Series();
+ result.ResultLanguage = seriesInfo.ResultLanguage;
- ProcessMainInfo(item, seriesInfo, preferredCountryCode);
+ ProcessMainInfo(result.Item, seriesInfo, preferredCountryCode);
- return item;
+ return result;
}
private void ProcessMainInfo(Series series, RootObject seriesInfo, string preferredCountryCode)
@@ -324,7 +328,7 @@ namespace MediaBrowser.Providers.TV
var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
- _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));
+ _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));
_jsonSerializer.SerializeToFile(mainResult, dataFilePath);
}
@@ -354,6 +358,11 @@ namespace MediaBrowser.Providers.TV
}).ConfigureAwait(false))
{
mainResult = _jsonSerializer.DeserializeFromStream<RootObject>(json);
+
+ if (!string.IsNullOrEmpty(language))
+ {
+ mainResult.ResultLanguage = language;
+ }
}
cancellationToken.ThrowIfCancellationRequested();
@@ -385,6 +394,7 @@ namespace MediaBrowser.Providers.TV
var englishResult = _jsonSerializer.DeserializeFromStream<RootObject>(json);
mainResult.overview = englishResult.overview;
+ mainResult.ResultLanguage = "en";
}
}
@@ -627,6 +637,7 @@ namespace MediaBrowser.Providers.TV
public ExternalIds external_ids { get; set; }
public Videos videos { get; set; }
public ContentRatings content_ratings { get; set; }
+ public string ResultLanguage { get; set; }
}
public int Order
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
index a41a95c12..41a2282d8 100644
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs
@@ -108,6 +108,7 @@ namespace MediaBrowser.Providers.TV
public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo searchInfo, CancellationToken cancellationToken)
{
var result = new MetadataResult<Episode>();
+ result.QueriedById = true;
if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds) &&
(searchInfo.IndexNumber.HasValue || searchInfo.PremiereDate.HasValue))
@@ -715,6 +716,17 @@ namespace MediaBrowser.Providers.TV
break;
}
+ case "Language":
+ {
+ var val = reader.ReadElementContentAsString();
+
+ if (!string.IsNullOrWhiteSpace(val))
+ {
+ result.ResultLanguage = val;
+ }
+
+ break;
+ }
default:
reader.Skip();
diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
index 66a02eba2..4ac9e6836 100644
--- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
+++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs
@@ -93,9 +93,11 @@ namespace MediaBrowser.Providers.TV
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo itemId, CancellationToken cancellationToken)
{
var result = new MetadataResult<Series>();
+ result.QueriedById = true;
if (!IsValidSeries(itemId.ProviderIds))
{
+ result.QueriedById = false;
await Identify(itemId).ConfigureAwait(false);
}
@@ -159,7 +161,7 @@ namespace MediaBrowser.Providers.TV
var seriesXmlPath = GetSeriesXmlPath(seriesProviderIds, metadataLanguage);
var actorsXmlPath = Path.Combine(seriesDataPath, "actors.xml");
- FetchSeriesInfo(series, seriesXmlPath, cancellationToken);
+ FetchSeriesInfo(result, seriesXmlPath, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
@@ -607,7 +609,7 @@ namespace MediaBrowser.Providers.TV
return name.Trim();
}
- private void FetchSeriesInfo(Series item, string seriesXmlPath, CancellationToken cancellationToken)
+ private void FetchSeriesInfo(MetadataResult<Series> result, string seriesXmlPath, CancellationToken cancellationToken)
{
var settings = new XmlReaderSettings
{
@@ -639,7 +641,7 @@ namespace MediaBrowser.Providers.TV
{
using (var subtree = reader.ReadSubtree())
{
- FetchDataFromSeriesNode(item, subtree, cancellationToken);
+ FetchDataFromSeriesNode(result, subtree, cancellationToken);
}
break;
}
@@ -667,9 +669,9 @@ namespace MediaBrowser.Providers.TV
}
}
- if (item.Status.HasValue && item.Status.Value == SeriesStatus.Ended && episiodeAirDates.Count > 0)
+ if (result.Item.Status.HasValue && result.Item.Status.Value == SeriesStatus.Ended && episiodeAirDates.Count > 0)
{
- item.EndDate = episiodeAirDates.Max();
+ result.Item.EndDate = episiodeAirDates.Max();
}
}
@@ -861,8 +863,10 @@ namespace MediaBrowser.Providers.TV
}
}
- private void FetchDataFromSeriesNode(Series item, XmlReader reader, CancellationToken cancellationToken)
+ private void FetchDataFromSeriesNode(MetadataResult<Series> result, XmlReader reader, CancellationToken cancellationToken)
{
+ Series item = result.Item;
+
reader.MoveToContent();
// Loop through each element
@@ -886,6 +890,12 @@ namespace MediaBrowser.Providers.TV
break;
}
+ case "Language":
+ {
+ result.ResultLanguage = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
+ break;
+ }
+
case "Airs_DayOfWeek":
{
var val = reader.ReadElementContentAsString();
diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs b/MediaBrowser.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
index 3239b20b2..6cba1b441 100644
--- a/MediaBrowser.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
+++ b/MediaBrowser.Server.Implementations/Channels/ChannelDynamicMediaSourceProvider.cs
@@ -35,7 +35,7 @@ namespace MediaBrowser.Server.Implementations.Channels
throw new NotImplementedException();
}
- public Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken)
+ public Task CloseMediaSource(string liveStreamId)
{
throw new NotImplementedException();
}
diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs
index bb7e142b6..b76cf46b0 100644
--- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs
+++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs
@@ -530,6 +530,19 @@ namespace MediaBrowser.Server.Implementations.Channels
return GetChannelFeaturesDto(channel, channelProvider, channelProvider.GetChannelFeatures());
}
+ public bool SupportsSync(string channelId)
+ {
+ if (string.IsNullOrWhiteSpace(channelId))
+ {
+ throw new ArgumentNullException("channelId");
+ }
+
+ //var channel = GetChannel(channelId);
+ var channelProvider = GetChannelProvider(channelId);
+
+ return channelProvider.GetChannelFeatures().SupportsContentDownloading;
+ }
+
public ChannelFeatures GetChannelFeaturesDto(Channel channel,
IChannel provider,
InternalChannelFeatures features)
@@ -1450,6 +1463,24 @@ namespace MediaBrowser.Server.Implementations.Channels
return result;
}
+ internal IChannel GetChannelProvider(string internalChannelId)
+ {
+ if (internalChannelId == null)
+ {
+ throw new ArgumentNullException("internalChannelId");
+ }
+
+ var result = GetAllChannels()
+ .FirstOrDefault(i => string.Equals(GetInternalChannelId(i.Name).ToString("N"), internalChannelId, StringComparison.OrdinalIgnoreCase));
+
+ if (result == null)
+ {
+ throw new ResourceNotFoundException("No channel provider found for channel id " + internalChannelId);
+ }
+
+ return result;
+ }
+
private IEnumerable<BaseItem> ApplyFilters(IEnumerable<BaseItem> items, IEnumerable<ItemFilter> filters, User user)
{
foreach (var filter in filters.OrderByDescending(f => (int)f))
diff --git a/MediaBrowser.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/MediaBrowser.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
index 005bbb852..5ac3da3db 100644
--- a/MediaBrowser.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
+++ b/MediaBrowser.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs
@@ -35,7 +35,7 @@ namespace MediaBrowser.Server.Implementations.Channels
public string Category
{
- get { return "Channels"; }
+ get { return "Internet Channels"; }
}
public async Task Execute(System.Threading.CancellationToken cancellationToken, IProgress<double> progress)
diff --git a/MediaBrowser.Server.Implementations/Collections/CollectionsDynamicFolder.cs b/MediaBrowser.Server.Implementations/Collections/CollectionsDynamicFolder.cs
index 6cd9e9620..50bb6c559 100644
--- a/MediaBrowser.Server.Implementations/Collections/CollectionsDynamicFolder.cs
+++ b/MediaBrowser.Server.Implementations/Collections/CollectionsDynamicFolder.cs
@@ -2,6 +2,7 @@
using MediaBrowser.Controller.Entities;
using System.IO;
using CommonIO;
+using MediaBrowser.Controller.Collections;
namespace MediaBrowser.Server.Implementations.Collections
{
diff --git a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs
index 28a62c012..2b2373a47 100644
--- a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs
+++ b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs
@@ -43,7 +43,7 @@ namespace MediaBrowser.Server.Implementations.Connect
{
LoadCachedAddress();
- _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
+ _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(1));
((ConnectManager)_connectManager).Start();
}
diff --git a/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs b/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs
index 45cb2f57d..b2dd8ec86 100644
--- a/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs
+++ b/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs
@@ -403,6 +403,14 @@ namespace MediaBrowser.Server.Implementations.Connect
public async Task<UserLinkResult> LinkUser(string userId, string connectUsername)
{
+ if (string.IsNullOrWhiteSpace(userId))
+ {
+ throw new ArgumentNullException("userId");
+ }
+ if (string.IsNullOrWhiteSpace(connectUsername))
+ {
+ throw new ArgumentNullException("connectUsername");
+ }
if (string.IsNullOrWhiteSpace(ConnectServerId))
{
await UpdateConnectInfo().ConfigureAwait(false);
@@ -422,14 +430,6 @@ namespace MediaBrowser.Server.Implementations.Connect
private async Task<UserLinkResult> LinkUserInternal(string userId, string connectUsername)
{
- if (string.IsNullOrWhiteSpace(userId))
- {
- throw new ArgumentNullException("userId");
- }
- if (string.IsNullOrWhiteSpace(connectUsername))
- {
- throw new ArgumentNullException("connectUsername");
- }
if (string.IsNullOrWhiteSpace(ConnectServerId))
{
throw new ArgumentNullException("ConnectServerId");
@@ -446,11 +446,17 @@ namespace MediaBrowser.Server.Implementations.Connect
throw new ArgumentException("The Emby account has been disabled.");
}
+ var existingUser = _userManager.Users.FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUser.Id) && !string.IsNullOrWhiteSpace(i.ConnectAccessKey));
+ if (existingUser != null)
+ {
+ throw new InvalidOperationException("This connect user is already linked to local user " + existingUser.Name);
+ }
+
var user = GetUser(userId);
if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
{
- await RemoveConnect(user, connectUser.Id).ConfigureAwait(false);
+ await RemoveConnect(user, user.ConnectUserId).ConfigureAwait(false);
}
var url = GetConnectUrl("ServerAuthorizations");
diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs
index be68162ca..e4f1460c6 100644
--- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs
+++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs
@@ -437,6 +437,7 @@ namespace MediaBrowser.Server.Implementations.Dto
dto.TrailerCount = taggedItems.Count(i => i is Trailer);
dto.MusicVideoCount = taggedItems.Count(i => i is MusicVideo);
dto.SeriesCount = taggedItems.Count(i => i is Series);
+ dto.ProgramCount = taggedItems.Count(i => i is LiveTvProgram);
dto.SongCount = taggedItems.Count(i => i is Audio);
}
@@ -1168,6 +1169,26 @@ namespace MediaBrowser.Server.Implementations.Dto
};
})
.ToList();
+
+ // Include artists that are not in the database yet, e.g., just added via metadata editor
+ var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
+ dto.ArtistItems.AddRange(hasArtist.Artists
+ .Except(foundArtists, new DistinctNameComparer())
+ .Select(i =>
+ {
+ var artist = _libraryManager.GetArtist(i);
+ if (artist != null)
+ {
+ return new NameIdPair
+ {
+ Name = artist.Name,
+ Id = artist.Id.ToString("N")
+ };
+ }
+
+ return null;
+
+ }).Where(i => i != null));
}
var hasAlbumArtist = item as IHasAlbumArtist;
@@ -1488,7 +1509,7 @@ namespace MediaBrowser.Server.Implementations.Dto
}
}
- private string GetMappedPath(IHasMetadata item)
+ private string GetMappedPath(BaseItem item)
{
var path = item.Path;
@@ -1496,10 +1517,7 @@ namespace MediaBrowser.Server.Implementations.Dto
if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
{
- foreach (var map in _config.Configuration.PathSubstitutions)
- {
- path = _libraryManager.SubstitutePath(path, map.From, map.To);
- }
+ path = _libraryManager.GetPathAfterNetworkSubstitution(path, item);
}
return path;
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index 280bec65b..1021d8823 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -9,6 +9,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Net;
using MediaBrowser.Common.Threading;
+using MediaBrowser.Model.Events;
namespace MediaBrowser.Server.Implementations.EntryPoints
{
@@ -17,17 +18,17 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
private readonly IServerApplicationHost _appHost;
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
- private readonly ISsdpHandler _ssdp;
+ private readonly IDeviceDiscovery _deviceDiscovery;
private PeriodicTimer _timer;
private bool _isStarted;
- public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, ISsdpHandler ssdp)
+ public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery)
{
_logger = logmanager.GetLogger("PortMapper");
_appHost = appHost;
_config = config;
- _ssdp = ssdp;
+ _deviceDiscovery = deviceDiscovery;
}
private string _lastConfigIdentifier;
@@ -61,7 +62,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
public void Run()
{
- //NatUtility.Logger = new LogWriter(_logger);
+ NatUtility.Logger = _logger;
if (_config.Configuration.EnableUPnP)
{
@@ -93,33 +94,22 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
_timer = new PeriodicTimer(ClearCreatedRules, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
- _ssdp.MessageReceived += _ssdp_MessageReceived;
+ _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
_lastConfigIdentifier = GetConfigIdentifier();
_isStarted = true;
}
- private void ClearCreatedRules(object state)
- {
- _createdRules = new List<string>();
- _usnsHandled = new List<string>();
- }
-
- void _ssdp_MessageReceived(object sender, SsdpMessageEventArgs e)
+ private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
- var endpoint = e.EndPoint as IPEndPoint;
-
- if (endpoint == null || e.LocalEndPoint == null)
- {
- return;
- }
+ var info = e.Argument;
string usn;
- if (!e.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
+ if (!info.Headers.TryGetValue("USN", out usn)) usn = string.Empty;
string nt;
- if (!e.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
+ if (!info.Headers.TryGetValue("NT", out nt)) nt = string.Empty;
// Filter device type
if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 &&
@@ -132,15 +122,45 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn;
- if (!_usnsHandled.Contains(identifier))
+ if (info.Location != null && !_usnsHandled.Contains(identifier))
{
_usnsHandled.Add(identifier);
_logger.Debug("Calling Nat.Handle on " + identifier);
- NatUtility.Handle(e.LocalEndPoint.Address, e.Message, endpoint, NatProtocol.Upnp);
+
+ IPAddress address;
+ if (IPAddress.TryParse(info.Location.Host, out address))
+ {
+ // The Handle method doesn't need the port
+ var endpoint = new IPEndPoint(address, info.Location.Port);
+
+ IPAddress localAddress = null;
+
+ try
+ {
+ var localAddressString = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
+
+ if (!IPAddress.TryParse(localAddressString, out localAddress))
+ {
+ return;
+ }
+ }
+ catch
+ {
+ return;
+ }
+
+ NatUtility.Handle(localAddress, info, endpoint, NatProtocol.Upnp);
+ }
}
}
+ private void ClearCreatedRules(object state)
+ {
+ _createdRules = new List<string>();
+ _usnsHandled = new List<string>();
+ }
+
void NatUtility_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
@@ -228,7 +248,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
_timer = null;
}
- _ssdp.MessageReceived -= _ssdp_MessageReceived;
+ _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;
try
{
diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
index f82bb01bb..d14bd4368 100644
--- a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
+++ b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs
@@ -92,11 +92,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints
DeviceId = session.DeviceId
};
- // Report usage to remote server, except for web client, since we already have data on that
- if (!string.Equals(info.AppName, "Dashboard", StringComparison.OrdinalIgnoreCase))
- {
- ReportNewSession(info);
- }
+ ReportNewSession(info);
return info;
}
diff --git a/MediaBrowser.Server.Implementations/IO/FileRefresher.cs b/MediaBrowser.Server.Implementations/IO/FileRefresher.cs
index 2f4605c5c..3df7a03d4 100644
--- a/MediaBrowser.Server.Implementations/IO/FileRefresher.cs
+++ b/MediaBrowser.Server.Implementations/IO/FileRefresher.cs
@@ -12,6 +12,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations.ScheduledTasks;
+using MoreLinq;
namespace MediaBrowser.Server.Implementations.IO
{
@@ -68,6 +69,11 @@ namespace MediaBrowser.Server.Implementations.IO
lock (_timerLock)
{
+ if (_disposed)
+ {
+ return;
+ }
+
if (_timer == null)
{
_timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
@@ -131,9 +137,10 @@ namespace MediaBrowser.Server.Implementations.IO
private async Task ProcessPathChanges(List<string> paths)
{
var itemsToRefresh = paths
+ .Distinct(StringComparer.OrdinalIgnoreCase)
.Select(GetAffectedBaseItem)
.Where(item => item != null)
- .Distinct()
+ .DistinctBy(i => i.Id)
.ToList();
foreach (var p in paths)
@@ -287,6 +294,7 @@ namespace MediaBrowser.Server.Implementations.IO
if (_timer != null)
{
_timer.Dispose();
+ _timer = null;
}
}
}
diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs
index 7ed4dc71e..76f0e6a1d 100644
--- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs
+++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs
@@ -46,6 +46,15 @@ namespace MediaBrowser.Server.Implementations.IO
"TempSBE"
};
+ private readonly IReadOnlyList<string> _alwaysIgnoreSubstrings = new List<string>
+ {
+ // Synology
+ "eaDir",
+ "#recycle",
+ ".wd_tv",
+ ".actors"
+ };
+
private readonly IReadOnlyList<string> _alwaysIgnoreExtensions = new List<string>
{
// thumbs.db
@@ -98,7 +107,14 @@ namespace MediaBrowser.Server.Implementations.IO
if (refreshPath)
{
- ReportFileSystemChanged(path);
+ try
+ {
+ ReportFileSystemChanged(path);
+ }
+ catch (Exception ex)
+ {
+ Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, path);
+ }
}
}
@@ -156,32 +172,16 @@ namespace MediaBrowser.Server.Implementations.IO
Start();
}
- private bool EnableLibraryMonitor
- {
- get
- {
- switch (ConfigurationManager.Configuration.EnableLibraryMonitor)
- {
- case AutoOnOff.Auto:
- return Environment.OSVersion.Platform == PlatformID.Win32NT;
- case AutoOnOff.Enabled:
- return true;
- default:
- return false;
- }
- }
- }
-
private bool IsLibraryMonitorEnabaled(BaseItem item)
{
var options = LibraryManager.GetLibraryOptions(item);
- if (options != null && options.SchemaVersion >= 1)
+ if (options != null)
{
return options.EnableRealtimeMonitor;
}
- return EnableLibraryMonitor;
+ return false;
}
public void Start()
@@ -405,7 +405,20 @@ namespace MediaBrowser.Server.Implementations.IO
{
Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
- ReportFileSystemChanged(e.FullPath);
+ var path = e.FullPath;
+
+ // For deletes, use the parent path
+ if (e.ChangeType == WatcherChangeTypes.Deleted)
+ {
+ var parentPath = Path.GetDirectoryName(path);
+
+ if (!string.IsNullOrWhiteSpace(parentPath))
+ {
+ path = parentPath;
+ }
+ }
+
+ ReportFileSystemChanged(path);
}
catch (Exception ex)
{
@@ -421,10 +434,11 @@ namespace MediaBrowser.Server.Implementations.IO
}
var filename = Path.GetFileName(path);
-
+
var monitorPath = !string.IsNullOrEmpty(filename) &&
!_alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase) &&
- !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path) ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+ !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path) ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
+ _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
// Ignore certain files
var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
diff --git a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs
index 4a43befed..9b23d5be4 100644
--- a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs
+++ b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs
@@ -99,8 +99,9 @@ namespace MediaBrowser.Server.Implementations.Intros
IncludeItemTypes = new[] { typeof(Trailer).Name },
TrailerTypes = trailerTypes.ToArray(),
SimilarTo = item,
- IsPlayed = config.EnableIntrosForWatchedContent ? (bool?) null : false,
+ IsPlayed = config.EnableIntrosForWatchedContent ? (bool?)null : false,
MaxParentalRating = config.EnableIntrosParentalControl ? ratingLevel : null,
+ BlockUnratedItems = config.EnableIntrosParentalControl ? new[] { UnratedItem.Trailer } : new UnratedItem[] { },
Limit = config.TrailerLimit
});
@@ -110,7 +111,7 @@ namespace MediaBrowser.Server.Implementations.Intros
Type = i.SourceType == SourceType.Channel ? ItemWithTrailerType.ChannelTrailer : ItemWithTrailerType.ItemWithTrailer,
LibraryManager = _libraryManager
}));
- }
+ }
return GetResult(item, candidates, config);
}
@@ -197,7 +198,7 @@ namespace MediaBrowser.Server.Implementations.Intros
}
returnResult.AddRange(GetMediaInfoIntrosByTags(allIntros, item.Tags).Take(1));
-
+
return returnResult.DistinctBy(i => i.Path, StringComparer.OrdinalIgnoreCase);
}
catch (IOException)
diff --git a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
index ba7e33890..b550d1dda 100644
--- a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
+++ b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
@@ -33,7 +33,8 @@ namespace MediaBrowser.Server.Implementations.Library
// Synology
"@eaDir",
- "eaDir"
+ "eaDir",
+ "#recycle"
};
diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs
index 5d556e3a6..f6fb158ae 100644
--- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs
+++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs
@@ -401,7 +401,7 @@ namespace MediaBrowser.Server.Implementations.Library
var locationType = item.LocationType;
var children = item.IsFolder
- ? ((Folder)item).GetRecursiveChildren().ToList()
+ ? ((Folder)item).GetRecursiveChildren(false).ToList()
: new List<BaseItem>();
foreach (var metadataPath in GetMetadataPaths(item, children))
@@ -621,9 +621,38 @@ namespace MediaBrowser.Server.Implementations.Library
return ResolveItem(args, resolvers);
}
+ private readonly List<string> _ignoredPaths = new List<string>();
+
+ public void RegisterIgnoredPath(string path)
+ {
+ lock (_ignoredPaths)
+ {
+ _ignoredPaths.Add(path);
+ }
+ }
+ public void UnRegisterIgnoredPath(string path)
+ {
+ lock (_ignoredPaths)
+ {
+ _ignoredPaths.Remove(path);
+ }
+ }
+
public bool IgnoreFile(FileSystemMetadata file, BaseItem parent)
{
- return EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
+ if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)))
+ {
+ return true;
+ }
+
+ //lock (_ignoredPaths)
+ {
+ if (_ignoredPaths.Contains(file.FullName, StringComparer.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ }
+ return false;
}
public IEnumerable<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
@@ -666,7 +695,7 @@ namespace MediaBrowser.Server.Implementations.Library
public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
IDirectoryService directoryService,
- Folder parent,
+ Folder parent,
LibraryOptions libraryOptions,
string collectionType,
IItemResolver[] resolvers)
@@ -1461,10 +1490,10 @@ namespace MediaBrowser.Server.Implementations.Library
private void AddUserToQuery(InternalItemsQuery query, User user)
{
- if (query.AncestorIds.Length == 0 &&
- !query.ParentId.HasValue &&
- query.ChannelIds.Length == 0 &&
- query.TopParentIds.Length == 0 &&
+ if (query.AncestorIds.Length == 0 &&
+ !query.ParentId.HasValue &&
+ query.ChannelIds.Length == 0 &&
+ query.TopParentIds.Length == 0 &&
string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey)
&& query.ItemIds.Length == 0)
{
@@ -2498,8 +2527,60 @@ namespace MediaBrowser.Server.Implementations.Library
}).OrderBy(i => i.Path).ToList();
}
+ public string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem)
+ {
+ if (ownerItem != null)
+ {
+ var libraryOptions = GetLibraryOptions(ownerItem);
+ if (libraryOptions != null)
+ {
+ foreach (var pathInfo in libraryOptions.PathInfos)
+ {
+ if (string.IsNullOrWhiteSpace(pathInfo.NetworkPath))
+ {
+ continue;
+ }
+
+ var substitutionResult = SubstitutePathInternal(path, pathInfo.Path, pathInfo.NetworkPath);
+ if (substitutionResult.Item2)
+ {
+ return substitutionResult.Item1;
+ }
+ }
+ }
+ }
+
+ var metadataPath = ConfigurationManager.Configuration.MetadataPath;
+ var metadataNetworkPath = ConfigurationManager.Configuration.MetadataNetworkPath;
+
+ if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath))
+ {
+ var metadataSubstitutionResult = SubstitutePathInternal(path, metadataPath, metadataNetworkPath);
+ if (metadataSubstitutionResult.Item2)
+ {
+ return metadataSubstitutionResult.Item1;
+ }
+ }
+
+ foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
+ {
+ var substitutionResult = SubstitutePathInternal(path, map.From, map.To);
+ if (substitutionResult.Item2)
+ {
+ return substitutionResult.Item1;
+ }
+ }
+
+ return path;
+ }
+
public string SubstitutePath(string path, string from, string to)
{
+ return SubstitutePathInternal(path, from, to).Item1;
+ }
+
+ private Tuple<string, bool> SubstitutePathInternal(string path, string from, string to)
+ {
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException("path");
@@ -2513,7 +2594,11 @@ namespace MediaBrowser.Server.Implementations.Library
throw new ArgumentNullException("to");
}
+ from = from.Trim();
+ to = to.Trim();
+
var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
+ var changed = false;
if (!string.Equals(newPath, path))
{
@@ -2525,9 +2610,11 @@ namespace MediaBrowser.Server.Implementations.Library
{
newPath = newPath.Replace('/', '\\');
}
+
+ changed = true;
}
- return newPath;
+ return new Tuple<string, bool>(newPath, changed);
}
private void SetExtraTypeFromFilename(Video item)
@@ -2656,7 +2743,7 @@ namespace MediaBrowser.Server.Implementations.Library
throw new InvalidOperationException();
}
- public void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, LibraryOptions options, bool refreshLibrary)
+ public void AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary)
{
if (string.IsNullOrWhiteSpace(name))
{
@@ -2674,12 +2761,13 @@ namespace MediaBrowser.Server.Implementations.Library
virtualFolderPath = Path.Combine(rootFolderPath, name);
}
- if (mediaPaths != null)
+ var mediaPathInfos = options.PathInfos;
+ if (mediaPathInfos != null)
{
- var invalidpath = mediaPaths.FirstOrDefault(i => !_fileSystem.DirectoryExists(i));
+ var invalidpath = mediaPathInfos.FirstOrDefault(i => !_fileSystem.DirectoryExists(i.Path));
if (invalidpath != null)
{
- throw new ArgumentException("The specified path does not exist: " + invalidpath + ".");
+ throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
}
}
@@ -2701,11 +2789,11 @@ namespace MediaBrowser.Server.Implementations.Library
CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
- if (mediaPaths != null)
+ if (mediaPathInfos != null)
{
- foreach (var path in mediaPaths)
+ foreach (var path in mediaPathInfos)
{
- AddMediaPath(name, path);
+ AddMediaPathInternal(name, path, false);
}
}
}
@@ -2731,6 +2819,137 @@ namespace MediaBrowser.Server.Implementations.Library
}
}
+ private bool ValidateNetworkPath(string path)
+ {
+ if (Environment.OSVersion.Platform == PlatformID.Win32NT || !path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
+ {
+ return Directory.Exists(path);
+ }
+
+ // Without native support for unc, we cannot validate this when running under mono
+ return true;
+ }
+
+ private const string ShortcutFileExtension = ".mblink";
+ private const string ShortcutFileSearch = "*" + ShortcutFileExtension;
+ public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
+ {
+ AddMediaPathInternal(virtualFolderName, pathInfo, true);
+ }
+
+ private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
+ {
+ if (pathInfo == null)
+ {
+ throw new ArgumentNullException("path");
+ }
+
+ var path = pathInfo.Path;
+
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ throw new ArgumentNullException("path");
+ }
+
+ if (!_fileSystem.DirectoryExists(path))
+ {
+ throw new DirectoryNotFoundException("The path does not exist.");
+ }
+
+ if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
+ {
+ throw new DirectoryNotFoundException("The network path does not exist.");
+ }
+
+ var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
+
+ var shortcutFilename = _fileSystem.GetFileNameWithoutExtension(path);
+
+ var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
+
+ while (_fileSystem.FileExists(lnk))
+ {
+ shortcutFilename += "1";
+ lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
+ }
+
+ _fileSystem.CreateShortcut(lnk, path);
+
+ RemoveContentTypeOverrides(path);
+
+ if (saveLibraryOptions)
+ {
+ var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
+
+ var list = libraryOptions.PathInfos.ToList();
+ list.Add(pathInfo);
+ libraryOptions.PathInfos = list.ToArray();
+
+ SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
+
+ CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
+ }
+ }
+
+ public void UpdateMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
+ {
+ if (pathInfo == null)
+ {
+ throw new ArgumentNullException("path");
+ }
+
+ if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
+ {
+ throw new DirectoryNotFoundException("The network path does not exist.");
+ }
+
+ var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
+
+ var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
+
+ SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
+
+ var list = libraryOptions.PathInfos.ToList();
+ foreach (var originalPathInfo in list)
+ {
+ if (string.Equals(pathInfo.Path, originalPathInfo.Path, StringComparison.Ordinal))
+ {
+ originalPathInfo.NetworkPath = pathInfo.NetworkPath;
+ break;
+ }
+ }
+
+ libraryOptions.PathInfos = list.ToArray();
+
+ CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
+ }
+
+ private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
+ {
+ var topLibraryFolders = GetUserRootFolder().Children.ToList();
+ var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders);
+
+ if (info.Locations.Count > 0 && info.Locations.Count != options.PathInfos.Length)
+ {
+ var list = options.PathInfos.ToList();
+
+ foreach (var location in info.Locations)
+ {
+ if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
+ {
+ list.Add(new MediaPathInfo
+ {
+ Path = location
+ });
+ }
+ }
+
+ options.PathInfos = list.ToArray();
+ }
+ }
+
public void RemoveVirtualFolder(string name, bool refreshLibrary)
{
if (string.IsNullOrWhiteSpace(name))
@@ -2775,38 +2994,6 @@ namespace MediaBrowser.Server.Implementations.Library
}
}
- private const string ShortcutFileExtension = ".mblink";
- private const string ShortcutFileSearch = "*" + ShortcutFileExtension;
- public void AddMediaPath(string virtualFolderName, string path)
- {
- if (string.IsNullOrWhiteSpace(path))
- {
- throw new ArgumentNullException("path");
- }
-
- if (!_fileSystem.DirectoryExists(path))
- {
- throw new DirectoryNotFoundException("The path does not exist.");
- }
-
- var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
- var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
-
- var shortcutFilename = _fileSystem.GetFileNameWithoutExtension(path);
-
- var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
-
- while (_fileSystem.FileExists(lnk))
- {
- shortcutFilename += "1";
- lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
- }
-
- _fileSystem.CreateShortcut(lnk, path);
-
- RemoveContentTypeOverrides(path);
- }
-
private void RemoveContentTypeOverrides(string path)
{
if (string.IsNullOrWhiteSpace(path))
@@ -2843,19 +3030,28 @@ namespace MediaBrowser.Server.Implementations.Library
}
var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
- var path = Path.Combine(rootFolderPath, virtualFolderName);
+ var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
- if (!_fileSystem.DirectoryExists(path))
+ if (!_fileSystem.DirectoryExists(virtualFolderPath))
{
throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
}
- var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => _fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
+ var shortcut = Directory.EnumerateFiles(virtualFolderPath, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => _fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(shortcut))
{
_fileSystem.DeleteFile(shortcut);
}
+
+ var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
+
+ libraryOptions.PathInfos = libraryOptions
+ .PathInfos
+ .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
+ .ToArray();
+
+ CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
}
}
} \ No newline at end of file
diff --git a/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs b/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs
index 4a533ff93..c7650102f 100644
--- a/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs
+++ b/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs
@@ -221,8 +221,28 @@ namespace MediaBrowser.Server.Implementations.Library
}
}
- public async Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, bool enablePathSubstitution)
+ public async Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, string liveStreamId, bool enablePathSubstitution, CancellationToken cancellationToken)
{
+ if (!string.IsNullOrWhiteSpace(liveStreamId))
+ {
+ return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false);
+ }
+ //await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ //try
+ //{
+ // var stream = _openStreams.Values.FirstOrDefault(i => string.Equals(i.MediaSource.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
+
+ // if (stream != null)
+ // {
+ // return stream.MediaSource;
+ // }
+ //}
+ //finally
+ //{
+ // _liveStreamSemaphore.Release();
+ //}
+
var sources = await GetPlayackMediaSources(item.Id.ToString("N"), null, enablePathSubstitution, new[] { MediaType.Audio, MediaType.Video },
CancellationToken.None).ConfigureAwait(false);
@@ -335,7 +355,7 @@ namespace MediaBrowser.Server.Implementations.Library
.ToList();
}
- private readonly ConcurrentDictionary<string, LiveStreamInfo> _openStreams = new ConcurrentDictionary<string, LiveStreamInfo>(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary<string, LiveStreamInfo> _openStreams = new Dictionary<string, LiveStreamInfo>(StringComparer.OrdinalIgnoreCase);
private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, bool enableAutoClose, CancellationToken cancellationToken)
@@ -363,7 +383,7 @@ namespace MediaBrowser.Server.Implementations.Library
Id = mediaSource.LiveStreamId,
MediaSource = mediaSource
};
- _openStreams.AddOrUpdate(mediaSource.LiveStreamId, info, (key, i) => info);
+ _openStreams[mediaSource.LiveStreamId] = info;
if (enableAutoClose)
{
@@ -401,7 +421,7 @@ namespace MediaBrowser.Server.Implementations.Library
throw new ArgumentNullException("id");
}
- _logger.Debug("Getting live stream {0}", id);
+ _logger.Debug("Getting already opened live stream {0}", id);
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
@@ -445,17 +465,16 @@ namespace MediaBrowser.Server.Implementations.Library
}
}
- private async Task CloseLiveStreamWithProvider(IMediaSourceProvider provider, string streamId, CancellationToken cancellationToken)
+ private async Task CloseLiveStreamWithProvider(IMediaSourceProvider provider, string streamId)
{
_logger.Info("Closing live stream {0} with provider {1}", streamId, provider.GetType().Name);
try
{
- await provider.CloseMediaSource(streamId, cancellationToken).ConfigureAwait(false);
+ await provider.CloseMediaSource(streamId).ConfigureAwait(false);
}
catch (NotImplementedException)
{
-
}
catch (Exception ex)
{
@@ -463,37 +482,35 @@ namespace MediaBrowser.Server.Implementations.Library
}
}
- public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
+ public async Task CloseLiveStream(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false);
try
{
LiveStreamInfo current;
+
if (_openStreams.TryGetValue(id, out current))
{
+ _openStreams.Remove(id);
+ current.Closed = true;
+
if (current.MediaSource.RequiresClosing)
{
var tuple = GetProvider(id);
- await CloseLiveStreamWithProvider(tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false);
+ await CloseLiveStreamWithProvider(tuple.Item1, tuple.Item2).ConfigureAwait(false);
}
- }
-
- LiveStreamInfo removed;
- if (_openStreams.TryRemove(id, out removed))
- {
- removed.Closed = true;
- }
- if (_openStreams.Count == 0)
- {
- StopCloseTimer();
+ if (_openStreams.Count == 0)
+ {
+ StopCloseTimer();
+ }
}
}
finally
@@ -545,10 +562,20 @@ namespace MediaBrowser.Server.Implementations.Library
private async void CloseTimerCallback(object state)
{
- var infos = _openStreams
- .Values
- .Where(i => i.EnableCloseTimer && DateTime.UtcNow - i.Date > _openStreamMaxAge)
- .ToList();
+ List<LiveStreamInfo> infos;
+ await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false);
+
+ try
+ {
+ infos = _openStreams
+ .Values
+ .Where(i => i.EnableCloseTimer && DateTime.UtcNow - i.Date > _openStreamMaxAge)
+ .ToList();
+ }
+ finally
+ {
+ _liveStreamSemaphore.Release();
+ }
foreach (var info in infos)
{
@@ -556,7 +583,7 @@ namespace MediaBrowser.Server.Implementations.Library
{
try
{
- await CloseLiveStream(info.Id, CancellationToken.None).ConfigureAwait(false);
+ await CloseLiveStream(info.Id).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -588,12 +615,10 @@ namespace MediaBrowser.Server.Implementations.Library
{
foreach (var key in _openStreams.Keys.ToList())
{
- var task = CloseLiveStream(key, CancellationToken.None);
+ var task = CloseLiveStream(key);
Task.WaitAll(task);
}
-
- _openStreams.Clear();
}
}
}
diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoResolver.cs
index 3f9475480..d4ebb8457 100644
--- a/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoResolver.cs
+++ b/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoResolver.cs
@@ -89,7 +89,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers
return false;
}
- if (IgnoreFiles.Any(i => filename.IndexOf("-" + i, StringComparison.OrdinalIgnoreCase) != -1))
+ if (IgnoreFiles.Any(i => filename.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1))
{
return false;
}
diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
index 4c6254330..207486f26 100644
--- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
+++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs
@@ -54,7 +54,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV
{
if (args.IsDirectory)
{
- if (args.HasParent<Series>())
+ if (args.HasParent<Series>() || args.HasParent<Season>())
{
return null;
}
@@ -80,7 +80,8 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV
{
return null;
}
- if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, args.GetLibraryOptions(), false))
+ if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, args.GetLibraryOptions(), false) ||
+ args.ContainsFileSystemEntryByName("tvshow.nfo"))
{
return new Series
{
diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
index b21aa904b..0f8c15e71 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs
@@ -47,25 +47,60 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
_logger.Info("Copying recording stream to file {0}", targetFile);
- if (mediaSource.RunTimeTicks.HasValue)
- {
- // The media source already has a fixed duration
- // But add another stop 1 minute later just in case the recording gets stuck for any reason
- var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1)));
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
- }
- else
- {
- // The media source if infinite so we need to handle stopping ourselves
- var durationToken = new CancellationTokenSource(duration);
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
- }
-
- await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
+ // The media source if infinite so we need to handle stopping ourselves
+ var durationToken = new CancellationTokenSource(duration);
+ cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
+
+ await CopyUntilCancelled(response.Content, output, cancellationToken).ConfigureAwait(false);
}
}
_logger.Info("Recording completed to file {0}", targetFile);
}
+
+ private const int BufferSize = 81920;
+ public static Task CopyUntilCancelled(Stream source, Stream target, CancellationToken cancellationToken)
+ {
+ return CopyUntilCancelled(source, target, null, cancellationToken);
+ }
+ public static async Task CopyUntilCancelled(Stream source, Stream target, Action onStarted, CancellationToken cancellationToken)
+ {
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ var bytesRead = await CopyToAsyncInternal(source, target, BufferSize, onStarted, cancellationToken).ConfigureAwait(false);
+
+ onStarted = null;
+
+ //var position = fs.Position;
+ //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
+
+ if (bytesRead == 0)
+ {
+ await Task.Delay(100).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, Int32 bufferSize, Action onStarted, CancellationToken cancellationToken)
+ {
+ byte[] buffer = new byte[bufferSize];
+ int bytesRead;
+ int totalBytesRead = 0;
+
+ while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
+ {
+ await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
+
+ totalBytesRead += bytesRead;
+
+ if (onStarted != null)
+ {
+ onStarted();
+ }
+ onStarted = null;
+ }
+
+ return totalBytesRead;
+ }
}
}
diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
index 649024d16..3db764ae1 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
@@ -22,18 +22,21 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using System.Xml;
using CommonIO;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Power;
using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.FileOrganization;
using Microsoft.Win32;
namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
{
- public class EmbyTV : ILiveTvService, ISupportsNewTimerIds, IHasRegistrationInfo, IDisposable
+ public class EmbyTV : ILiveTvService, ISupportsNewTimerIds, IDisposable
{
private readonly IApplicationHost _appHpst;
private readonly ILogger _logger;
@@ -46,7 +49,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
private readonly LiveTvManager _liveTvManager;
private readonly IFileSystem _fileSystem;
- private readonly ISecurityManager _security;
private readonly ILibraryMonitor _libraryMonitor;
private readonly ILibraryManager _libraryManager;
@@ -62,7 +64,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
- public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, IPowerManagement powerManagement)
+ public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder)
{
Current = this;
@@ -71,7 +73,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
_httpClient = httpClient;
_config = config;
_fileSystem = fileSystem;
- _security = security;
_libraryManager = libraryManager;
_libraryMonitor = libraryMonitor;
_providerManager = providerManager;
@@ -81,7 +82,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
_jsonSerializer = jsonSerializer;
_seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
- _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), powerManagement, _logger);
+ _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
_timerProvider.TimerFired += _timerProvider_TimerFired;
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
@@ -142,9 +143,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
continue;
}
+ var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo { Path = i }).ToArray();
+
+ var libraryOptions = new LibraryOptions
+ {
+ PathInfos = mediaPathInfos
+ };
try
{
- _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, pathsToCreate.ToArray(), new LibraryOptions(), true);
+ _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, libraryOptions, true);
}
catch (Exception ex)
{
@@ -323,27 +330,25 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
{
if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
{
- _timerProvider.Delete(timer);
+ OnTimerOutOfDate(timer);
}
}
}
- private List<ChannelInfo> _channelCache = null;
- private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
+ private void OnTimerOutOfDate(TimerInfo timer)
{
- if (enableCache && _channelCache != null)
- {
-
- return _channelCache.ToList();
- }
+ _timerProvider.Delete(timer);
+ }
+ private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
+ {
var list = new List<ChannelInfo>();
foreach (var hostInstance in _liveTvManager.TunerHosts)
{
try
{
- var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
+ var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
list.AddRange(channels);
}
@@ -376,7 +381,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
}
- _channelCache = list.ToList();
return list;
}
@@ -388,7 +392,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
{
try
{
- var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
+ var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
list.AddRange(channels);
}
@@ -417,7 +421,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
foreach (var timer in timers)
{
- CancelTimerInternal(timer.Id);
+ CancelTimerInternal(timer.Id, true);
}
var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
@@ -428,12 +432,20 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return Task.FromResult(true);
}
- private void CancelTimerInternal(string timerId)
+ private void CancelTimerInternal(string timerId, bool isSeriesCancelled)
{
- var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
- if (remove != null)
+ var timer = _timerProvider.GetTimer(timerId);
+ if (timer != null)
{
- _timerProvider.Delete(remove);
+ if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
+ {
+ _timerProvider.Delete(timer);
+ }
+ else
+ {
+ timer.Status = RecordingStatus.Cancelled;
+ _timerProvider.AddOrUpdate(timer, false);
+ }
}
ActiveRecordingInfo activeRecordingInfo;
@@ -445,7 +457,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
{
- CancelTimerInternal(timerId);
+ CancelTimerInternal(timerId, false);
return Task.FromResult(true);
}
@@ -454,21 +466,57 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return Task.FromResult(true);
}
- public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
+ public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
{
- return CreateTimer(info, cancellationToken);
+ throw new NotImplementedException();
}
- public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
+ public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
{
- return CreateSeriesTimer(info, cancellationToken);
+ throw new NotImplementedException();
}
- public Task<string> CreateTimer(TimerInfo info, CancellationToken cancellationToken)
+ public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
{
- info.Id = Guid.NewGuid().ToString("N");
- _timerProvider.Add(info);
- return Task.FromResult(info.Id);
+ var existingTimer = _timerProvider.GetAll()
+ .FirstOrDefault(i => string.Equals(timer.ProgramId, i.ProgramId, StringComparison.OrdinalIgnoreCase));
+
+ if (existingTimer != null)
+ {
+ if (existingTimer.Status == RecordingStatus.Cancelled ||
+ existingTimer.Status == RecordingStatus.Completed)
+ {
+ existingTimer.Status = RecordingStatus.New;
+ _timerProvider.Update(existingTimer);
+ return Task.FromResult(existingTimer.Id);
+ }
+ else
+ {
+ throw new ArgumentException("A scheduled recording already exists for this program.");
+ }
+ }
+
+ timer.Id = Guid.NewGuid().ToString("N");
+
+ ProgramInfo programInfo = null;
+
+ if (!string.IsNullOrWhiteSpace(timer.ProgramId))
+ {
+ programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
+ }
+ if (programInfo == null)
+ {
+ _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
+ programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
+ }
+
+ if (programInfo != null)
+ {
+ RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
+ }
+
+ _timerProvider.Add(timer);
+ return Task.FromResult(timer.Id);
}
public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
@@ -522,6 +570,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
instance.RecordAnyChannel = info.RecordAnyChannel;
instance.RecordAnyTime = info.RecordAnyTime;
instance.RecordNewOnly = info.RecordNewOnly;
+ instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
+ instance.KeepUpTo = info.KeepUpTo;
+ instance.KeepUntil = info.KeepUntil;
instance.StartDate = info.StartDate;
_seriesTimerProvider.Update(instance);
@@ -542,12 +593,53 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
}
- public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
+ public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
{
- _timerProvider.Update(info);
+ var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
+
+ if (existingTimer == null)
+ {
+ throw new ResourceNotFoundException();
+ }
+
+ // Only update if not currently active
+ ActiveRecordingInfo activeRecordingInfo;
+ if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo))
+ {
+ UpdateExistingTimerWithNewData(existingTimer, updatedTimer);
+
+ _timerProvider.Update(existingTimer);
+ }
+
return Task.FromResult(true);
}
+ private void UpdateExistingTimerWithNewData(TimerInfo existingTimer, TimerInfo updatedTimer)
+ {
+ // Update the program info but retain the status
+ existingTimer.ChannelId = updatedTimer.ChannelId;
+ existingTimer.CommunityRating = updatedTimer.CommunityRating;
+ existingTimer.EndDate = updatedTimer.EndDate;
+ existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
+ existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
+ existingTimer.Genres = updatedTimer.Genres;
+ existingTimer.HomePageUrl = updatedTimer.HomePageUrl;
+ existingTimer.IsKids = updatedTimer.IsKids;
+ existingTimer.IsNews = updatedTimer.IsNews;
+ existingTimer.IsMovie = updatedTimer.IsMovie;
+ existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
+ existingTimer.IsSports = updatedTimer.IsSports;
+ existingTimer.Name = updatedTimer.Name;
+ existingTimer.OfficialRating = updatedTimer.OfficialRating;
+ existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
+ existingTimer.Overview = updatedTimer.Overview;
+ existingTimer.ProductionYear = updatedTimer.ProductionYear;
+ existingTimer.ProgramId = updatedTimer.ProgramId;
+ existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
+ existingTimer.ShortOverview = updatedTimer.ShortOverview;
+ existingTimer.StartDate = updatedTimer.StartDate;
+ }
+
public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
@@ -570,7 +662,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
{
- return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
+ var excludeStatues = new List<RecordingStatus>
+ {
+ RecordingStatus.Completed,
+ RecordingStatus.Cancelled
+ };
+
+ var timers = _timerProvider.GetAll()
+ .Where(i => !excludeStatues.Contains(i.Status));
+
+ return Task.FromResult(timers);
}
public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
@@ -583,7 +684,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
RecordAnyChannel = true,
RecordAnyTime = true,
- RecordNewOnly = false,
+ RecordNewOnly = true,
Days = new List<DayOfWeek>
{
@@ -603,6 +704,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
defaults.ProgramId = program.Id;
}
+ defaults.SkipEpisodesInLibrary = true;
+ defaults.KeepUntil = KeepUntil.UntilDeleted;
+
return Task.FromResult(defaults);
}
@@ -719,46 +823,85 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
throw new NotImplementedException();
}
+ private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
+ private readonly Dictionary<string, LiveStream> _liveStreams = new Dictionary<string, LiveStream>();
+
public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
{
- _logger.Info("Streaming Channel " + channelId);
+ var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
- foreach (var hostInstance in _liveTvManager.TunerHosts)
- {
- try
- {
- var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
+ return result.Item2;
+ }
- result.Item2.Release();
+ private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, int consumerId, bool enableStreamSharing)
+ {
+ var json = _jsonSerializer.SerializeToString(mediaSource);
+ mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
- return result.Item1;
- }
- catch (Exception e)
- {
- _logger.ErrorException("Error getting channel stream", e);
- }
+ mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
+
+ if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
+ {
+ var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks;
+ ticks = Math.Max(0, ticks);
+ mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture);
}
- throw new ApplicationException("Tuner not found.");
+ return mediaSource;
}
- private async Task<Tuple<MediaSourceInfo, ITunerHost, SemaphoreSlim>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
+ private async Task<Tuple<LiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
{
_logger.Info("Streaming Channel " + channelId);
- foreach (var hostInstance in _liveTvManager.TunerHosts)
+ await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ var result = _liveStreams.Values.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
+
+ if (result != null && result.EnableStreamSharing)
{
- try
- {
- var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
+ result.ConsumerCount++;
- return new Tuple<MediaSourceInfo, ITunerHost, SemaphoreSlim>(result.Item1, hostInstance, result.Item2);
- }
- catch (Exception e)
+ _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
+
+ var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.ConsumerCount - 1, result.EnableStreamSharing);
+ _liveStreamsSemaphore.Release();
+ return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, result.TunerHost);
+ }
+
+ try
+ {
+ foreach (var hostInstance in _liveTvManager.TunerHosts)
{
- _logger.ErrorException("Error getting channel stream", e);
+ try
+ {
+ result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
+
+ var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, 0, result.EnableStreamSharing);
+
+ _liveStreams[openedMediaSource.Id] = result;
+
+ result.ConsumerCount++;
+ result.TunerHost = hostInstance;
+ result.OriginalStreamId = streamId;
+
+ _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
+ streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
+
+ return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, hostInstance);
+ }
+ catch (FileNotFoundException)
+ {
+ }
+ catch (OperationCanceledException)
+ {
+ }
}
}
+ finally
+ {
+ _liveStreamsSemaphore.Release();
+ }
throw new ApplicationException("Tuner not found.");
}
@@ -790,9 +933,48 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
throw new NotImplementedException();
}
- public Task CloseLiveStream(string id, CancellationToken cancellationToken)
+ public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
{
- return Task.FromResult(0);
+ // Ignore the consumer id
+ //id = id.Substring(id.IndexOf('_') + 1);
+
+ await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ LiveStream stream;
+ if (_liveStreams.TryGetValue(id, out stream))
+ {
+ stream.ConsumerCount--;
+
+ _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
+
+ if (stream.ConsumerCount <= 0)
+ {
+ _liveStreams.Remove(id);
+
+ _logger.Info("Closing live stream {0}", id);
+
+ await stream.Close().ConfigureAwait(false);
+ _logger.Info("Live stream {0} closed successfully", id);
+ }
+ }
+ else
+ {
+ _logger.Warn("Live stream not found: {0}, unable to close", id);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error closing live stream", ex);
+ }
+ finally
+ {
+ _liveStreamsSemaphore.Release();
+ }
}
public Task RecordLiveStream(string id, CancellationToken cancellationToken)
@@ -817,7 +999,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
if (recordingEndDate <= DateTime.UtcNow)
{
- _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
+ _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
+ OnTimerOutOfDate(timer);
return;
}
@@ -846,12 +1029,13 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
}
- private string GetRecordingPath(TimerInfo timer, ProgramInfo info)
+ private string GetRecordingPath(TimerInfo timer, out string seriesPath)
{
var recordPath = RecordingPath;
var config = GetConfiguration();
+ seriesPath = null;
- if (info.IsSeries)
+ if (timer.IsProgramSeries)
{
var customRecordingPath = config.SeriesRecordingPath;
var allowSubfolder = true;
@@ -866,29 +1050,20 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
recordPath = Path.Combine(recordPath, "Series");
}
- var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
- var folderNameWithYear = folderName;
- if (info.ProductionYear.HasValue)
- {
- folderNameWithYear += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
- }
+ var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
- if (Directory.Exists(Path.Combine(recordPath, folderName)))
- {
- recordPath = Path.Combine(recordPath, folderName);
- }
- else
- {
- recordPath = Path.Combine(recordPath, folderNameWithYear);
- }
+ // Can't use the year here in the folder name because it is the year of the episode, not the series.
+ recordPath = Path.Combine(recordPath, folderName);
+
+ seriesPath = recordPath;
- if (info.SeasonNumber.HasValue)
+ if (timer.SeasonNumber.HasValue)
{
- folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
+ folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
recordPath = Path.Combine(recordPath, folderName);
}
}
- else if (info.IsMovie)
+ else if (timer.IsMovie)
{
var customRecordingPath = config.MovieRecordingPath;
var allowSubfolder = true;
@@ -903,34 +1078,34 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
recordPath = Path.Combine(recordPath, "Movies");
}
- var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
- if (info.ProductionYear.HasValue)
+ var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
+ if (timer.ProductionYear.HasValue)
{
- folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
+ folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
}
recordPath = Path.Combine(recordPath, folderName);
}
- else if (info.IsKids)
+ else if (timer.IsKids)
{
if (config.EnableRecordingSubfolders)
{
recordPath = Path.Combine(recordPath, "Kids");
}
- var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
- if (info.ProductionYear.HasValue)
+ var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
+ if (timer.ProductionYear.HasValue)
{
- folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
+ folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
}
recordPath = Path.Combine(recordPath, folderName);
}
- else if (info.IsSports)
+ else if (timer.IsSports)
{
if (config.EnableRecordingSubfolders)
{
recordPath = Path.Combine(recordPath, "Sports");
}
- recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
+ recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
}
else
{
@@ -938,54 +1113,54 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
{
recordPath = Path.Combine(recordPath, "Other");
}
- recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
+ recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
}
- var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
+ var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
return Path.Combine(recordPath, recordingFileName);
}
- private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
+ private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
+ ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
{
if (timer == null)
{
throw new ArgumentNullException("timer");
}
- ProgramInfo info = null;
+ ProgramInfo programInfo = null;
- if (string.IsNullOrWhiteSpace(timer.ProgramId))
+ if (!string.IsNullOrWhiteSpace(timer.ProgramId))
{
- _logger.Info("Timer {0} has null programId", timer.Id);
+ programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
}
- else
- {
- info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
- }
-
- if (info == null)
+ if (programInfo == null)
{
_logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
- info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
+ programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
}
- if (info == null)
+ if (programInfo != null)
{
- throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
+ RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
}
- var recordPath = GetRecordingPath(timer, info);
+ string seriesPath = null;
+ var recordPath = GetRecordingPath(timer, out seriesPath);
var recordingStatus = RecordingStatus.New;
- var isResourceOpen = false;
- SemaphoreSlim semaphore = null;
+
+ string liveStreamId = null;
try
{
- var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
- isResourceOpen = true;
- semaphore = result.Item3;
- var mediaStreamInfo = result.Item1;
+ var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
+
+ var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
+ .ConfigureAwait(false);
+
+ var mediaStreamInfo = liveStreamInfo.Item2;
+ liveStreamId = mediaStreamInfo.Id;
// HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
//await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
@@ -995,13 +1170,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
recordPath = EnsureFileUnique(recordPath, timer.Id);
+ _libraryManager.RegisterIgnoredPath(recordPath);
_libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
_fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
activeRecordingInfo.Path = recordPath;
var duration = recordingEndDate - DateTime.UtcNow;
- _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ _logger.Info("Beginning recording. Will record for {0} minutes.",
+ duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
_logger.Info("Writing file to path: " + recordPath);
_logger.Info("Opening recording stream from tuner provider");
@@ -1011,20 +1188,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
timer.Status = RecordingStatus.InProgress;
_timerProvider.AddOrUpdate(timer, false);
- result.Item3.Release();
- isResourceOpen = false;
+ SaveNfo(timer, recordPath, seriesPath);
+ EnforceKeepUpTo(timer);
};
- var pathWithDuration = result.Item2.ApplyDuration(mediaStreamInfo.Path, duration);
-
- // If it supports supplying duration via url
- if (!string.Equals(pathWithDuration, mediaStreamInfo.Path, StringComparison.OrdinalIgnoreCase))
- {
- mediaStreamInfo.Path = pathWithDuration;
- mediaStreamInfo.RunTimeTicks = duration.Ticks;
- }
-
- await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false);
+ await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
+ .ConfigureAwait(false);
recordingStatus = RecordingStatus.Completed;
_logger.Info("Recording completed: {0}", recordPath);
@@ -1039,27 +1208,26 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
_logger.ErrorException("Error recording to {0}", ex, recordPath);
recordingStatus = RecordingStatus.Error;
}
- finally
+
+ if (!string.IsNullOrWhiteSpace(liveStreamId))
{
- if (isResourceOpen && semaphore != null)
+ try
{
- semaphore.Release();
+ await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error closing live stream", ex);
}
-
- _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
-
- ActiveRecordingInfo removed;
- _activeRecordings.TryRemove(timer.Id, out removed);
}
- if (recordingStatus == RecordingStatus.Completed)
- {
- timer.Status = RecordingStatus.Completed;
- _timerProvider.Delete(timer);
+ _libraryManager.UnRegisterIgnoredPath(recordPath);
+ _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
- OnSuccessfulRecording(info.IsSeries, recordPath);
- }
- else if (DateTime.UtcNow < timer.EndDate)
+ ActiveRecordingInfo removed;
+ _activeRecordings.TryRemove(timer.Id, out removed);
+
+ if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate)
{
const int retryIntervalSeconds = 60;
_logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
@@ -1068,12 +1236,115 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
_timerProvider.AddOrUpdate(timer);
}
+ else if (File.Exists(recordPath))
+ {
+ timer.RecordingPath = recordPath;
+ timer.Status = RecordingStatus.Completed;
+ _timerProvider.AddOrUpdate(timer, false);
+ OnSuccessfulRecording(timer, recordPath);
+ }
else
{
_timerProvider.Delete(timer);
}
}
+ private async void EnforceKeepUpTo(TimerInfo timer)
+ {
+ if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
+ {
+ return;
+ }
+
+ var seriesTimerId = timer.SeriesTimerId;
+ var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
+
+ if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
+ {
+ return;
+ }
+
+ if (_disposed)
+ {
+ return;
+ }
+
+ await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
+
+ try
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ var timersToDelete = _timerProvider.GetAll()
+ .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
+ .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
+ .OrderByDescending(i => i.EndDate)
+ .Where(i => File.Exists(i.RecordingPath))
+ .Skip(seriesTimer.KeepUpTo - 1)
+ .ToList();
+
+ await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
+ }
+ finally
+ {
+ _recordingDeleteSemaphore.Release();
+ }
+ }
+
+ private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
+ private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
+ {
+ foreach (var timer in timers)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ try
+ {
+ await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error deleting recording", ex);
+ }
+ }
+ }
+
+ private async Task DeleteLibraryItemForTimer(TimerInfo timer)
+ {
+ var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
+
+ if (libraryItem != null)
+ {
+ await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
+ {
+ DeleteFileLocation = true
+ });
+ }
+ else
+ {
+ try
+ {
+ File.Delete(timer.RecordingPath);
+ }
+ catch (DirectoryNotFoundException)
+ {
+
+ }
+ catch (FileNotFoundException)
+ {
+
+ }
+ }
+
+ _timerProvider.Delete(timer);
+ }
+
private string EnsureFileUnique(string path, string timerId)
{
var originalPath = path;
@@ -1114,7 +1385,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
if (config.EnableRecordingEncoding)
{
- var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false);
+ var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
if (regInfo.IsValid)
{
@@ -1125,30 +1396,179 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return new DirectRecorder(_logger, _httpClient, _fileSystem);
}
- private async void OnSuccessfulRecording(bool isSeries, string path)
+ private async void OnSuccessfulRecording(TimerInfo timer, string path)
{
- if (GetConfiguration().EnableAutoOrganize)
+ if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
{
- if (isSeries)
+ try
{
- try
+ // this is to account for the library monitor holding a lock for additional time after the change is complete.
+ // ideally this shouldn't be hard-coded
+ await Task.Delay(30000).ConfigureAwait(false);
+
+ var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
+
+ var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
+
+ if (result.Status == FileSortingStatus.Success)
+ {
+ return;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error processing new recording", ex);
+ }
+ }
+ }
+
+ private void SaveNfo(TimerInfo timer, string recordingPath, string seriesPath)
+ {
+ try
+ {
+ if (timer.IsProgramSeries)
+ {
+ SaveSeriesNfo(timer, recordingPath, seriesPath);
+ }
+ else if (!timer.IsMovie || timer.IsSports)
+ {
+ SaveVideoNfo(timer, recordingPath);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error saving nfo", ex);
+ }
+ }
+
+ private void SaveSeriesNfo(TimerInfo timer, string recordingPath, string seriesPath)
+ {
+ var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
+
+ if (File.Exists(nfoPath))
+ {
+ return;
+ }
+
+ using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
+ {
+ var settings = new XmlWriterSettings
+ {
+ Indent = true,
+ Encoding = Encoding.UTF8,
+ CloseOutput = false
+ };
+
+ using (XmlWriter writer = XmlWriter.Create(stream, settings))
+ {
+ writer.WriteStartDocument(true);
+ writer.WriteStartElement("tvshow");
+
+ if (!string.IsNullOrWhiteSpace(timer.Name))
+ {
+ writer.WriteElementString("title", timer.Name);
+ }
+
+ writer.WriteEndElement();
+ writer.WriteEndDocument();
+ }
+ }
+ }
+
+ public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
+ private void SaveVideoNfo(TimerInfo timer, string recordingPath)
+ {
+ var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
+
+ if (File.Exists(nfoPath))
+ {
+ return;
+ }
+
+ using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
+ {
+ var settings = new XmlWriterSettings
+ {
+ Indent = true,
+ Encoding = Encoding.UTF8,
+ CloseOutput = false
+ };
+
+ using (XmlWriter writer = XmlWriter.Create(stream, settings))
+ {
+ writer.WriteStartDocument(true);
+ writer.WriteStartElement("movie");
+
+ if (!string.IsNullOrWhiteSpace(timer.Name))
{
- // this is to account for the library monitor holding a lock for additional time after the change is complete.
- // ideally this shouldn't be hard-coded
- await Task.Delay(30000).ConfigureAwait(false);
+ writer.WriteElementString("title", timer.Name);
+ }
- var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
+ writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
- var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
+ if (timer.ProductionYear.HasValue)
+ {
+ writer.WriteElementString("year", timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
}
- catch (Exception ex)
+ if (!string.IsNullOrEmpty(timer.OfficialRating))
+ {
+ writer.WriteElementString("mpaa", timer.OfficialRating);
+ }
+
+ var overview = (timer.Overview ?? string.Empty)
+ .StripHtml()
+ .Replace("&quot;", "'");
+
+ writer.WriteElementString("plot", overview);
+ writer.WriteElementString("lockdata", true.ToString().ToLower());
+
+ if (timer.CommunityRating.HasValue)
+ {
+ writer.WriteElementString("rating", timer.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
+ }
+
+ if (timer.IsSports)
+ {
+ AddGenre(timer.Genres, "Sports");
+ }
+ if (timer.IsKids)
+ {
+ AddGenre(timer.Genres, "Kids");
+ }
+ if (timer.IsNews)
+ {
+ AddGenre(timer.Genres, "News");
+ }
+
+ foreach (var genre in timer.Genres)
+ {
+ writer.WriteElementString("genre", genre);
+ }
+
+ if (!string.IsNullOrWhiteSpace(timer.ShortOverview))
{
- _logger.ErrorException("Error processing new recording", ex);
+ writer.WriteElementString("outline", timer.ShortOverview);
}
+
+ if (!string.IsNullOrWhiteSpace(timer.HomePageUrl))
+ {
+ writer.WriteElementString("website", timer.HomePageUrl);
+ }
+
+ writer.WriteEndElement();
+ writer.WriteEndDocument();
}
}
}
+ private void AddGenre(List<string> genres, string genre)
+ {
+ if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
+ {
+ genres.Add(genre);
+ }
+ }
+
private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
{
var epgData = GetEpgDataForChannel(channelId);
@@ -1168,41 +1588,78 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return _config.GetConfiguration<LiveTvOptions>("livetv");
}
+ private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
+ {
+ return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
+ }
+
private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
{
- var newTimers = GetTimersForSeries(seriesTimer, epgData, true).ToList();
+ var allTimers = GetTimersForSeries(seriesTimer, epgData)
+ .ToList();
- var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
+ var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
if (registration.IsValid)
{
- foreach (var timer in newTimers)
+ foreach (var timer in allTimers)
{
- _timerProvider.AddOrUpdate(timer);
+ var existingTimer = _timerProvider.GetTimer(timer.Id);
+
+ if (existingTimer == null)
+ {
+ if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
+ {
+ timer.Status = RecordingStatus.Cancelled;
+ }
+ _timerProvider.Add(timer);
+ }
+ else
+ {
+ // Only update if not currently active
+ ActiveRecordingInfo activeRecordingInfo;
+ if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
+ {
+ UpdateExistingTimerWithNewData(existingTimer, timer);
+
+ if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
+ {
+ existingTimer.Status = RecordingStatus.Cancelled;
+ }
+
+ existingTimer.SeriesTimerId = seriesTimer.Id;
+ _timerProvider.Update(existingTimer);
+ }
+ }
}
}
if (deleteInvalidTimers)
{
- var allTimers = GetTimersForSeries(seriesTimer, epgData, false)
+ var allTimerIds = allTimers
.Select(i => i.Id)
.ToList();
+ var deleteStatuses = new List<RecordingStatus>
+ {
+ RecordingStatus.New
+ };
+
var deletes = _timerProvider.GetAll()
.Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
- .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
+ .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
+ .Where(i => deleteStatuses.Contains(i.Status))
.ToList();
foreach (var timer in deletes)
{
- await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
+ CancelTimerInternal(timer.Id, false);
}
}
}
private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer,
- IEnumerable<ProgramInfo> allPrograms,
- bool filterByCurrentRecordings)
+ IEnumerable<ProgramInfo> allPrograms)
{
if (seriesTimer == null)
{
@@ -1214,19 +1671,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
// Exclude programs that have already ended
- allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
+ allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
- if (filterByCurrentRecordings)
- {
- allPrograms = allPrograms.Where(i => !IsProgramAlreadyInLibrary(i));
- }
-
return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
}
- private bool IsProgramAlreadyInLibrary(ProgramInfo program)
+ private bool IsProgramAlreadyInLibrary(TimerInfo program)
{
if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
{
@@ -1341,28 +1793,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return channelIds.SelectMany(GetEpgDataForChannel).ToList();
}
+ private bool _disposed;
public void Dispose()
{
+ _disposed = true;
foreach (var pair in _activeRecordings.ToList())
{
pair.Value.CancellationTokenSource.Cancel();
}
}
- public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
- {
- if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
- {
- return _security.GetRegistrationStatus("embytvseriesrecordings");
- }
-
- return Task.FromResult(new MBRegistrationRecord
- {
- IsValid = true,
- IsRegistered = true
- });
- }
-
public List<VirtualFolderInfo> GetRecordingFolders()
{
var list = new List<VirtualFolderInfo>();
diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
index fc3a507d1..3e9d186e3 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
@@ -46,82 +46,32 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
_httpClient = httpClient;
}
- public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
- {
- return Path.ChangeExtension(targetFile, ".mp4");
- }
-
- public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
+ private string OutputFormat
{
- var tempfile = Path.Combine(_appPaths.TranscodingTempPath, Guid.NewGuid().ToString("N") + ".ts");
-
- try
- {
- await RecordInternal(mediaSource, tempfile, targetFile, duration, onStarted, cancellationToken)
- .ConfigureAwait(false);
- }
- finally
+ get
{
- try
- {
- File.Delete(tempfile);
- }
- catch (Exception ex)
+ var format = _liveTvOptions.RecordingEncodingFormat;
+
+ if (string.Equals(format, "mkv", StringComparison.OrdinalIgnoreCase))
{
- _logger.ErrorException("Error deleting recording temp file", ex);
+ return "mkv";
}
+
+ return "mp4";
}
}
- public async Task RecordInternal(MediaSourceInfo mediaSource, string tempFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
+ public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
{
- var httpRequestOptions = new HttpRequestOptions()
- {
- Url = mediaSource.Path
- };
-
- httpRequestOptions.BufferContent = false;
-
- using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
- {
- _logger.Info("Opened recording stream from tuner provider");
-
- Directory.CreateDirectory(Path.GetDirectoryName(tempFile));
-
- using (var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read))
- {
- //onStarted();
-
- _logger.Info("Copying recording stream to file {0}", tempFile);
-
- var bufferMs = 5000;
-
- if (mediaSource.RunTimeTicks.HasValue)
- {
- // The media source already has a fixed duration
- // But add another stop 1 minute later just in case the recording gets stuck for any reason
- var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1)));
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
- }
- else
- {
- // The media source if infinite so we need to handle stopping ourselves
- var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMilliseconds(bufferMs)));
- cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
- }
-
- var tempFileTask = response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken);
-
- // Give the temp file a little time to build up
- await Task.Delay(bufferMs, cancellationToken).ConfigureAwait(false);
-
- var recordTask = Task.Run(() => RecordFromFile(mediaSource, tempFile, targetFile, duration, onStarted, cancellationToken), cancellationToken);
+ return Path.ChangeExtension(targetFile, "." + OutputFormat);
+ }
- await tempFileTask.ConfigureAwait(false);
+ public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
+ {
+ var durationToken = new CancellationTokenSource(duration);
+ cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
- await recordTask.ConfigureAwait(false);
- }
- }
+ await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
_logger.Info("Recording completed to file {0}", targetFile);
}
@@ -167,7 +117,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
_logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
- process.Exited += (sender, args) => OnFfMpegProcessExited(process);
+ process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
process.Start();
@@ -181,6 +131,8 @@ namespace MediaBrowser.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);
+
return _taskCompletionSource.Task;
}
@@ -201,29 +153,41 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
- var commandLineArgs = "-fflags +genpts -async 1 -vsync -1 -re -i \"{0}\"{4} -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
+ var inputModifiers = "-fflags +genpts -async 1 -vsync -1";
+ var commandLineArgs = "-i \"{0}\"{4} -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
+
+ long startTimeTicks = 0;
+ //if (mediaSource.DateLiveStreamOpened.HasValue)
+ //{
+ // var elapsed = DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value;
+ // elapsed -= TimeSpan.FromSeconds(10);
+ // if (elapsed.TotalSeconds >= 0)
+ // {
+ // startTimeTicks = elapsed.Ticks + startTimeTicks;
+ // }
+ //}
if (mediaSource.ReadAtNativeFramerate)
{
- commandLineArgs = "-re " + commandLineArgs;
+ inputModifiers += " -re";
+ }
+
+ if (startTimeTicks > 0)
+ {
+ inputModifiers = "-ss " + _mediaEncoder.GetTimeParameter(startTimeTicks) + " " + inputModifiers;
}
commandLineArgs = string.Format(commandLineArgs, inputTempFile, targetFile, videoArgs, GetAudioArgs(mediaSource), durationParam);
- return commandLineArgs;
+ return inputModifiers + " " + commandLineArgs;
}
private string GetAudioArgs(MediaSourceInfo mediaSource)
{
- // do not copy aac because many players have difficulty with aac_latm
- var copyAudio = new[] { "mp3" };
var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
- if (copyAudio.Contains(inputAudioCodec, StringComparer.OrdinalIgnoreCase))
- {
- return "-codec:a:0 copy";
- }
+ // do not copy aac because many players have difficulty with aac_latm
if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return "-codec:a:0 copy";
@@ -281,8 +245,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
/// <summary>
/// Processes the exited.
/// </summary>
- /// <param name="process">The process.</param>
- private void OnFfMpegProcessExited(Process process)
+ private void OnFfMpegProcessExited(Process process, string inputFile)
{
_hasExited = true;
diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
index 9485e0325..bb6935e8e 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs
@@ -25,24 +25,41 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
timer.PostPaddingSeconds = series.PostPaddingSeconds;
timer.IsPostPaddingRequired = series.IsPostPaddingRequired;
timer.IsPrePaddingRequired = series.IsPrePaddingRequired;
+ timer.KeepUntil = series.KeepUntil;
timer.Priority = series.Priority;
timer.Name = parent.Name;
timer.Overview = parent.Overview;
timer.SeriesTimerId = series.Id;
+ CopyProgramInfoToTimerInfo(parent, timer);
+
return timer;
}
- public static string GetRecordingName(TimerInfo timer, ProgramInfo info)
+ public static void CopyProgramInfoToTimerInfo(ProgramInfo programInfo, TimerInfo timerInfo)
{
- if (info == null)
- {
- return timer.ProgramId;
- }
+ timerInfo.SeasonNumber = programInfo.SeasonNumber;
+ timerInfo.EpisodeNumber = programInfo.EpisodeNumber;
+ timerInfo.IsMovie = programInfo.IsMovie;
+ timerInfo.IsKids = programInfo.IsKids;
+ timerInfo.IsNews = programInfo.IsNews;
+ timerInfo.IsSports = programInfo.IsSports;
+ timerInfo.ProductionYear = programInfo.ProductionYear;
+ timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
+ timerInfo.OriginalAirDate = programInfo.OriginalAirDate;
+ timerInfo.IsProgramSeries = programInfo.IsSeries;
+ timerInfo.HomePageUrl = programInfo.HomePageUrl;
+ timerInfo.CommunityRating = programInfo.CommunityRating;
+ timerInfo.ShortOverview = programInfo.ShortOverview;
+ timerInfo.OfficialRating = programInfo.OfficialRating;
+ }
+
+ public static string GetRecordingName(TimerInfo info)
+ {
var name = info.Name;
- if (info.IsSeries)
+ if (info.IsProgramSeries)
{
var addHyphen = true;
diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
index 423358906..bddce0420 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
@@ -9,7 +9,6 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using CommonIO;
-using MediaBrowser.Controller.Power;
using MediaBrowser.Model.LiveTv;
namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
@@ -17,15 +16,13 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
public class TimerManager : ItemDataProvider<TimerInfo>
{
private readonly ConcurrentDictionary<string, Timer> _timers = new ConcurrentDictionary<string, Timer>(StringComparer.OrdinalIgnoreCase);
- private readonly IPowerManagement _powerManagement;
private readonly ILogger _logger;
public event EventHandler<GenericEventArgs<TimerInfo>> TimerFired;
- public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, IPowerManagement powerManagement, ILogger logger1)
+ public TimerManager(IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1)
: base(fileSystem, jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
{
- _powerManagement = powerManagement;
_logger = logger1;
}
@@ -35,7 +32,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
foreach (var item in GetAll().ToList())
{
- AddTimer(item);
+ AddOrUpdateSystemTimer(item);
}
}
@@ -58,18 +55,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
public override void Update(TimerInfo item)
{
base.Update(item);
-
- Timer timer;
- if (_timers.TryGetValue(item.Id, out timer))
- {
- var timespan = RecordingHelper.GetStartTime(item) - DateTime.UtcNow;
- timer.Change(timespan, TimeSpan.Zero);
- ScheduleWake(item);
- }
- else
- {
- AddTimer(item);
- }
+ AddOrUpdateSystemTimer(item);
}
public void AddOrUpdate(TimerInfo item, bool resetTimer)
@@ -100,13 +86,25 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
}
base.Add(item);
- AddTimer(item);
- ScheduleWake(item);
+ AddOrUpdateSystemTimer(item);
+ }
+
+ private bool ShouldStartTimer(TimerInfo item)
+ {
+ if (item.Status == RecordingStatus.Completed ||
+ item.Status == RecordingStatus.Cancelled)
+ {
+ return false;
+ }
+
+ return true;
}
- private void AddTimer(TimerInfo item)
+ private void AddOrUpdateSystemTimer(TimerInfo item)
{
- if (item.Status == RecordingStatus.Completed)
+ StopTimer(item);
+
+ if (!ShouldStartTimer(item))
{
return;
}
@@ -120,33 +118,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
return;
}
- var timerLength = startDate - now;
- StartTimer(item, timerLength);
+ var dueTime = startDate - now;
+ StartTimer(item, dueTime);
}
- private void ScheduleWake(TimerInfo info)
+ private void StartTimer(TimerInfo item, TimeSpan dueTime)
{
- var startDate = RecordingHelper.GetStartTime(info).AddMinutes(-5);
-
- try
- {
- _powerManagement.ScheduleWake(startDate);
- _logger.Info("Scheduled system wake timer at {0} (UTC)", startDate);
- }
- catch (NotImplementedException)
- {
-
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error scheduling wake timer", ex);
- }
- }
-
- public void StartTimer(TimerInfo item, TimeSpan dueTime)
- {
- StopTimer(item);
-
var timer = new Timer(TimerCallback, item.Id, dueTime, TimeSpan.Zero);
if (_timers.TryAdd(item.Id, timer))
@@ -179,5 +156,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs<TimerInfo> { Argument = timer }, Logger);
}
}
+
+ public TimerInfo GetTimer(string id)
+ {
+ return GetAll().FirstOrDefault(r => string.Equals(r.Id, id, StringComparison.OrdinalIgnoreCase));
+ }
}
}
diff --git a/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
index e37109c14..b98919282 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
@@ -166,7 +166,17 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
if (imageIndex > -1)
{
- programDict[schedule.programID].images = GetProgramLogo(ApiUrl, images[imageIndex]);
+ var programEntry = programDict[schedule.programID];
+
+ var data = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>();
+ data = data.OrderByDescending(GetSizeOrder).ToList();
+
+ programEntry.primaryImage = GetProgramImage(ApiUrl, data, "Logo", true, 600);
+ //programEntry.thumbImage = GetProgramImage(ApiUrl, data, "Iconic", false);
+ //programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
+ // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
}
}
@@ -179,6 +189,20 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
return programsInfo;
}
+ private int GetSizeOrder(ScheduleDirect.ImageData image)
+ {
+ if (!string.IsNullOrWhiteSpace(image.height))
+ {
+ int value;
+ if (int.TryParse(image.height, out value))
+ {
+ return value;
+ }
+ }
+
+ return 0;
+ }
+
private readonly object _channelCacheLock = new object();
private ScheduleDirect.Station GetStation(string listingsId, string channelNumber, string channelName)
{
@@ -194,14 +218,22 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
return station;
}
- if (string.IsNullOrWhiteSpace(channelName))
+ if (!string.IsNullOrWhiteSpace(channelName))
{
- return null;
- }
+ channelName = NormalizeName(channelName);
+
+ var result = channelPair.Values.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
- channelName = NormalizeName(channelName);
+ if (result != null)
+ {
+ return result;
+ }
+ }
- return channelPair.Values.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
+ if (!string.IsNullOrWhiteSpace(channelNumber))
+ {
+ return channelPair.Values.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
+ }
}
return null;
@@ -307,9 +339,19 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
channelNumber = channelNumber.TrimStart('0');
_logger.Debug("Found channel: " + channelNumber + " in Schedules Direct");
- var schChannel = root.stations.FirstOrDefault(item => item.stationID == map.stationID);
- AddToChannelPairCache(listingsId, channelNumber, schChannel);
+ var schChannel = (root.stations ?? new List<ScheduleDirect.Station>()).FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
+ if (schChannel != null)
+ {
+ AddToChannelPairCache(listingsId, channelNumber, schChannel);
+ }
+ else
+ {
+ AddToChannelPairCache(listingsId, channelNumber, new ScheduleDirect.Station
+ {
+ stationID = map.stationID
+ });
+ }
}
_logger.Info("Added " + GetChannelPairCacheCount(listingsId) + " channels to the dictionary");
@@ -324,8 +366,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
channel.ImageUrl = station.logo.URL;
channel.HasImage = true;
}
- string channelName = station.name;
- channel.Name = channelName;
+
+ if (!string.IsNullOrWhiteSpace(station.name))
+ {
+ channel.Name = station.name;
+ }
}
else
{
@@ -348,7 +393,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
if (programInfo.audioProperties != null)
{
- if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
+ if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
+ {
+ audioType = ProgramAudio.Atmos;
+ }
+ else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
{
audioType = ProgramAudio.DolbyDigital;
}
@@ -372,13 +421,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
episodeTitle = details.episodeTitle150;
}
- string imageUrl = null;
-
- if (details.hasImageArtwork)
- {
- imageUrl = details.images;
- }
-
var showType = details.showType ?? string.Empty;
var info = new ProgramInfo
@@ -394,7 +436,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
Audio = audioType,
IsRepeat = repeat,
IsSeries = showType.IndexOf("series", StringComparison.OrdinalIgnoreCase) != -1,
- ImageUrl = imageUrl,
+ ImageUrl = details.primaryImage,
IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
IsSports = showType.IndexOf("sports", StringComparison.OrdinalIgnoreCase) != -1,
IsMovie = showType.IndexOf("movie", StringComparison.OrdinalIgnoreCase) != -1 || showType.IndexOf("film", StringComparison.OrdinalIgnoreCase) != -1,
@@ -405,6 +447,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
if (programInfo.videoProperties != null)
{
info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
+ info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
}
if (details.contentRating != null && details.contentRating.Count > 0)
@@ -442,7 +485,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
}
}
- if (!string.IsNullOrWhiteSpace(details.originalAirDate))
+ if (!string.IsNullOrWhiteSpace(details.originalAirDate) && (!info.IsSeries || info.IsRepeat))
{
info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
}
@@ -472,36 +515,69 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
return date;
}
- private string GetProgramLogo(string apiUrl, ScheduleDirect.ShowImages images)
+ private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, string category, bool returnDefaultImage, int desiredWidth)
{
string url = null;
- if (images.data != null)
+
+ var matches = images
+ .Where(i => string.Equals(i.category, category, StringComparison.OrdinalIgnoreCase))
+ .ToList();
+
+ if (matches.Count == 0)
{
- var smallImages = images.data.Where(i => i.size == "Sm").ToList();
- if (smallImages.Any())
- {
- images.data = smallImages;
- }
- var logoIndex = images.data.FindIndex(i => i.category == "Logo");
- if (logoIndex == -1)
+ if (!returnDefaultImage)
{
- logoIndex = 0;
+ return null;
}
- var uri = images.data[logoIndex].uri;
+ matches = images;
+ }
- if (!string.IsNullOrWhiteSpace(uri))
+ var match = matches.FirstOrDefault(i =>
+ {
+ if (!string.IsNullOrWhiteSpace(i.width))
{
- if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
- {
- url = uri;
- }
- else
+ int value;
+ if (int.TryParse(i.width, out value))
{
- url = apiUrl + "/image/" + uri;
+ return value <= desiredWidth;
}
}
- //_logger.Debug("URL for image is : " + url);
+
+ return false;
+ });
+
+ if (match == null)
+ {
+ // Get the second lowest quality image, when possible
+ if (matches.Count > 1)
+ {
+ match = matches[matches.Count - 2];
+ }
+ else
+ {
+ match = matches.FirstOrDefault();
+ }
+ }
+
+ if (match == null)
+ {
+ return null;
+ }
+
+ var uri = match.uri;
+
+ if (!string.IsNullOrWhiteSpace(uri))
+ {
+ if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ url = uri;
+ }
+ else
+ {
+ url = apiUrl + "/image/" + uri;
+ }
}
+ //_logger.Debug("URL for image is : " + url);
return url;
}
@@ -785,9 +861,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
get { return "Schedules Direct"; }
}
+ public static string TypeName = "SchedulesDirect";
public string Type
{
- get { return "SchedulesDirect"; }
+ get { return TypeName; }
}
private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
@@ -924,7 +1001,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
var name = channelNumber;
var station = GetStation(listingsId, channelNumber, null);
- if (station != null)
+ if (station != null && !string.IsNullOrWhiteSpace(station.name))
{
name = station.name;
}
@@ -1190,7 +1267,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
public List<Crew> crew { get; set; }
public string showType { get; set; }
public bool hasImageArtwork { get; set; }
- public string images { get; set; }
+ public string primaryImage { get; set; }
+ public string thumbImage { get; set; }
+ public string bannerImage { get; set; }
public string imageID { get; set; }
public string md5 { get; set; }
public List<string> contentAdvisory { get; set; }
diff --git a/MediaBrowser.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
index d1d8df2e8..d3549aef5 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
@@ -11,6 +11,7 @@ using System.Text;
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.Controller.Configuration;
@@ -115,7 +116,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
var reader = new XmlTvReader(path, GetLanguage(), null);
var results = reader.GetProgrammes(channelNumber, startDateUtc, endDateUtc, cancellationToken);
- return results.Select(p => new ProgramInfo()
+ return results.Select(p => GetProgramInfo(p, info));
+ }
+
+ private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info)
+ {
+ var programInfo = new ProgramInfo
{
ChannelId = p.ChannelId,
EndDate = GetDate(p.EndDate),
@@ -141,7 +147,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.Listings
OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null,
CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null,
SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null
- });
+ };
+
+ if (programInfo.IsMovie)
+ {
+ programInfo.IsSeries = false;
+ programInfo.EpisodeNumber = null;
+ programInfo.EpisodeTitle = null;
+ }
+
+ return programInfo;
}
private DateTime GetDate(DateTime date)
diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvDtoService.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvDtoService.cs
index 683377c61..348bcd97b 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvDtoService.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvDtoService.cs
@@ -52,6 +52,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
PostPaddingSeconds = info.PostPaddingSeconds,
IsPostPaddingRequired = info.IsPostPaddingRequired,
IsPrePaddingRequired = info.IsPrePaddingRequired,
+ KeepUntil = info.KeepUntil,
ExternalChannelId = info.ChannelId,
ExternalSeriesTimerId = info.SeriesTimerId,
ServiceName = service.Name,
@@ -100,6 +101,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
Priority = info.Priority,
RecordAnyChannel = info.RecordAnyChannel,
RecordAnyTime = info.RecordAnyTime,
+ SkipEpisodesInLibrary = info.SkipEpisodesInLibrary,
+ KeepUpTo = info.KeepUpTo,
+ KeepUntil = info.KeepUntil,
RecordNewOnly = info.RecordNewOnly,
ExternalChannelId = info.ChannelId,
ExternalProgramId = info.ProgramId,
@@ -244,6 +248,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
PostPaddingSeconds = dto.PostPaddingSeconds,
IsPostPaddingRequired = dto.IsPostPaddingRequired,
IsPrePaddingRequired = dto.IsPrePaddingRequired,
+ KeepUntil = dto.KeepUntil,
Priority = dto.Priority,
SeriesTimerId = dto.ExternalSeriesTimerId,
ProgramId = dto.ExternalProgramId,
@@ -308,6 +313,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
Priority = dto.Priority,
RecordAnyChannel = dto.RecordAnyChannel,
RecordAnyTime = dto.RecordAnyTime,
+ SkipEpisodesInLibrary = dto.SkipEpisodesInLibrary,
+ KeepUpTo = dto.KeepUpTo,
+ KeepUntil = dto.KeepUntil,
RecordNewOnly = dto.RecordNewOnly,
ProgramId = dto.ExternalProgramId,
ChannelId = dto.ExternalChannelId,
diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs
index 88017aa59..e34868428 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs
@@ -31,7 +31,11 @@ using CommonIO;
using IniParser;
using IniParser.Model;
using MediaBrowser.Common.Events;
+using MediaBrowser.Common.Security;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Model.Events;
+using MediaBrowser.Server.Implementations.LiveTv.Listings;
namespace MediaBrowser.Server.Implementations.LiveTv
{
@@ -49,6 +53,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
private readonly ITaskManager _taskManager;
private readonly IJsonSerializer _jsonSerializer;
private readonly IProviderManager _providerManager;
+ private readonly ISecurityManager _security;
private readonly IDtoService _dtoService;
private readonly ILocalizationManager _localization;
@@ -57,9 +62,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv
private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
- private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
- new ConcurrentDictionary<string, LiveStreamData>();
-
private readonly SemaphoreSlim _refreshRecordingsLock = new SemaphoreSlim(1, 1);
private readonly List<ITunerHost> _tunerHosts = new List<ITunerHost>();
@@ -71,7 +73,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
- public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager, IFileSystem fileSystem)
+ public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager, IFileSystem fileSystem, ISecurityManager security)
{
_config = config;
_logger = logger;
@@ -83,6 +85,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
_jsonSerializer = jsonSerializer;
_providerManager = providerManager;
_fileSystem = fileSystem;
+ _security = security;
_dtoService = dtoService;
_userDataManager = userDataManager;
@@ -145,112 +148,40 @@ namespace MediaBrowser.Server.Implementations.LiveTv
var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
- var channels = _libraryManager.GetItemList(new InternalItemsQuery
+ var internalQuery = new InternalItemsQuery(user)
{
+ IsMovie = query.IsMovie,
+ IsNews = query.IsNews,
+ IsKids = query.IsKids,
+ IsSports = query.IsSports,
+ IsSeries = query.IsSeries,
IncludeItemTypes = new[] { typeof(LiveTvChannel).Name },
- SortBy = new[] { ItemSortBy.SortName },
- TopParentIds = new[] { topFolder.Id.ToString("N") }
+ SortOrder = query.SortOrder ?? SortOrder.Ascending,
+ TopParentIds = new[] { topFolder.Id.ToString("N") },
+ IsFavorite = query.IsFavorite,
+ IsLiked = query.IsLiked,
+ StartIndex = query.StartIndex,
+ Limit = query.Limit
+ };
- }).Cast<LiveTvChannel>();
+ internalQuery.OrderBy.AddRange(query.SortBy.Select(i => new Tuple<string, SortOrder>(i, query.SortOrder ?? SortOrder.Ascending)));
- if (user != null)
+ if (query.EnableFavoriteSorting)
{
- // Avoid implicitly captured closure
- var currentUser = user;
-
- channels = channels
- .Where(i => i.IsVisible(currentUser))
- .OrderBy(i =>
- {
- double number = 0;
-
- if (!string.IsNullOrEmpty(i.Number))
- {
- double.TryParse(i.Number, out number);
- }
-
- return number;
-
- });
-
- if (query.IsFavorite.HasValue)
- {
- var val = query.IsFavorite.Value;
-
- channels = channels
- .Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val);
- }
-
- if (query.IsLiked.HasValue)
- {
- var val = query.IsLiked.Value;
-
- channels = channels
- .Where(i =>
- {
- var likes = _userDataManager.GetUserData(user, i).Likes;
-
- return likes.HasValue && likes.Value == val;
- });
- }
-
- if (query.IsDisliked.HasValue)
- {
- var val = query.IsDisliked.Value;
-
- channels = channels
- .Where(i =>
- {
- var likes = _userDataManager.GetUserData(user, i).Likes;
-
- return likes.HasValue && likes.Value != val;
- });
- }
+ internalQuery.OrderBy.Insert(0, new Tuple<string, SortOrder>(ItemSortBy.IsFavoriteOrLiked, SortOrder.Descending));
}
- var enableFavoriteSorting = query.EnableFavoriteSorting;
-
- channels = channels.OrderBy(i =>
+ if (!internalQuery.OrderBy.Any(i => string.Equals(i.Item1, ItemSortBy.SortName, StringComparison.OrdinalIgnoreCase)))
{
- if (enableFavoriteSorting)
- {
- var userData = _userDataManager.GetUserData(user, i);
-
- if (userData.IsFavorite)
- {
- return 0;
- }
- if (userData.Likes.HasValue)
- {
- if (!userData.Likes.Value)
- {
- return 3;
- }
-
- return 1;
- }
- }
-
- return 2;
- });
-
- var allChannels = channels.ToList();
- IEnumerable<LiveTvChannel> allEnumerable = allChannels;
-
- if (query.StartIndex.HasValue)
- {
- allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
+ internalQuery.OrderBy.Add(new Tuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending));
}
- if (query.Limit.HasValue)
- {
- allEnumerable = allEnumerable.Take(query.Limit.Value);
- }
+ var channelResult = _libraryManager.GetItemsResult(internalQuery);
var result = new QueryResult<LiveTvChannel>
{
- Items = allEnumerable.ToArray(),
- TotalRecordCount = allChannels.Count
+ Items = channelResult.Items.Cast<LiveTvChannel>().ToArray(),
+ TotalRecordCount = channelResult.TotalRecordCount
};
return result;
@@ -401,15 +332,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv
_logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
Normalize(info, service, isVideo);
- var data = new LiveStreamData
- {
- Info = info,
- IsChannel = isChannel,
- ItemId = id
- };
-
- _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
-
return info;
}
catch (Exception ex)
@@ -643,6 +565,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv
};
}
+ var seriesId = info.SeriesId;
+
if (!item.ParentId.Equals(channel.Id))
{
forceUpdate = true;
@@ -662,6 +586,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv
item.EpisodeTitle = info.EpisodeTitle;
item.ExternalId = info.Id;
+ item.ExternalSeriesIdLegacy = seriesId;
+
+ if (!string.IsNullOrWhiteSpace(seriesId) && !string.Equals(item.ExternalSeriesId, seriesId, StringComparison.Ordinal))
+ {
+ forceUpdate = true;
+ }
+ item.ExternalSeriesId = seriesId;
+
item.Genres = info.Genres;
item.IsHD = info.IsHD;
item.IsKids = info.IsKids;
@@ -692,7 +624,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv
item.HomePageUrl = info.HomePageUrl;
item.ProductionYear = info.ProductionYear;
- item.PremiereDate = info.OriginalAirDate;
+
+ if (!info.IsSeries || info.IsRepeat)
+ {
+ item.PremiereDate = info.OriginalAirDate;
+ }
item.IndexNumber = info.EpisodeNumber;
item.ParentIndexNumber = info.SeasonNumber;
@@ -897,8 +833,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv
var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
- var list = new List<Tuple<BaseItemDto, string, string>>();
- list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ServiceName, program.ExternalId));
+ var list = new List<Tuple<BaseItemDto, string, string, string>>();
+ list.Add(new Tuple<BaseItemDto, string, string, string>(dto, program.ServiceName, program.ExternalId, program.ExternalSeriesIdLegacy));
await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
@@ -926,8 +862,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv
MaxStartDate = query.MaxStartDate,
ChannelIds = query.ChannelIds,
IsMovie = query.IsMovie,
+ IsSeries = query.IsSeries,
IsSports = query.IsSports,
IsKids = query.IsKids,
+ IsNews = query.IsNews,
Genres = query.Genres,
StartIndex = query.StartIndex,
Limit = query.Limit,
@@ -937,6 +875,27 @@ namespace MediaBrowser.Server.Implementations.LiveTv
TopParentIds = new[] { topFolder.Id.ToString("N") }
};
+ if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
+ {
+ var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery {}, cancellationToken).ConfigureAwait(false);
+ var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
+ if (seriesTimer != null)
+ {
+ internalQuery.ExternalSeriesId = seriesTimer.SeriesId;
+
+ if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
+ {
+ // Better to return nothing than every program in the database
+ return new QueryResult<BaseItemDto>();
+ }
+ }
+ else
+ {
+ // Better to return nothing than every program in the database
+ return new QueryResult<BaseItemDto>();
+ }
+ }
+
if (query.HasAired.HasValue)
{
if (query.HasAired.Value)
@@ -974,7 +933,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
{
IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
IsAiring = query.IsAiring,
+ IsNews = query.IsNews,
IsMovie = query.IsMovie,
+ IsSeries = query.IsSeries,
IsSports = query.IsSports,
IsKids = query.IsKids,
EnableTotalRecordCount = query.EnableTotalRecordCount,
@@ -1003,9 +964,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
var programList = programs.ToList();
- var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false);
+ var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false) || (query.IsNews ?? false) || (query.IsSeries ?? false);
- programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
+ programs = programList.OrderBy(i => i.StartDate.Date)
.ThenByDescending(i => GetRecommendationScore(i, user.Id, factorChannelWatchCount))
.ThenBy(i => i.StartDate);
@@ -1086,15 +1047,17 @@ namespace MediaBrowser.Server.Implementations.LiveTv
return score;
}
- private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
+ private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string, string>> programs, CancellationToken cancellationToken)
{
var timers = new Dictionary<string, List<TimerInfo>>();
+ var seriesTimers = new Dictionary<string, List<SeriesTimerInfo>>();
foreach (var programTuple in programs)
{
var program = programTuple.Item1;
var serviceName = programTuple.Item2;
var externalProgramId = programTuple.Item3;
+ string externalSeriesId = programTuple.Item4;
if (string.IsNullOrWhiteSpace(serviceName))
{
@@ -1117,6 +1080,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
}
var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
+ var foundSeriesTimer = false;
if (timer != null)
{
@@ -1127,8 +1091,38 @@ namespace MediaBrowser.Server.Implementations.LiveTv
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
.ToString("N");
+
+ foundSeriesTimer = true;
+ }
+ }
+
+ if (foundSeriesTimer || string.IsNullOrWhiteSpace(externalSeriesId))
+ {
+ continue;
+ }
+
+ List<SeriesTimerInfo> seriesTimerList;
+ if (!seriesTimers.TryGetValue(serviceName, out seriesTimerList))
+ {
+ try
+ {
+ var tempTimers = await GetService(serviceName).GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
+ seriesTimers[serviceName] = seriesTimerList = tempTimers.ToList();
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error getting series timer infos", ex);
+ seriesTimers[serviceName] = seriesTimerList = new List<SeriesTimerInfo>();
}
}
+
+ var seriesTimer = seriesTimerList.FirstOrDefault(i => string.Equals(i.SeriesId, externalSeriesId, StringComparison.OrdinalIgnoreCase));
+
+ if (seriesTimer != null)
+ {
+ program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, seriesTimer.Id)
+ .ToString("N");
+ }
}
}
@@ -1261,6 +1255,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv
var start = DateTime.UtcNow.AddHours(-1);
var end = start.AddDays(guideDays);
+ var isMovie = false;
+ var isSports = false;
+ var isNews = false;
+ var isKids = false;
+ var iSSeries = false;
+
var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
foreach (var program in channelPrograms)
@@ -1268,7 +1268,40 @@ namespace MediaBrowser.Server.Implementations.LiveTv
var programItem = await GetProgram(program, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
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;
+ }
}
+
+ currentChannel.IsMovie = isMovie;
+ currentChannel.IsNews = isNews;
+ currentChannel.IsSports = isSports;
+ currentChannel.IsKids = isKids;
+ currentChannel.IsSeries = iSSeries;
+
+ await currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -1423,6 +1456,49 @@ namespace MediaBrowser.Server.Implementations.LiveTv
return new QueryResult<BaseItem>();
}
+ var includeItemTypes = new List<string>();
+ var excludeItemTypes = new List<string>();
+ var genres = new List<string>();
+
+ if (query.IsMovie.HasValue)
+ {
+ if (query.IsMovie.Value)
+ {
+ includeItemTypes.Add(typeof(Movie).Name);
+ }
+ else
+ {
+ excludeItemTypes.Add(typeof(Movie).Name);
+ }
+ }
+ if (query.IsSeries.HasValue)
+ {
+ if (query.IsSeries.Value)
+ {
+ includeItemTypes.Add(typeof(Episode).Name);
+ }
+ else
+ {
+ excludeItemTypes.Add(typeof(Episode).Name);
+ }
+ }
+ if (query.IsSports.HasValue)
+ {
+ if (query.IsSports.Value)
+ {
+ genres.Add("Sports");
+ }
+ }
+ if (query.IsKids.HasValue)
+ {
+ if (query.IsKids.Value)
+ {
+ genres.Add("Kids");
+ genres.Add("Children");
+ genres.Add("Family");
+ }
+ }
+
return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
{
MediaTypes = new[] { MediaType.Video },
@@ -1430,11 +1506,73 @@ namespace MediaBrowser.Server.Implementations.LiveTv
AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
IsFolder = false,
ExcludeLocationTypes = new[] { LocationType.Virtual },
- Limit = Math.Min(200, query.Limit ?? int.MaxValue),
+ Limit = query.Limit,
+ SortBy = new[] { ItemSortBy.DateCreated },
+ SortOrder = SortOrder.Descending,
+ EnableTotalRecordCount = query.EnableTotalRecordCount,
+ IncludeItemTypes = includeItemTypes.ToArray(),
+ ExcludeItemTypes = excludeItemTypes.ToArray(),
+ Genres = genres.ToArray()
+ });
+ }
+
+ public async Task<QueryResult<BaseItemDto>> GetRecordingSeries(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
+ {
+ var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
+ if (user != null && !IsLiveTvEnabled(user))
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ if (_services.Count > 1)
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ if (user == null || (query.IsInProgress ?? false))
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
+ .SelectMany(i => i.Locations)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Select(i => _libraryManager.FindByPath(i, true))
+ .Where(i => i != null)
+ .Where(i => i.IsVisibleStandalone(user))
+ .ToList();
+
+ if (folders.Count == 0)
+ {
+ return new QueryResult<BaseItemDto>();
+ }
+
+ var includeItemTypes = new List<string>();
+ var excludeItemTypes = new List<string>();
+
+ includeItemTypes.Add(typeof(Series).Name);
+
+ var internalResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
+ {
+ Recursive = true,
+ AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
+ Limit = query.Limit,
SortBy = new[] { ItemSortBy.DateCreated },
SortOrder = SortOrder.Descending,
- EnableTotalRecordCount = query.EnableTotalRecordCount
+ EnableTotalRecordCount = query.EnableTotalRecordCount,
+ IncludeItemTypes = includeItemTypes.ToArray(),
+ ExcludeItemTypes = excludeItemTypes.ToArray()
});
+
+ RemoveFields(options);
+
+ var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
+
+ return new QueryResult<BaseItemDto>
+ {
+ Items = returnArray,
+ TotalRecordCount = internalResult.TotalRecordCount
+ };
}
public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
@@ -1492,6 +1630,36 @@ namespace MediaBrowser.Server.Implementations.LiveTv
recordings = recordings.Where(i => i.Status == val);
}
+ if (query.IsMovie.HasValue)
+ {
+ var val = query.IsMovie.Value;
+ recordings = recordings.Where(i => i.IsMovie == val);
+ }
+
+ if (query.IsNews.HasValue)
+ {
+ var val = query.IsNews.Value;
+ recordings = recordings.Where(i => i.IsNews == val);
+ }
+
+ if (query.IsSeries.HasValue)
+ {
+ var val = query.IsSeries.Value;
+ recordings = recordings.Where(i => i.IsSeries == val);
+ }
+
+ if (query.IsKids.HasValue)
+ {
+ var val = query.IsKids.Value;
+ recordings = recordings.Where(i => i.IsKids == val);
+ }
+
+ if (query.IsSports.HasValue)
+ {
+ var val = query.IsSports.Value;
+ recordings = recordings.Where(i => i.IsSports == val);
+ }
+
if (!string.IsNullOrEmpty(query.SeriesTimerId))
{
var guid = new Guid(query.SeriesTimerId);
@@ -1524,7 +1692,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
public async Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, List<ItemFields> fields, User user = null)
{
- var recordingTuples = new List<Tuple<BaseItemDto, string, string>>();
+ var recordingTuples = new List<Tuple<BaseItemDto, string, string, string>>();
foreach (var tuple in tuples)
{
@@ -1592,7 +1760,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv
dto.ServiceName = serviceName;
}
- recordingTuples.Add(new Tuple<BaseItemDto, string, string>(dto, serviceName, program.ExternalId));
+ recordingTuples.Add(new Tuple<BaseItemDto, string, string, string>(dto, serviceName, program.ExternalId, program.ExternalSeriesIdLegacy));
}
await AddRecordingInfo(recordingTuples, CancellationToken.None).ConfigureAwait(false);
@@ -1867,6 +2035,56 @@ namespace MediaBrowser.Server.Implementations.LiveTv
return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
}
+ private async Task<QueryResult<SeriesTimerInfo>> GetSeriesTimersInternal(SeriesTimerQuery query, CancellationToken cancellationToken)
+ {
+ var tasks = _services.Select(async i =>
+ {
+ try
+ {
+ var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
+ return recs.Select(r =>
+ {
+ r.ServiceName = i.Name;
+ return new Tuple<SeriesTimerInfo, ILiveTvService>(r, i);
+ });
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error getting recordings", ex);
+ return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
+ }
+ });
+ var results = await Task.WhenAll(tasks).ConfigureAwait(false);
+ var timers = results.SelectMany(i => i.ToList());
+
+ if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
+ {
+ timers = query.SortOrder == SortOrder.Descending ?
+ timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
+ timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
+ }
+ else
+ {
+ timers = query.SortOrder == SortOrder.Descending ?
+ timers.OrderByStringDescending(i => i.Item1.Name) :
+ timers.OrderByString(i => i.Item1.Name);
+ }
+
+ var returnArray = timers
+ .Select(i =>
+ {
+ return i.Item1;
+
+ })
+ .ToArray();
+
+ return new QueryResult<SeriesTimerInfo>
+ {
+ Items = returnArray,
+ TotalRecordCount = returnArray.Length
+ };
+ }
+
public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
{
var tasks = _services.Select(async i =>
@@ -1950,16 +2168,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv
dto.Number = channel.Number;
dto.ChannelNumber = channel.Number;
dto.ChannelType = channel.ChannelType;
- dto.ServiceName = GetService(channel).Name;
+ dto.ServiceName = channel.ServiceName;
if (options.Fields.Contains(ItemFields.MediaSources))
{
dto.MediaSources = channel.GetMediaSources(true).ToList();
}
- var channelIdString = channel.Id.ToString("N");
if (options.AddCurrentProgram)
{
+ var channelIdString = channel.Id.ToString("N");
var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString));
if (currentProgram != null)
@@ -2091,6 +2309,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv
public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
{
+ var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
+
+ if (!registration.IsValid)
+ {
+ _logger.Info("Creating series recordings requires an active Emby Premiere subscription.");
+ return;
+ }
+
var service = GetService(timer.ServiceName);
var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
@@ -2263,9 +2489,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
internal bool IsChannel;
}
- public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
+ public async Task CloseLiveStream(string id)
{
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false);
try
{
@@ -2280,12 +2506,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
id = parts[1];
- LiveStreamData data;
- _openStreams.TryRemove(id, out data);
-
_logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
- await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
+ await service.CloseLiveStream(id, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -2319,7 +2542,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv
Dispose(true);
}
- private readonly object _disposeLock = new object();
private bool _isDisposed = false;
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
@@ -2330,18 +2552,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv
if (dispose)
{
_isDisposed = true;
-
- lock (_disposeLock)
- {
- foreach (var stream in _openStreams.Values.ToList())
- {
- var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
-
- Task.WaitAll(task);
- }
-
- _openStreams.Clear();
- }
}
}
@@ -2653,33 +2863,28 @@ namespace MediaBrowser.Server.Implementations.LiveTv
}
}
- public Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature)
+ public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
{
- ILiveTvService service;
-
- if (string.IsNullOrWhiteSpace(programId))
+ if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
{
- var channel = GetInternalChannel(channelId);
- service = GetService(channel);
+ feature = "embytvseriesrecordings";
}
- else
- {
- var program = GetInternalProgram(programId);
- service = GetService(program);
- }
-
- var hasRegistration = service as IHasRegistrationInfo;
- if (hasRegistration != null)
+ if (string.Equals(feature, "dvr-l", StringComparison.OrdinalIgnoreCase))
{
- return hasRegistration.GetRegistrationInfo(feature);
+ var config = GetConfiguration();
+ if (config.TunerHosts.Count(i => i.IsEnabled) > 0 &&
+ config.ListingProviders.Count(i => (i.EnableAllTuners || i.EnabledTuners.Length > 0) && string.Equals(i.Type, SchedulesDirect.TypeName, StringComparison.OrdinalIgnoreCase)) > 0)
+ {
+ return Task.FromResult(new MBRegistrationRecord
+ {
+ IsRegistered = true,
+ IsValid = true
+ });
+ }
}
- return Task.FromResult(new MBRegistrationRecord
- {
- IsValid = true,
- IsRegistered = true
- });
+ return _security.GetRegistrationStatus(feature);
}
public List<NameValuePair> GetSatIniMappings()
diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
index cdba1873e..aacc0c22b 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
@@ -204,9 +204,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv
}
}
- public Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken)
+ public Task CloseMediaSource(string liveStreamId)
{
- return _liveTvManager.CloseLiveStream(liveStreamId, cancellationToken);
+ return _liveTvManager.CloseLiveStream(liveStreamId);
}
}
}
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
index 9bb5b4fd7..a4236763f 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs
@@ -6,9 +6,11 @@ using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Serialization;
@@ -17,7 +19,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
{
public abstract class BaseTunerHost
{
- protected readonly IConfigurationManager Config;
+ protected readonly IServerConfigurationManager Config;
protected readonly ILogger Logger;
protected IJsonSerializer JsonSerializer;
protected readonly IMediaEncoder MediaEncoder;
@@ -25,7 +27,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
private readonly ConcurrentDictionary<string, ChannelCache> _channelCache =
new ConcurrentDictionary<string, ChannelCache>(StringComparer.OrdinalIgnoreCase);
- protected BaseTunerHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
+ protected BaseTunerHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
{
Config = config;
Logger = logger;
@@ -71,7 +73,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
.ToList();
}
- public async Task<IEnumerable<ChannelInfo>> GetChannels(CancellationToken cancellationToken)
+ public async Task<IEnumerable<ChannelInfo>> GetChannels(bool enableCache, CancellationToken cancellationToken)
{
var list = new List<ChannelInfo>();
@@ -81,7 +83,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
{
try
{
- var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
+ var channels = await GetChannels(host, enableCache, cancellationToken).ConfigureAwait(false);
var newChannels = channels.Where(i => !list.Any(l => string.Equals(i.Id, l.Id, StringComparison.OrdinalIgnoreCase))).ToList();
list.AddRange(newChannels);
@@ -124,12 +126,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
foreach (var host in hostsWithChannel)
{
- var resourcePool = GetLock(host.Url);
- Logger.Debug("GetChannelStreamMediaSources - Waiting on tuner resource pool");
-
- await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
- Logger.Debug("GetChannelStreamMediaSources - Unlocked resource pool");
-
try
{
// Check to make sure the tuner is available
@@ -155,89 +151,63 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
{
Logger.Error("Error opening tuner", ex);
}
- finally
- {
- resourcePool.Release();
- }
}
}
return new List<MediaSourceInfo>();
}
- protected abstract Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken);
+ protected abstract Task<LiveStream> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken);
- public async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
+ public async Task<LiveStream> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
{
- if (IsValidChannelId(channelId))
+ if (!IsValidChannelId(channelId))
{
- var hosts = GetTunerHosts();
-
- var hostsWithChannel = new List<TunerHostInfo>();
+ throw new FileNotFoundException();
+ }
- foreach (var host in hosts)
- {
- if (string.IsNullOrWhiteSpace(streamId))
- {
- try
- {
- var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
+ var hosts = GetTunerHosts();
- if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
- {
- hostsWithChannel.Add(host);
- }
- }
- catch (Exception ex)
- {
- Logger.Error("Error getting channels", ex);
- }
- }
- else if (streamId.StartsWith(host.Id, StringComparison.OrdinalIgnoreCase))
- {
- hostsWithChannel = new List<TunerHostInfo> { host };
- streamId = streamId.Substring(host.Id.Length);
- break;
- }
- }
+ var hostsWithChannel = new List<TunerHostInfo>();
- foreach (var host in hostsWithChannel)
+ foreach (var host in hosts)
+ {
+ if (string.IsNullOrWhiteSpace(streamId))
{
- var resourcePool = GetLock(host.Url);
- Logger.Debug("GetChannelStream - Waiting on tuner resource pool");
- await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
- Logger.Debug("GetChannelStream - Unlocked resource pool");
try
{
- // Check to make sure the tuner is available
- // If there's only one tuner, don't bother with the check and just let the tuner be the one to throw an error
- // If a streamId is specified then availibility has already been checked in GetChannelStreamMediaSources
- if (string.IsNullOrWhiteSpace(streamId) && hostsWithChannel.Count > 1)
- {
- if (!await IsAvailable(host, channelId, cancellationToken).ConfigureAwait(false))
- {
- Logger.Error("Tuner is not currently available");
- resourcePool.Release();
- continue;
- }
- }
-
- var stream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false);
+ var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
- if (EnableMediaProbing)
+ if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
{
- await AddMediaInfo(stream, false, resourcePool, cancellationToken).ConfigureAwait(false);
+ hostsWithChannel.Add(host);
}
-
- return new Tuple<MediaSourceInfo, SemaphoreSlim>(stream, resourcePool);
}
catch (Exception ex)
{
- Logger.Error("Error opening tuner", ex);
-
- resourcePool.Release();
+ Logger.Error("Error getting channels", ex);
}
}
+ else if (streamId.StartsWith(host.Id, StringComparison.OrdinalIgnoreCase))
+ {
+ hostsWithChannel = new List<TunerHostInfo> { host };
+ streamId = streamId.Substring(host.Id.Length);
+ break;
+ }
+ }
+
+ foreach (var host in hostsWithChannel)
+ {
+ try
+ {
+ var liveStream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false);
+ await liveStream.Open(cancellationToken).ConfigureAwait(false);
+ return liveStream;
+ }
+ catch (Exception ex)
+ {
+ Logger.Error("Error opening tuner", ex);
+ }
}
throw new LiveTvConflictException();
@@ -263,37 +233,23 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
protected abstract Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken);
- /// <summary>
- /// The _semaphoreLocks
- /// </summary>
- private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
- /// <summary>
- /// Gets the lock.
- /// </summary>
- /// <param name="url">The filename.</param>
- /// <returns>System.Object.</returns>
- private SemaphoreSlim GetLock(string url)
+ private async Task AddMediaInfo(LiveStream stream, bool isAudio, CancellationToken cancellationToken)
{
- return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
- }
+ //await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
- private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
- {
- await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
+ //try
+ //{
+ // await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false);
- try
- {
- await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false);
-
- // Leave the resource locked. it will be released upstream
- }
- catch (Exception)
- {
- // Release the resource if there's some kind of failure.
- resourcePool.Release();
+ // // Leave the resource locked. it will be released upstream
+ //}
+ //catch (Exception)
+ //{
+ // // Release the resource if there's some kind of failure.
+ // resourcePool.Release();
- throw;
- }
+ // throw;
+ //}
}
private async Task AddMediaInfoInternal(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs
index 9ba1c60cc..ef37e3b35 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunDiscovery.cs
@@ -10,6 +10,7 @@ using System;
using System.Linq;
using System.Threading;
using MediaBrowser.Common.Net;
+using MediaBrowser.Model.Events;
using MediaBrowser.Model.Serialization;
namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
@@ -39,13 +40,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
_deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
}
- void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
+ void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
string server = null;
- if (e.Headers.TryGetValue("SERVER", out server) && server.IndexOf("HDHomeRun", StringComparison.OrdinalIgnoreCase) != -1)
+ var info = e.Argument;
+
+ if (info.Headers.TryGetValue("SERVER", out server) && server.IndexOf("HDHomeRun", StringComparison.OrdinalIgnoreCase) != -1)
{
string location;
- if (e.Headers.TryGetValue("Location", out location))
+ if (info.Headers.TryGetValue("Location", out location))
{
//_logger.Debug("HdHomerun found at {0}", location);
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
index fd4775938..14ae45228 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
@@ -14,7 +14,10 @@ using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
+using CommonIO;
using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Net;
@@ -24,11 +27,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
public class HdHomerunHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
{
private readonly IHttpClient _httpClient;
+ private readonly IFileSystem _fileSystem;
+ private readonly IServerApplicationHost _appHost;
- public HdHomerunHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IHttpClient httpClient)
+ public HdHomerunHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IHttpClient httpClient, IFileSystem fileSystem, IServerApplicationHost appHost)
: base(config, logger, jsonSerializer, mediaEncoder)
{
_httpClient = httpClient;
+ _fileSystem = fileSystem;
+ _appHost = appHost;
}
public string Name
@@ -60,14 +67,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return id;
}
- public string ApplyDuration(string streamPath, TimeSpan duration)
- {
- streamPath += streamPath.IndexOf('?') == -1 ? "?" : "&";
- streamPath += "duration=" + Convert.ToInt32(duration.TotalSeconds).ToString(CultureInfo.InvariantCulture);
-
- return streamPath;
- }
-
private async Task<IEnumerable<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken)
{
var options = new HttpRequestOptions
@@ -105,8 +104,18 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
});
}
+ private Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>();
private async Task<string> GetModelInfo(TunerHostInfo info, CancellationToken cancellationToken)
{
+ lock (_modelCache)
+ {
+ DiscoverResponse response;
+ if (_modelCache.TryGetValue(info.Url, out response))
+ {
+ return response.ModelNumber;
+ }
+ }
+
try
{
using (var stream = await _httpClient.Get(new HttpRequestOptions()
@@ -120,6 +129,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
var response = JsonSerializer.DeserializeFromStream<DiscoverResponse>(stream);
+ lock (_modelCache)
+ {
+ _modelCache[info.Id] = response;
+ }
+
return response.ModelNumber;
}
}
@@ -127,8 +141,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{
if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
{
+ var defaultValue = "HDHR";
// HDHR4 doesn't have this api
- return "HDHR";
+ lock (_modelCache)
+ {
+ _modelCache[info.Id] = new DiscoverResponse
+ {
+ ModelNumber = defaultValue
+ };
+ }
+ return defaultValue;
}
throw;
@@ -319,18 +341,21 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
videoBitrate = 1000000;
}
- if (string.IsNullOrWhiteSpace(videoCodec))
+ var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false);
+ var channel = channels.FirstOrDefault(i => string.Equals(i.Number, channelId, StringComparison.OrdinalIgnoreCase));
+ if (channel != null)
{
- var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false);
- var channel = channels.FirstOrDefault(i => string.Equals(i.Number, channelId, StringComparison.OrdinalIgnoreCase));
- if (channel != null)
+ if (string.IsNullOrWhiteSpace(videoCodec))
{
videoCodec = channel.VideoCodec;
- audioCodec = channel.AudioCodec;
+ }
+ audioCodec = channel.AudioCodec;
+ if (!videoBitrate.HasValue)
+ {
videoBitrate = (channel.IsHD ?? true) ? 15000000 : 2000000;
- audioBitrate = (channel.IsHD ?? true) ? 448000 : 192000;
}
+ audioBitrate = (channel.IsHD ?? true) ? 448000 : 192000;
}
// normalize
@@ -352,6 +377,13 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
url += "?transcode=" + profile;
}
+ var id = profile;
+ if (string.IsNullOrWhiteSpace(id))
+ {
+ id = "native";
+ }
+ id += "_" + url.GetMD5().ToString("N");
+
var mediaSource = new MediaSourceInfo
{
Path = url,
@@ -380,14 +412,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
BitRate = audioBitrate
}
},
- RequiresOpening = false,
+ RequiresOpening = true,
RequiresClosing = false,
BufferMs = 0,
Container = "ts",
- Id = profile,
- SupportsDirectPlay = true,
- SupportsDirectStream = false,
- SupportsTranscoding = true
+ Id = id,
+ SupportsDirectPlay = false,
+ SupportsDirectStream = true,
+ SupportsTranscoding = true,
+ IsInfiniteStream = true
};
return mediaSource;
@@ -417,18 +450,21 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
try
{
- string model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false);
- model = model ?? string.Empty;
-
- if (info.AllowHWTranscoding && (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1))
+ if (info.AllowHWTranscoding)
{
- list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false));
+ string model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false);
+ model = model ?? string.Empty;
- list.Add(await GetMediaSource(info, hdhrId, "internet540").ConfigureAwait(false));
- list.Add(await GetMediaSource(info, hdhrId, "internet480").ConfigureAwait(false));
- list.Add(await GetMediaSource(info, hdhrId, "internet360").ConfigureAwait(false));
- list.Add(await GetMediaSource(info, hdhrId, "internet240").ConfigureAwait(false));
- list.Add(await GetMediaSource(info, hdhrId, "mobile").ConfigureAwait(false));
+ if ((model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1))
+ {
+ list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false));
+
+ list.Add(await GetMediaSource(info, hdhrId, "internet540").ConfigureAwait(false));
+ list.Add(await GetMediaSource(info, hdhrId, "internet480").ConfigureAwait(false));
+ list.Add(await GetMediaSource(info, hdhrId, "internet360").ConfigureAwait(false));
+ list.Add(await GetMediaSource(info, hdhrId, "internet240").ConfigureAwait(false));
+ list.Add(await GetMediaSource(info, hdhrId, "mobile").ConfigureAwait(false));
+ }
}
}
catch
@@ -449,9 +485,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase);
}
- protected override async Task<MediaSourceInfo> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
+ protected override async Task<LiveStream> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
{
- Logger.Info("GetChannelStream: channel id: {0}. stream id: {1}", channelId, streamId ?? string.Empty);
+ var profile = streamId.Split('_')[0];
+
+ Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelId, streamId, profile);
if (!channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase))
{
@@ -459,7 +497,27 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
var hdhrId = GetHdHrIdFromChannelId(channelId);
- return await GetMediaSource(info, hdhrId, streamId).ConfigureAwait(false);
+ var mediaSource = await GetMediaSource(info, hdhrId, profile).ConfigureAwait(false);
+
+ var liveStream = new HdHomerunLiveStream(mediaSource, _fileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost);
+ if (info.AllowHWTranscoding)
+ {
+ var model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false);
+
+ if ((model ?? string.Empty).IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ liveStream.EnableStreamSharing = !info.AllowHWTranscoding;
+ }
+ else
+ {
+ liveStream.EnableStreamSharing = true;
+ }
+ }
+ else
+ {
+ liveStream.EnableStreamSharing = true;
+ }
+ return liveStream;
}
public async Task Validate(TunerHostInfo info)
@@ -469,6 +527,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
return;
}
+ lock (_modelCache)
+ {
+ _modelCache.Clear();
+ }
+
try
{
// Test it by pulling down the lineup
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunLiveStream.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunLiveStream.cs
new file mode 100644
index 000000000..2cdd0571b
--- /dev/null
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunLiveStream.cs
@@ -0,0 +1,166 @@
+using System;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using CommonIO;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Logging;
+using MediaBrowser.Model.MediaInfo;
+using MediaBrowser.Server.Implementations.LiveTv.EmbyTV;
+
+namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
+{
+ public class HdHomerunLiveStream : LiveStream
+ {
+ private readonly ILogger _logger;
+ private readonly IHttpClient _httpClient;
+ private readonly IFileSystem _fileSystem;
+ private readonly IServerApplicationPaths _appPaths;
+ private readonly IServerApplicationHost _appHost;
+
+ private readonly CancellationTokenSource _liveStreamCancellationTokenSource = new CancellationTokenSource();
+ private readonly TaskCompletionSource<bool> _liveStreamTaskCompletionSource = new TaskCompletionSource<bool>();
+
+ public HdHomerunLiveStream(MediaSourceInfo mediaSource, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost)
+ : base(mediaSource)
+ {
+ _fileSystem = fileSystem;
+ _httpClient = httpClient;
+ _logger = logger;
+ _appPaths = appPaths;
+ _appHost = appHost;
+ }
+
+ protected override async Task OpenInternal(CancellationToken openCancellationToken)
+ {
+ _liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
+
+ var mediaSource = OriginalMediaSource;
+
+ var url = mediaSource.Path;
+ var tempFile = Path.Combine(_appPaths.TranscodingTempPath, Guid.NewGuid().ToString("N") + ".ts");
+ Directory.CreateDirectory(Path.GetDirectoryName(tempFile));
+
+ _logger.Info("Opening HDHR Live stream from {0} to {1}", url, tempFile);
+
+ var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read);
+
+ var taskCompletionSource = new TaskCompletionSource<bool>();
+
+ StartStreamingToTempFile(output, tempFile, url, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
+
+ //OpenedMediaSource.Protocol = MediaProtocol.File;
+ //OpenedMediaSource.Path = tempFile;
+ //OpenedMediaSource.ReadAtNativeFramerate = true;
+
+ OpenedMediaSource.Path = _appHost.GetLocalApiUrl("localhost") + "/LiveTv/LiveStreamFiles/" + Path.GetFileNameWithoutExtension(tempFile) + "/stream.ts";
+ OpenedMediaSource.Protocol = MediaProtocol.Http;
+ OpenedMediaSource.SupportsDirectPlay = false;
+ OpenedMediaSource.SupportsDirectStream = true;
+ OpenedMediaSource.SupportsTranscoding = true;
+
+ await taskCompletionSource.Task.ConfigureAwait(false);
+
+ //await Task.Delay(5000).ConfigureAwait(false);
+ }
+
+ public override Task Close()
+ {
+ _logger.Info("Closing HDHR live stream");
+ _liveStreamCancellationTokenSource.Cancel();
+
+ return _liveStreamTaskCompletionSource.Task;
+ }
+
+ private async Task StartStreamingToTempFile(Stream outputStream, string tempFilePath, string url, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
+ {
+ await Task.Run(async () =>
+ {
+ using (outputStream)
+ {
+ var isFirstAttempt = true;
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ using (var response = await _httpClient.SendAsync(new HttpRequestOptions
+ {
+ Url = url,
+ CancellationToken = cancellationToken,
+ BufferContent = false
+
+ }, "GET").ConfigureAwait(false))
+ {
+ _logger.Info("Opened HDHR stream from {0}", url);
+
+ if (!cancellationToken.IsCancellationRequested)
+ {
+ _logger.Info("Beginning DirectRecorder.CopyUntilCancelled");
+
+ Action onStarted = null;
+ if (isFirstAttempt)
+ {
+ onStarted = () => openTaskCompletionSource.TrySetResult(true);
+ }
+ await DirectRecorder.CopyUntilCancelled(response.Content, outputStream, onStarted, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ if (isFirstAttempt)
+ {
+ _logger.ErrorException("Error opening live stream:", ex);
+ openTaskCompletionSource.TrySetException(ex);
+ break;
+ }
+
+ _logger.ErrorException("Error copying live stream, will reopen", ex);
+ }
+
+ isFirstAttempt = false;
+ }
+ }
+
+ _liveStreamTaskCompletionSource.TrySetResult(true);
+
+ DeleteTempFile(tempFilePath);
+
+ }).ConfigureAwait(false);
+ }
+
+ private async void DeleteTempFile(string path)
+ {
+ for (var i = 0; i < 10; i++)
+ {
+ try
+ {
+ File.Delete(path);
+ return;
+ }
+ catch (FileNotFoundException)
+ {
+ return;
+ }
+ catch (DirectoryNotFoundException)
+ {
+ return;
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error deleting temp file {0}", ex, path);
+ }
+
+ await Task.Delay(1000).ConfigureAwait(false);
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
index 5c508aacd..b03feefe4 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
@@ -13,8 +13,10 @@ using System.Threading;
using System.Threading.Tasks;
using CommonIO;
using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Serialization;
+using MediaBrowser.Server.Implementations.LiveTv.EmbyTV;
namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
{
@@ -23,7 +25,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
private readonly IFileSystem _fileSystem;
private readonly IHttpClient _httpClient;
- public M3UTunerHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IHttpClient httpClient)
+ public M3UTunerHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IHttpClient httpClient)
: base(config, logger, jsonSerializer, mediaEncoder)
{
_fileSystem = fileSystem;
@@ -63,11 +65,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
return Task.FromResult(list);
}
- protected override async Task<MediaSourceInfo> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
+ protected override async Task<LiveStream> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
{
var sources = await GetChannelStreamMediaSources(info, channelId, cancellationToken).ConfigureAwait(false);
- return sources.First();
+ var liveStream = new LiveStream(sources.First());
+ return liveStream;
}
public async Task Validate(TunerHostInfo info)
@@ -136,7 +139,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
RequiresOpening = false,
RequiresClosing = false,
- ReadAtNativeFramerate = false
+ ReadAtNativeFramerate = false,
+
+ Id = channel.Path.GetMD5().ToString("N"),
+ IsInfiniteStream = true
};
return new List<MediaSourceInfo> { mediaSource };
@@ -148,10 +154,5 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
{
return Task.FromResult(true);
}
-
- public string ApplyDuration(string streamPath, TimeSpan duration)
- {
- return streamPath;
- }
}
}
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs
index cb0e573da..a0b8ef5f7 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs
@@ -14,6 +14,7 @@ using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Extensions;
using System.Xml.Linq;
+using MediaBrowser.Model.Events;
namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
{
@@ -50,18 +51,20 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
_deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered;
}
- void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e)
+ void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs<UpnpDeviceInfo> e)
{
+ var info = e.Argument;
+
string st = null;
string nt = null;
- e.Headers.TryGetValue("ST", out st);
- e.Headers.TryGetValue("NT", out nt);
+ info.Headers.TryGetValue("ST", out st);
+ info.Headers.TryGetValue("NT", out nt);
if (string.Equals(st, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase) ||
string.Equals(nt, "urn:ses-com:device:SatIPServer:1", StringComparison.OrdinalIgnoreCase))
{
string location;
- if (e.Headers.TryGetValue("Location", out location) && !string.IsNullOrWhiteSpace(location))
+ if (info.Headers.TryGetValue("Location", out location) && !string.IsNullOrWhiteSpace(location))
{
_logger.Debug("SAT IP found at {0}", location);
diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs
index b1e349a86..81deb2995 100644
--- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs
+++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs
@@ -8,6 +8,7 @@ using CommonIO;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.Dto;
@@ -16,6 +17,7 @@ using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
+using MediaBrowser.Server.Implementations.LiveTv.EmbyTV;
namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
{
@@ -24,7 +26,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
private readonly IFileSystem _fileSystem;
private readonly IHttpClient _httpClient;
- public SatIpHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IHttpClient httpClient)
+ public SatIpHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IHttpClient httpClient)
: base(config, logger, jsonSerializer, mediaEncoder)
{
_fileSystem = fileSystem;
@@ -113,11 +115,13 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp
return new List<MediaSourceInfo>();
}
- protected override async Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken)
+ protected override async Task<LiveStream> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken)
{
var sources = await GetChannelStreamMediaSources(tuner, channelId, cancellationToken).ConfigureAwait(false);
- return sources.First();
+ var liveStream = new LiveStream(sources.First());
+
+ return liveStream;
}
protected override async Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Server.Implementations/Localization/Ratings/de.txt b/MediaBrowser.Server.Implementations/Localization/Ratings/de.txt
index 723807509..ad1f18619 100644
--- a/MediaBrowser.Server.Implementations/Localization/Ratings/de.txt
+++ b/MediaBrowser.Server.Implementations/Localization/Ratings/de.txt
@@ -1,5 +1,10 @@
DE-0,1
+FSK-0,1
DE-6,5
+FSK-6,5
DE-12,7
+FSK-12,7
DE-16,8
+FSK-16,8
DE-18,9
+FSK-18,9 \ No newline at end of file
diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj
index 9a92cf896..12691a69b 100644
--- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj
+++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj
@@ -69,12 +69,12 @@
<Reference Include="ServiceStack.Api.Swagger">
<HintPath>..\ThirdParty\ServiceStack\ServiceStack.Api.Swagger.dll</HintPath>
</Reference>
- <Reference Include="SimpleInjector, Version=3.2.0.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
- <HintPath>..\packages\SimpleInjector.3.2.0\lib\net45\SimpleInjector.dll</HintPath>
+ <Reference Include="SimpleInjector, Version=3.2.2.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
+ <HintPath>..\packages\SimpleInjector.3.2.2\lib\net45\SimpleInjector.dll</HintPath>
<Private>True</Private>
</Reference>
- <Reference Include="SocketHttpListener, Version=1.0.6063.4624, Culture=neutral, processorArchitecture=MSIL">
- <HintPath>..\packages\SocketHttpListener.1.0.0.39\lib\net45\SocketHttpListener.dll</HintPath>
+ <Reference Include="SocketHttpListener, Version=1.0.6109.26162, Culture=neutral, processorArchitecture=MSIL">
+ <HintPath>..\packages\SocketHttpListener.1.0.0.40\lib\net45\SocketHttpListener.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
@@ -105,9 +105,6 @@
<Reference Include="UniversalDetector">
<HintPath>..\ThirdParty\UniversalDetector\UniversalDetector.dll</HintPath>
</Reference>
- <Reference Include="Mono.Nat">
- <HintPath>..\packages\Mono.Nat.1.2.24.0\lib\net40\Mono.Nat.dll</HintPath>
- </Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\SharedVersion.cs">
@@ -124,7 +121,6 @@
<Compile Include="Channels\RefreshChannelsScheduledTask.cs" />
<Compile Include="Collections\CollectionManager.cs" />
<Compile Include="Collections\CollectionsDynamicFolder.cs" />
- <Compile Include="Collections\ManualCollectionsFolder.cs" />
<Compile Include="Collections\CollectionImageProvider.cs" />
<Compile Include="Configuration\ServerConfigurationManager.cs" />
<Compile Include="Connect\ConnectData.cs" />
@@ -245,6 +241,7 @@
<Compile Include="LiveTv\TunerHosts\BaseTunerHost.cs" />
<Compile Include="LiveTv\TunerHosts\HdHomerun\HdHomerunHost.cs" />
<Compile Include="LiveTv\TunerHosts\HdHomerun\HdHomerunDiscovery.cs" />
+ <Compile Include="LiveTv\TunerHosts\HdHomerun\HdHomerunLiveStream.cs" />
<Compile Include="LiveTv\TunerHosts\M3uParser.cs" />
<Compile Include="LiveTv\TunerHosts\M3UTunerHost.cs" />
<Compile Include="LiveTv\ProgramImageProvider.cs" />
@@ -391,6 +388,10 @@
<Project>{7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}</Project>
<Name>MediaBrowser.Model</Name>
</ProjectReference>
+ <ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj">
+ <Project>{d7453b88-2266-4805-b39b-2b5a2a33e1ba}</Project>
+ <Name>Mono.Nat</Name>
+ </ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Localization\Ratings\us.txt" />
diff --git a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs
index 11338df6d..06c109dfc 100644
--- a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs
+++ b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs
@@ -149,18 +149,20 @@ namespace MediaBrowser.Server.Implementations.MediaEncoder
}
}
- // Add some time for the first chapter to make sure we don't end up with a black image
- var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
+ try
+ {
+ // Add some time for the first chapter to make sure we don't end up with a black image
+ var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
- var protocol = MediaProtocol.File;
+ var protocol = MediaProtocol.File;
- var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, video.PlayableStreamFileNames);
+ var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, protocol, null, video.PlayableStreamFileNames);
- try
- {
- _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
+ _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
+
+ var container = video.Container;
- var tempFile = await _encoder.ExtractVideoImage(inputPath, protocol, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
+ var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false);
File.Copy(tempFile, path, true);
try
@@ -178,7 +180,7 @@ namespace MediaBrowser.Server.Implementations.MediaEncoder
}
catch (Exception ex)
{
- _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", inputPath));
+ _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path));
success = false;
break;
}
diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs
index 5ece3dd82..c843ab596 100644
--- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs
+++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs
@@ -270,6 +270,7 @@ namespace MediaBrowser.Server.Implementations.Persistence
_connection.AddColumn(Logger, "TypedBaseItems", "SeasonId", "GUID");
_connection.AddColumn(Logger, "TypedBaseItems", "SeriesId", "GUID");
_connection.AddColumn(Logger, "TypedBaseItems", "SeriesSortName", "Text");
+ _connection.AddColumn(Logger, "TypedBaseItems", "ExternalSeriesId", "Text");
_connection.AddColumn(Logger, "UserDataKeys", "Priority", "INT");
_connection.AddColumn(Logger, "ItemValues", "CleanValue", "Text");
@@ -412,7 +413,9 @@ namespace MediaBrowser.Server.Implementations.Persistence
"SeriesId",
"SeriesSortName",
"PresentationUniqueKey",
- "InheritedParentalRatingValue"
+ "InheritedParentalRatingValue",
+ "InheritedTags",
+ "ExternalSeriesId"
};
private readonly string[] _mediaStreamSaveColumns =
@@ -534,7 +537,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
"SeasonName",
"SeasonId",
"SeriesId",
- "SeriesSortName"
+ "SeriesSortName",
+ "ExternalSeriesId"
};
_saveItemCommand = _connection.CreateCommand();
_saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values (";
@@ -974,6 +978,8 @@ namespace MediaBrowser.Server.Implementations.Persistence
_saveItemCommand.GetParameter(index++).Value = null;
}
+ _saveItemCommand.GetParameter(index++).Value = item.ExternalSeriesId;
+
_saveItemCommand.Transaction = transaction;
_saveItemCommand.ExecuteNonQuery();
@@ -1459,6 +1465,18 @@ namespace MediaBrowser.Server.Implementations.Persistence
}
index++;
+ if (!reader.IsDBNull(index))
+ {
+ item.InheritedTags = reader.GetString(index).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
+ }
+ index++;
+
+ if (!reader.IsDBNull(index))
+ {
+ item.ExternalSeriesId = reader.GetString(index);
+ }
+ index++;
+
return item;
}
@@ -1723,28 +1741,28 @@ namespace MediaBrowser.Server.Implementations.Persistence
return true;
}
- if (query.SortBy != null && query.SortBy.Length > 0)
+ var sortingFields = query.SortBy.ToList();
+ sortingFields.AddRange(query.OrderBy.Select(i => i.Item1));
+
+ if (sortingFields.Contains(ItemSortBy.IsFavoriteOrLiked, StringComparer.OrdinalIgnoreCase))
{
- if (query.SortBy.Contains(ItemSortBy.IsFavoriteOrLiked, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
- if (query.SortBy.Contains(ItemSortBy.IsPlayed, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
- if (query.SortBy.Contains(ItemSortBy.IsUnplayed, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
- if (query.SortBy.Contains(ItemSortBy.PlayCount, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
- if (query.SortBy.Contains(ItemSortBy.DatePlayed, StringComparer.OrdinalIgnoreCase))
- {
- return true;
- }
+ return true;
+ }
+ if (sortingFields.Contains(ItemSortBy.IsPlayed, StringComparer.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ if (sortingFields.Contains(ItemSortBy.IsUnplayed, StringComparer.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ if (sortingFields.Contains(ItemSortBy.PlayCount, StringComparer.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ if (sortingFields.Contains(ItemSortBy.DatePlayed, StringComparer.OrdinalIgnoreCase))
+ {
+ return true;
}
if (query.IsFavoriteOrLiked.HasValue)
@@ -2144,34 +2162,41 @@ namespace MediaBrowser.Server.Implementations.Persistence
private string GetOrderByText(InternalItemsQuery query)
{
+ var orderBy = query.OrderBy.ToList();
+ var enableOrderInversion = true;
+
+ if (orderBy.Count == 0)
+ {
+ orderBy.AddRange(query.SortBy.Select(i => new Tuple<string, SortOrder>(i, query.SortOrder)));
+ }
+ else
+ {
+ enableOrderInversion = false;
+ }
+
if (query.SimilarTo != null)
{
- if (query.SortBy == null || query.SortBy.Length == 0)
+ if (orderBy.Count == 0)
{
- if (query.User != null)
- {
- query.SortBy = new[] { "SimilarityScore", ItemSortBy.Random };
- }
- else
- {
- query.SortBy = new[] { "SimilarityScore", ItemSortBy.Random };
- }
+ orderBy.Add(new Tuple<string, SortOrder>("SimilarityScore", SortOrder.Descending));
+ orderBy.Add(new Tuple<string, SortOrder>(ItemSortBy.Random, SortOrder.Ascending));
query.SortOrder = SortOrder.Descending;
+ enableOrderInversion = false;
}
}
- if (query.SortBy == null || query.SortBy.Length == 0)
+ query.OrderBy = orderBy;
+
+ if (orderBy.Count == 0)
{
return string.Empty;
}
- var isAscending = query.SortOrder != SortOrder.Descending;
-
- return " ORDER BY " + string.Join(",", query.SortBy.Select(i =>
+ return " ORDER BY " + string.Join(",", orderBy.Select(i =>
{
- var columnMap = MapOrderByField(i, query);
- var columnAscending = isAscending;
- if (columnMap.Item2)
+ var columnMap = MapOrderByField(i.Item1, query);
+ var columnAscending = i.Item2 == SortOrder.Ascending;
+ if (columnMap.Item2 && enableOrderInversion)
{
columnAscending = !columnAscending;
}
@@ -2523,38 +2548,111 @@ namespace MediaBrowser.Server.Implementations.Persistence
whereClauses.Add("IsOffline=@IsOffline");
cmd.Parameters.Add(cmd, "@IsOffline", DbType.Boolean).Value = query.IsOffline;
}
- if (query.IsMovie.HasValue)
+
+ var exclusiveProgramAttribtues = !(query.IsMovie ?? true) ||
+ !(query.IsSports ?? true) ||
+ !(query.IsKids ?? true) ||
+ !(query.IsNews ?? true) ||
+ !(query.IsSeries ?? true);
+
+ if (exclusiveProgramAttribtues)
{
- var alternateTypes = new List<string>();
- if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Movie).Name))
+ if (query.IsMovie.HasValue)
+ {
+ var alternateTypes = new List<string>();
+ if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Movie).Name))
+ {
+ alternateTypes.Add(typeof(Movie).FullName);
+ }
+ if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Trailer).Name))
+ {
+ alternateTypes.Add(typeof(Trailer).FullName);
+ }
+
+ if (alternateTypes.Count == 0)
+ {
+ whereClauses.Add("IsMovie=@IsMovie");
+ cmd.Parameters.Add(cmd, "@IsMovie", DbType.Boolean).Value = query.IsMovie;
+ }
+ else
+ {
+ whereClauses.Add("(IsMovie is null OR IsMovie=@IsMovie)");
+ cmd.Parameters.Add(cmd, "@IsMovie", DbType.Boolean).Value = query.IsMovie;
+ }
+ }
+ if (query.IsSeries.HasValue)
{
- alternateTypes.Add(typeof(Movie).FullName);
+ whereClauses.Add("IsSeries=@IsSeries");
+ cmd.Parameters.Add(cmd, "@IsSeries", DbType.Boolean).Value = query.IsSeries;
}
- if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Trailer).Name))
+ if (query.IsNews.HasValue)
{
- alternateTypes.Add(typeof(Trailer).FullName);
+ whereClauses.Add("IsNews=@IsNews");
+ cmd.Parameters.Add(cmd, "@IsNews", DbType.Boolean).Value = query.IsNews;
}
-
- if (alternateTypes.Count == 0)
+ if (query.IsKids.HasValue)
{
- whereClauses.Add("IsMovie=@IsMovie");
+ whereClauses.Add("IsKids=@IsKids");
+ cmd.Parameters.Add(cmd, "@IsKids", DbType.Boolean).Value = query.IsKids;
}
- else
+ if (query.IsSports.HasValue)
{
- whereClauses.Add("(IsMovie is null OR IsMovie=@IsMovie)");
+ whereClauses.Add("IsSports=@IsSports");
+ cmd.Parameters.Add(cmd, "@IsSports", DbType.Boolean).Value = query.IsSports;
}
- cmd.Parameters.Add(cmd, "@IsMovie", DbType.Boolean).Value = query.IsMovie;
- }
- if (query.IsKids.HasValue)
- {
- whereClauses.Add("IsKids=@IsKids");
- cmd.Parameters.Add(cmd, "@IsKids", DbType.Boolean).Value = query.IsKids;
}
- if (query.IsSports.HasValue)
+ else
{
- whereClauses.Add("IsSports=@IsSports");
- cmd.Parameters.Add(cmd, "@IsSports", DbType.Boolean).Value = query.IsSports;
+ var programAttribtues = new List<string>();
+ if (query.IsMovie ?? false)
+ {
+ var alternateTypes = new List<string>();
+ if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Movie).Name))
+ {
+ alternateTypes.Add(typeof(Movie).FullName);
+ }
+ if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(typeof(Trailer).Name))
+ {
+ alternateTypes.Add(typeof(Trailer).FullName);
+ }
+
+ if (alternateTypes.Count == 0)
+ {
+ programAttribtues.Add("IsMovie=@IsMovie");
+ }
+ else
+ {
+ programAttribtues.Add("(IsMovie is null OR IsMovie=@IsMovie)");
+ }
+
+ cmd.Parameters.Add(cmd, "@IsMovie", DbType.Boolean).Value = true;
+ }
+ if (query.IsSports ?? false)
+ {
+ programAttribtues.Add("IsSports=@IsSports");
+ cmd.Parameters.Add(cmd, "@IsSports", DbType.Boolean).Value = true;
+ }
+ if (query.IsNews ?? false)
+ {
+ programAttribtues.Add("IsNews=@IsNews");
+ cmd.Parameters.Add(cmd, "@IsNews", DbType.Boolean).Value = true;
+ }
+ if (query.IsSeries ?? false)
+ {
+ programAttribtues.Add("IsSeries=@IsSeries");
+ cmd.Parameters.Add(cmd, "@IsSeries", DbType.Boolean).Value = true;
+ }
+ if (query.IsKids ?? false)
+ {
+ programAttribtues.Add("IsKids=@IsKids");
+ cmd.Parameters.Add(cmd, "@IsKids", DbType.Boolean).Value = true;
+ }
+ if (programAttribtues.Count > 0)
+ {
+ whereClauses.Add("("+string.Join(" OR ", programAttribtues.ToArray())+")");
+ }
}
+
if (query.IsFolder.HasValue)
{
whereClauses.Add("IsFolder=@IsFolder");
@@ -2765,6 +2863,12 @@ namespace MediaBrowser.Server.Implementations.Persistence
cmd.Parameters.Add(cmd, "@MinSortName", DbType.String).Value = query.MinSortName;
}
+ if (!string.IsNullOrWhiteSpace(query.ExternalSeriesId))
+ {
+ whereClauses.Add("ExternalSeriesId=@ExternalSeriesId");
+ cmd.Parameters.Add(cmd, "@ExternalSeriesId", DbType.String).Value = query.ExternalSeriesId;
+ }
+
if (!string.IsNullOrWhiteSpace(query.Name))
{
whereClauses.Add("CleanName=@Name");
diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs
index 9f52f799b..d2bdee9fa 100644
--- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs
+++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs
@@ -287,11 +287,9 @@ namespace MediaBrowser.Server.Implementations.Session
var key = GetSessionKey(session.Client, session.DeviceId);
SessionInfo removed;
+ _activeConnections.TryRemove(key, out removed);
- if (_activeConnections.TryRemove(key, out removed))
- {
- OnSessionEnded(removed);
- }
+ OnSessionEnded(session);
}
}
finally
@@ -300,9 +298,9 @@ namespace MediaBrowser.Server.Implementations.Session
}
}
- private Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId)
+ private Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, string liveStreamId)
{
- return _mediaSourceManager.GetMediaSource(item, mediaSourceId, false);
+ return _mediaSourceManager.GetMediaSource(item, mediaSourceId, liveStreamId, false, CancellationToken.None);
}
/// <summary>
@@ -330,7 +328,7 @@ namespace MediaBrowser.Server.Implementations.Session
var hasMediaSources = libraryItem as IHasMediaSources;
if (hasMediaSources != null)
{
- mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId).ConfigureAwait(false);
+ mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
if (mediaSource != null)
{
@@ -785,7 +783,7 @@ namespace MediaBrowser.Server.Implementations.Session
var hasMediaSources = libraryItem as IHasMediaSources;
if (hasMediaSources != null)
{
- mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId).ConfigureAwait(false);
+ mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
}
info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
@@ -813,7 +811,7 @@ namespace MediaBrowser.Server.Implementations.Session
{
try
{
- await _mediaSourceManager.CloseLiveStream(info.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
+ await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -1334,8 +1332,19 @@ namespace MediaBrowser.Server.Implementations.Session
private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
{
- var user = _userManager.Users
- .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
+ User user = null;
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ {
+ var idGuid = new Guid(request.UserId);
+ user = _userManager.Users
+ .FirstOrDefault(i => i.Id == idGuid);
+ }
+
+ if (user == null)
+ {
+ user = _userManager.Users
+ .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
+ }
if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
{
diff --git a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs
index ffba60af8..1278a40a4 100644
--- a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs
+++ b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs
@@ -541,6 +541,11 @@ namespace MediaBrowser.Server.Implementations.Sync
return true;
}
+ if (item.SourceType == SourceType.Channel)
+ {
+ return BaseItem.ChannelManager.SupportsSync(item.ChannelId);
+ }
+
return item.LocationType == LocationType.FileSystem || item is Season;
}
diff --git a/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs b/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs
index a2b5851ac..cb666b6ac 100644
--- a/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs
+++ b/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs
@@ -150,7 +150,7 @@ namespace MediaBrowser.Server.Implementations.Sync
}
}
- public Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken)
+ public Task CloseMediaSource(string liveStreamId)
{
throw new NotImplementedException();
}
diff --git a/MediaBrowser.Server.Implementations/UserViews/CollectionFolderImageProvider.cs b/MediaBrowser.Server.Implementations/UserViews/CollectionFolderImageProvider.cs
index 29716d33e..2cff4a14f 100644
--- a/MediaBrowser.Server.Implementations/UserViews/CollectionFolderImageProvider.cs
+++ b/MediaBrowser.Server.Implementations/UserViews/CollectionFolderImageProvider.cs
@@ -13,6 +13,10 @@ using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CommonIO;
+using MediaBrowser.Controller.Collections;
+using MediaBrowser.Controller.Entities.Movies;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Querying;
namespace MediaBrowser.Server.Implementations.UserViews
{
@@ -109,4 +113,62 @@ namespace MediaBrowser.Server.Implementations.UserViews
return await base.CreateImage(item, itemsWithImages, outputPath, imageType, imageIndex).ConfigureAwait(false);
}
}
+
+ public class ManualCollectionFolderImageProvider : BaseDynamicImageProvider<ManualCollectionsFolder>
+ {
+ private readonly ILibraryManager _libraryManager;
+
+ public ManualCollectionFolderImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor, ILibraryManager libraryManager) : base(fileSystem, providerManager, applicationPaths, imageProcessor)
+ {
+ _libraryManager = libraryManager;
+ }
+
+ public override IEnumerable<ImageType> GetSupportedImages(IHasImages item)
+ {
+ return new List<ImageType>
+ {
+ ImageType.Primary
+ };
+ }
+
+ protected override async Task<List<BaseItem>> GetItemsWithImages(IHasImages item)
+ {
+ var view = (ManualCollectionsFolder)item;
+
+ var recursive = !new[] { CollectionType.Playlists, CollectionType.Channels }.Contains(view.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
+
+ var items = _libraryManager.GetItemList(new InternalItemsQuery
+ {
+ Recursive = recursive,
+ IncludeItemTypes = new[] { typeof(BoxSet).Name },
+ Limit = 20,
+ SortBy = new[] { ItemSortBy.Random }
+ });
+
+ return GetFinalItems(items.Where(i => i.HasImage(ImageType.Primary) || i.HasImage(ImageType.Thumb)).ToList(), 8);
+ }
+
+ protected override bool Supports(IHasImages item)
+ {
+ return item is ManualCollectionsFolder;
+ }
+
+ protected override async Task<string> CreateImage(IHasImages item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+ {
+ var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ".png");
+
+ if (imageType == ImageType.Primary)
+ {
+ if (itemsWithImages.Count == 0)
+ {
+ return null;
+ }
+
+ return await CreateThumbCollage(item, itemsWithImages, outputPath, 960, 540).ConfigureAwait(false);
+ }
+
+ return await base.CreateImage(item, itemsWithImages, outputPath, imageType, imageIndex).ConfigureAwait(false);
+ }
+ }
+
}
diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config
index 746dc7f62..043257fc8 100644
--- a/MediaBrowser.Server.Implementations/packages.config
+++ b/MediaBrowser.Server.Implementations/packages.config
@@ -5,9 +5,8 @@
<package id="ini-parser" version="2.3.0" targetFramework="net45" />
<package id="Interfaces.IO" version="1.0.0.5" targetFramework="net45" />
<package id="MediaBrowser.Naming" version="1.0.0.55" targetFramework="net45" />
- <package id="Mono.Nat" version="1.2.24.0" targetFramework="net45" />
<package id="morelinq" version="1.4.0" targetFramework="net45" />
<package id="Patterns.Logging" version="1.0.0.2" targetFramework="net45" />
- <package id="SimpleInjector" version="3.2.0" targetFramework="net45" />
- <package id="SocketHttpListener" version="1.0.0.39" targetFramework="net45" />
+ <package id="SimpleInjector" version="3.2.2" targetFramework="net45" />
+ <package id="SocketHttpListener" version="1.0.0.40" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/MediaBrowser.Server.Mac/Emby.Server.Mac.csproj b/MediaBrowser.Server.Mac/Emby.Server.Mac.csproj
index f04b833b9..9f3bf5102 100644
--- a/MediaBrowser.Server.Mac/Emby.Server.Mac.csproj
+++ b/MediaBrowser.Server.Mac/Emby.Server.Mac.csproj
@@ -498,9 +498,6 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\livetvitems.html">
<Link>Resources\dashboard-ui\livetvitems.html</Link>
</BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\livetvrecordinglist.html">
- <Link>Resources\dashboard-ui\livetvrecordinglist.html</Link>
- </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\livetvseriestimer.html">
<Link>Resources\dashboard-ui\livetvseriestimer.html</Link>
</BundleResource>
@@ -1050,6 +1047,9 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-apiclient\serverdiscovery-chrome.js">
<Link>Resources\dashboard-ui\bower_components\emby-apiclient\serverdiscovery-chrome.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-apiclient\serverdiscovery-winjs.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-apiclient\serverdiscovery-winjs.js</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-apiclient\serverdiscovery.js">
<Link>Resources\dashboard-ui\bower_components\emby-apiclient\serverdiscovery.js</Link>
</BundleResource>
@@ -1215,6 +1215,9 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\dialog\dialog.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\dialog\dialog.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\dialog\dialog.template.html">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\dialog\dialog.template.html</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\dialoghelper\dialoghelper.css">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\dialoghelper\dialoghelper.css</Link>
</BundleResource>
@@ -1470,6 +1473,18 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\fonts\roboto\ty9dfvLAziwdqQ2dHoyjphTbgVql8nDJpwnrE27mub0.woff2">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\fonts\roboto\ty9dfvLAziwdqQ2dHoyjphTbgVql8nDJpwnrE27mub0.woff2</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\fullscreen\fullscreen-doubleclick.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\fullscreen\fullscreen-doubleclick.js</Link>
+ </BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\fullscreen\fullscreenmanager.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\fullscreen\fullscreenmanager.js</Link>
+ </BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\guide\guide-settings.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\guide\guide-settings.js</Link>
+ </BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\guide\guide-settings.template.html">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\guide\guide-settings.template.html</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\guide\guide.css">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\guide\guide.css</Link>
</BundleResource>
@@ -1479,6 +1494,12 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\guide\tvguide.template.html">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\guide\tvguide.template.html</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\imageeditor\imageeditor.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\imageeditor\imageeditor.js</Link>
+ </BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\imageeditor\imageeditor.template.html">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\imageeditor\imageeditor.template.html</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\images\basicimagefetcher.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\images\basicimagefetcher.js</Link>
</BundleResource>
@@ -1557,14 +1578,17 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\multiselect\multiselect.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\multiselect\multiselect.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\notifications\badge.png">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\notifications\badge.png</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\notifications\notificationicon.png">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\notifications\notificationicon.png</Link>
</BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\notifications\notifications.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\notifications\notifications.js</Link>
</BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\page.js\page.js">
- <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\page.js\page.js</Link>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\pagejs\page.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\pagejs\page.js</Link>
</BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\playlisteditor\playlisteditor.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\playlisteditor\playlisteditor.js</Link>
@@ -1578,14 +1602,17 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\polyfills\objectassign.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\polyfills\objectassign.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\polyfills\raf.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\polyfills\raf.js</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\prompt\nativeprompt.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\prompt\nativeprompt.js</Link>
</BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\prompt\prompt.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\prompt\prompt.js</Link>
</BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\prompt\style.css">
- <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\prompt\style.css</Link>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\prompt\prompt.template.html">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\prompt\prompt.template.html</Link>
</BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\recordingcreator\recordingcreator.css">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\recordingcreator\recordingcreator.css</Link>
@@ -1617,6 +1644,12 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\scroller\smoothscroller.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\scroller\smoothscroller.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\serviceworker\notifications.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\serviceworker\notifications.js</Link>
+ </BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\serviceworker\sync.js">
+ <Link>Resources\dashboard-ui\bower_components\emby-webcomponents\serviceworker\sync.js</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\bower_components\emby-webcomponents\sharing\sharingmanager.js">
<Link>Resources\dashboard-ui\bower_components\emby-webcomponents\sharing\sharingmanager.js</Link>
</BundleResource>
@@ -3423,12 +3456,6 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\components\imagedownloader\imagedownloader.template.html">
<Link>Resources\dashboard-ui\components\imagedownloader\imagedownloader.template.html</Link>
</BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\components\imageeditor\imageeditor.js">
- <Link>Resources\dashboard-ui\components\imageeditor\imageeditor.js</Link>
- </BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\components\imageeditor\imageeditor.template.html">
- <Link>Resources\dashboard-ui\components\imageeditor\imageeditor.template.html</Link>
- </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\components\imageuploader\imageuploader.js">
<Link>Resources\dashboard-ui\components\imageuploader\imageuploader.js</Link>
</BundleResource>
@@ -3936,12 +3963,12 @@
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\scripts\livetvitems.js">
<Link>Resources\dashboard-ui\scripts\livetvitems.js</Link>
</BundleResource>
- <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\scripts\livetvrecordinglist.js">
- <Link>Resources\dashboard-ui\scripts\livetvrecordinglist.js</Link>
- </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\scripts\livetvrecordings.js">
<Link>Resources\dashboard-ui\scripts\livetvrecordings.js</Link>
</BundleResource>
+ <BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\scripts\livetvschedule.js">
+ <Link>Resources\dashboard-ui\scripts\livetvschedule.js</Link>
+ </BundleResource>
<BundleResource Include="..\MediaBrowser.WebDashboard\dashboard-ui\scripts\livetvseriestimer.js">
<Link>Resources\dashboard-ui\scripts\livetvseriestimer.js</Link>
</BundleResource>
diff --git a/MediaBrowser.Server.Mac/Native/BaseMonoApp.cs b/MediaBrowser.Server.Mac/Native/BaseMonoApp.cs
index 7c9b43026..f4e054406 100644
--- a/MediaBrowser.Server.Mac/Native/BaseMonoApp.cs
+++ b/MediaBrowser.Server.Mac/Native/BaseMonoApp.cs
@@ -205,6 +205,16 @@ namespace MediaBrowser.Server.Mac
return new NullPowerManagement ();
}
+ public void EnableLoopback(string appName)
+ {
+
+ }
+
+ public bool PortsRequireAuthorization(string applicationPath)
+ {
+ return false;
+ }
+
private NativeEnvironment GetEnvironmentInfo()
{
var info = new NativeEnvironment
diff --git a/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj b/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj
index bcbb10174..e7acb3f50 100644
--- a/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj
+++ b/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
@@ -10,8 +10,9 @@
<RootNamespace>MediaBrowser.Server.Mono</RootNamespace>
<AssemblyName>MediaBrowser.Server.Mono</AssemblyName>
<StartupObject>MediaBrowser.Server.Mono.MainClass</StartupObject>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs
index 2185f4804..d2a544477 100644
--- a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs
+++ b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs
@@ -8,7 +8,6 @@ using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
-using MediaBrowser.Controller.Power;
using MediaBrowser.Model.System;
using MediaBrowser.Server.Implementations.Persistence;
using MediaBrowser.Server.Startup.Common.FFMpeg;
@@ -232,11 +231,6 @@ namespace MediaBrowser.Server.Mono.Native
public string machine = string.Empty;
}
- public IPowerManagement GetPowerManagement()
- {
- return new NullPowerManagement();
- }
-
public FFMpegInstallInfo GetFfmpegInstallInfo()
{
return GetInfo(Environment);
@@ -283,13 +277,10 @@ namespace MediaBrowser.Server.Mono.Native
{
}
- }
- public class NullPowerManagement : IPowerManagement
- {
- public void ScheduleWake(DateTime utcTime)
+ public bool PortsRequireAuthorization(string applicationPath)
{
- throw new NotImplementedException();
+ return false;
}
}
}
diff --git a/MediaBrowser.Server.Mono/app.config b/MediaBrowser.Server.Mono/app.config
index b0e8558fd..e14b908ad 100644
--- a/MediaBrowser.Server.Mono/app.config
+++ b/MediaBrowser.Server.Mono/app.config
@@ -1,21 +1,21 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
- <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
+ <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true"></targets>
</nlog>
<appSettings>
- <add key="DebugProgramDataPath" value="ProgramData-Server" />
- <add key="ReleaseProgramDataPath" value="ProgramData-Server" />
+ <add key="DebugProgramDataPath" value="ProgramData-Server"/>
+ <add key="ReleaseProgramDataPath" value="ProgramData-Server"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
- <assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-1.0.94.0" newVersion="1.0.94.0" />
+ <assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral"/>
+ <bindingRedirect oldVersion="0.0.0.0-1.0.94.0" newVersion="1.0.94.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
-</configuration>
+<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/></startup></configuration>
diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs
index 005b38a7d..59b553ecf 100644
--- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs
+++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs
@@ -315,6 +315,8 @@ namespace MediaBrowser.Server.Startup.Common
/// </summary>
public override async Task RunStartupTasks()
{
+ await PerformPreInitMigrations().ConfigureAwait(false);
+
if (ServerConfigurationManager.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion &&
ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
{
@@ -325,6 +327,15 @@ namespace MediaBrowser.Server.Startup.Common
await MediaEncoder.Init().ConfigureAwait(false);
+ if (string.IsNullOrWhiteSpace(MediaEncoder.EncoderPath))
+ {
+ if (ServerConfigurationManager.Configuration.IsStartupWizardCompleted)
+ {
+ ServerConfigurationManager.Configuration.IsStartupWizardCompleted = false;
+ ServerConfigurationManager.SaveConfiguration();
+ }
+ }
+
Logger.Info("ServerId: {0}", SystemId);
Logger.Info("Core startup complete");
HttpServer.GlobalResponse = null;
@@ -336,6 +347,7 @@ namespace MediaBrowser.Server.Startup.Common
{
var name = entryPoint.GetType().FullName;
Logger.Info("Starting entry point {0}", name);
+ var now = DateTime.UtcNow;
try
{
entryPoint.Run();
@@ -344,7 +356,7 @@ namespace MediaBrowser.Server.Startup.Common
{
Logger.ErrorException("Error in {0}", ex, name);
}
- Logger.Info("Entry point completed: {0}", name);
+ Logger.Info("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
}
Logger.Info("All entry points have started");
@@ -356,20 +368,21 @@ namespace MediaBrowser.Server.Startup.Common
HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
- PerformPreInitMigrations();
-
return base.Init(progress);
}
- private void PerformPreInitMigrations()
+ private async Task PerformPreInitMigrations()
{
- var migrations = new List<IVersionMigration>();
+ var migrations = new List<IVersionMigration>
+ {
+ new UpdateLevelMigration(ServerConfigurationManager, this, HttpClient, JsonSerializer, _releaseAssetFilename, Logger)
+ };
foreach (var task in migrations)
{
try
{
- task.Run();
+ await task.Run().ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -383,8 +396,7 @@ namespace MediaBrowser.Server.Startup.Common
var migrations = new List<IVersionMigration>
{
new MovieDbEpisodeProviderMigration(ServerConfigurationManager),
- new DbMigration(ServerConfigurationManager, TaskManager),
- new UpdateLevelMigration(ServerConfigurationManager, this, HttpClient, JsonSerializer, _releaseAssetFilename)
+ new DbMigration(ServerConfigurationManager, TaskManager)
};
foreach (var task in migrations)
@@ -519,7 +531,7 @@ namespace MediaBrowser.Server.Startup.Common
PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager);
RegisterSingleInstance<IPlaylistManager>(PlaylistManager);
- LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager);
+ LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager);
RegisterSingleInstance(LiveTvManager);
UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
@@ -537,7 +549,7 @@ namespace MediaBrowser.Server.Startup.Common
SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, MediaSourceManager);
RegisterSingleInstance(SubtitleManager);
- RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, this, NetworkManager));
+ RegisterSingleInstance<IDeviceDiscovery>(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager));
ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
RegisterSingleInstance(ChapterManager);
@@ -548,14 +560,10 @@ namespace MediaBrowser.Server.Startup.Common
EncodingManager = new EncodingManager(FileSystemManager, Logger, MediaEncoder, ChapterManager, LibraryManager);
RegisterSingleInstance(EncodingManager);
- RegisterSingleInstance(NativeApp.GetPowerManagement());
-
var sharingRepo = new SharingRepository(LogManager, ApplicationPaths, NativeApp.GetDbConnector());
await sharingRepo.Initialize().ConfigureAwait(false);
RegisterSingleInstance<ISharingManager>(new SharingManager(sharingRepo, ServerConfigurationManager, LibraryManager, this));
- RegisterSingleInstance<ISsdpHandler>(new SsdpHandler(LogManager.GetLogger("SsdpHandler"), ServerConfigurationManager, this));
-
var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
RegisterSingleInstance(activityLogRepo);
RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
@@ -772,7 +780,19 @@ namespace MediaBrowser.Server.Startup.Common
/// </summary>
protected override void FindParts()
{
- if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
+ var isAuthorized = ServerConfigurationManager.Configuration.IsPortAuthorized;
+ if (isAuthorized)
+ {
+ try
+ {
+ isAuthorized = !NativeApp.PortsRequireAuthorization(ConfigurationManager.CommonApplicationPaths.ApplicationPath);
+ }
+ catch
+ {
+
+ }
+ }
+ if (!isAuthorized)
{
RegisterServerWithAdministratorAccess();
ServerConfigurationManager.Configuration.IsPortAuthorized = true;
@@ -830,12 +850,12 @@ namespace MediaBrowser.Server.Startup.Common
{
var prefixes = new List<string>
{
- "http://"+i+":" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/"
+ "http://"+i+":" + HttpPort + "/"
};
if (!string.IsNullOrWhiteSpace(CertificatePath))
{
- prefixes.Add("https://" + i + ":" + ServerConfigurationManager.Configuration.HttpsPortNumber + "/");
+ prefixes.Add("https://" + i + ":" + HttpsPort + "/");
}
return prefixes;
@@ -852,6 +872,23 @@ namespace MediaBrowser.Server.Startup.Common
try
{
ServerManager.Start(GetUrlPrefixes(), CertificatePath);
+ return;
+ }
+ catch (Exception ex)
+ {
+ Logger.ErrorException("Error starting http server", ex);
+
+ if (HttpPort == 8096)
+ {
+ throw;
+ }
+ }
+
+ HttpPort = 8096;
+
+ try
+ {
+ ServerManager.Start(GetUrlPrefixes(), CertificatePath);
}
catch (Exception ex)
{
@@ -1095,7 +1132,8 @@ namespace MediaBrowser.Server.Startup.Common
LocalAddress = localAddress,
SupportsLibraryMonitor = SupportsLibraryMonitor,
EncoderLocationType = MediaEncoder.EncoderLocationType,
- SystemArchitecture = NativeApp.Environment.SystemArchitecture
+ SystemArchitecture = NativeApp.Environment.SystemArchitecture,
+ SystemUpdateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel
};
}
@@ -1153,20 +1191,24 @@ namespace MediaBrowser.Server.Startup.Common
public async Task<List<IPAddress>> GetLocalIpAddresses()
{
- var localAddresses = NetworkManager.GetLocalIpAddresses()
- .Where(IsIpAddressValid)
- .ToList();
+ var addresses = NetworkManager.GetLocalIpAddresses().ToList();
+ var list = new List<IPAddress>();
+
+ foreach (var address in addresses)
+ {
+ var valid = await IsIpAddressValidAsync(address).ConfigureAwait(false);
+ if (valid)
+ {
+ list.Add(address);
+ }
+ }
- return localAddresses;
+ return list;
}
private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private DateTime _lastAddressCacheClear;
- private bool IsIpAddressValid(IPAddress address)
- {
- return IsIpAddressValidInternal(address).Result;
- }
- private async Task<bool> IsIpAddressValidInternal(IPAddress address)
+ private async Task<bool> IsIpAddressValidAsync(IPAddress address)
{
if (IPAddress.IsLoopback(address))
{
@@ -1176,7 +1218,7 @@ namespace MediaBrowser.Server.Startup.Common
var apiUrl = GetLocalApiUrl(address);
apiUrl += "/system/ping";
- if ((DateTime.UtcNow - _lastAddressCacheClear).TotalMinutes >= 5)
+ if ((DateTime.UtcNow - _lastAddressCacheClear).TotalMinutes >= 10)
{
_lastAddressCacheClear = DateTime.UtcNow;
_validAddressResults.Clear();
@@ -1329,8 +1371,8 @@ namespace MediaBrowser.Server.Startup.Common
cacheLength = TimeSpan.FromMinutes(5);
}
- var result = await new GithubUpdater(HttpClient, JsonSerializer, cacheLength).CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, updateLevel, _releaseAssetFilename,
- "MBServer", "Mbserver.zip", cancellationToken).ConfigureAwait(false);
+ var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, updateLevel, _releaseAssetFilename,
+ "MBServer", "Mbserver.zip", cacheLength, cancellationToken).ConfigureAwait(false);
HasUpdateAvailable = result.IsUpdateAvailable;
diff --git a/MediaBrowser.Server.Startup.Common/ApplicationPathHelper.cs b/MediaBrowser.Server.Startup.Common/ApplicationPathHelper.cs
index 285806791..254a782db 100644
--- a/MediaBrowser.Server.Startup.Common/ApplicationPathHelper.cs
+++ b/MediaBrowser.Server.Startup.Common/ApplicationPathHelper.cs
@@ -18,10 +18,16 @@ namespace MediaBrowser.Server.Startup.Common
useDebugPath = true;
#endif
- var programDataPath = useDebugPath ? ConfigurationManager.AppSettings["DebugProgramDataPath"] : ConfigurationManager.AppSettings["ReleaseProgramDataPath"];
+ var programDataPath = useDebugPath ?
+ ConfigurationManager.AppSettings["DebugProgramDataPath"] :
+ ConfigurationManager.AppSettings["ReleaseProgramDataPath"];
programDataPath = programDataPath.Replace("%ApplicationData%", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
+ programDataPath = programDataPath
+ .Replace('/', Path.DirectorySeparatorChar)
+ .Replace('\\', Path.DirectorySeparatorChar);
+
// If it's a relative path, e.g. "..\"
if (!Path.IsPathRooted(programDataPath))
{
diff --git a/MediaBrowser.Server.Startup.Common/INativeApp.cs b/MediaBrowser.Server.Startup.Common/INativeApp.cs
index d2e278a3b..bf8314d13 100644
--- a/MediaBrowser.Server.Startup.Common/INativeApp.cs
+++ b/MediaBrowser.Server.Startup.Common/INativeApp.cs
@@ -2,7 +2,6 @@
using MediaBrowser.Model.Logging;
using System.Collections.Generic;
using System.Reflection;
-using MediaBrowser.Controller.Power;
using MediaBrowser.Server.Implementations.Persistence;
using MediaBrowser.Server.Startup.Common.FFMpeg;
@@ -25,6 +24,8 @@ namespace MediaBrowser.Server.Startup.Common
/// <param name="tempDirectory">The temporary directory.</param>
void AuthorizeServer(int udpPort, int httpServerPort, int httpsServerPort, string applicationPath, string tempDirectory);
+ bool PortsRequireAuthorization(string applicationPath);
+
/// <summary>
/// Gets the environment.
/// </summary>
@@ -96,12 +97,6 @@ namespace MediaBrowser.Server.Startup.Common
void AllowSystemStandby();
- /// <summary>
- /// Gets the power management.
- /// </summary>
- /// <returns>IPowerManagement.</returns>
- IPowerManagement GetPowerManagement();
-
FFMpegInstallInfo GetFfmpegInstallInfo();
void LaunchUrl(string url);
diff --git a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj
index 778002e50..7eba89650 100644
--- a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj
+++ b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj
@@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MediaBrowser.Server.Startup.Common</RootNamespace>
<AssemblyName>MediaBrowser.Server.Startup.Common</AssemblyName>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
+ <TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
diff --git a/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs
index f0cb9e84e..6bcdcca87 100644
--- a/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs
+++ b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs
@@ -16,7 +16,7 @@ namespace MediaBrowser.Server.Startup.Common.Migrations
_taskManager = taskManager;
}
- public void Run()
+ public async Task Run()
{
// If a forced migration is required, do that now
if (_config.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion)
diff --git a/MediaBrowser.Server.Startup.Common/Migrations/IVersionMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/IVersionMigration.cs
index a6a8c1a35..6ef08fae9 100644
--- a/MediaBrowser.Server.Startup.Common/Migrations/IVersionMigration.cs
+++ b/MediaBrowser.Server.Startup.Common/Migrations/IVersionMigration.cs
@@ -1,8 +1,9 @@
-
+using System.Threading.Tasks;
+
namespace MediaBrowser.Server.Startup.Common.Migrations
{
public interface IVersionMigration
{
- void Run();
+ Task Run();
}
}
diff --git a/MediaBrowser.Server.Startup.Common/Migrations/MovieDbEpisodeProviderMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/MovieDbEpisodeProviderMigration.cs
index 3ad5f577f..cd2122e57 100644
--- a/MediaBrowser.Server.Startup.Common/Migrations/MovieDbEpisodeProviderMigration.cs
+++ b/MediaBrowser.Server.Startup.Common/Migrations/MovieDbEpisodeProviderMigration.cs
@@ -1,5 +1,6 @@
using MediaBrowser.Controller.Configuration;
using System.Linq;
+using System.Threading.Tasks;
namespace MediaBrowser.Server.Startup.Common.Migrations
{
@@ -13,7 +14,7 @@ namespace MediaBrowser.Server.Startup.Common.Migrations
_config = config;
}
- public void Run()
+ public async Task Run()
{
var migrationKey = this.GetType().FullName;
var migrationKeyList = _config.Configuration.Migrations.ToList();
diff --git a/MediaBrowser.Server.Startup.Common/Migrations/UpdateLevelMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/UpdateLevelMigration.cs
index 1c90a7438..8483ca904 100644
--- a/MediaBrowser.Server.Startup.Common/Migrations/UpdateLevelMigration.cs
+++ b/MediaBrowser.Server.Startup.Common/Migrations/UpdateLevelMigration.cs
@@ -1,10 +1,12 @@
using System;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Implementations.Updates;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
@@ -17,17 +19,19 @@ namespace MediaBrowser.Server.Startup.Common.Migrations
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly string _releaseAssetFilename;
+ private readonly ILogger _logger;
- public UpdateLevelMigration(IServerConfigurationManager config, IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer, string releaseAssetFilename)
+ public UpdateLevelMigration(IServerConfigurationManager config, IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer, string releaseAssetFilename, ILogger logger)
{
_config = config;
_appHost = appHost;
_httpClient = httpClient;
_jsonSerializer = jsonSerializer;
_releaseAssetFilename = releaseAssetFilename;
+ _logger = logger;
}
- public async void Run()
+ public async Task Run()
{
var lastVersion = _config.Configuration.LastVersion;
var currentVersion = _appHost.ApplicationVersion;
@@ -41,35 +45,47 @@ namespace MediaBrowser.Server.Startup.Common.Migrations
{
var updateLevel = _config.Configuration.SystemUpdateLevel;
- if (updateLevel == PackageVersionClass.Dev)
- {
- // It's already dev, there's nothing to check
- return;
- }
-
await CheckVersion(currentVersion, updateLevel, CancellationToken.None).ConfigureAwait(false);
}
- catch
+ catch (Exception ex)
{
-
+ _logger.ErrorException("Error in update migration", ex);
}
}
- private async Task CheckVersion(Version currentVersion, PackageVersionClass updateLevel, CancellationToken cancellationToken)
+ private async Task CheckVersion(Version currentVersion, PackageVersionClass currentUpdateLevel, CancellationToken cancellationToken)
{
- var releases = await new GithubUpdater(_httpClient, _jsonSerializer, TimeSpan.FromMinutes(3))
+ var releases = await new GithubUpdater(_httpClient, _jsonSerializer)
.GetLatestReleases("MediaBrowser", "Emby", _releaseAssetFilename, cancellationToken).ConfigureAwait(false);
- var newUpdateLevel = updateLevel;
+ var newUpdateLevel = GetNewUpdateLevel(currentVersion, currentUpdateLevel, releases);
+
+ if (newUpdateLevel != currentUpdateLevel)
+ {
+ _config.Configuration.SystemUpdateLevel = newUpdateLevel;
+ _config.SaveConfiguration();
+ }
+ }
+
+ private PackageVersionClass GetNewUpdateLevel(Version currentVersion, PackageVersionClass currentUpdateLevel, List<GithubUpdater.RootObject> releases)
+ {
+ var newUpdateLevel = currentUpdateLevel;
// If the current version is later than current stable, set the update level to beta
if (releases.Count >= 1)
{
var release = releases[0];
var version = ParseVersion(release.tag_name);
- if (version != null && currentVersion > version)
+ if (version != null)
{
- newUpdateLevel = PackageVersionClass.Beta;
+ if (currentVersion > version)
+ {
+ newUpdateLevel = PackageVersionClass.Beta;
+ }
+ else
+ {
+ return PackageVersionClass.Release;
+ }
}
}
@@ -78,25 +94,31 @@ namespace MediaBrowser.Server.Startup.Common.Migrations
{
var release = releases[1];
var version = ParseVersion(release.tag_name);
- if (version != null && currentVersion > version)
+ if (version != null)
{
- newUpdateLevel = PackageVersionClass.Dev;
+ if (currentVersion > version)
+ {
+ newUpdateLevel = PackageVersionClass.Dev;
+ }
+ else
+ {
+ return PackageVersionClass.Beta;
+ }
}
}
- if (newUpdateLevel != updateLevel)
- {
- _config.Configuration.SystemUpdateLevel = newUpdateLevel;
- _config.SaveConfiguration();
- }
+ return newUpdateLevel;
}
private Version ParseVersion(string versionString)
{
- var parts = versionString.Split('.');
- if (parts.Length == 3)
+ if (!string.IsNullOrWhiteSpace(versionString))
{
- versionString += ".0";
+ var parts = versionString.Split('.');
+ if (parts.Length == 3)
+ {
+ versionString += ".0";
+ }
}
Version version;
diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs
index 8fb0e8f46..90e688733 100644
--- a/MediaBrowser.ServerApplication/MainStartup.cs
+++ b/MediaBrowser.ServerApplication/MainStartup.cs
@@ -15,6 +15,7 @@ using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.ServiceProcess;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
@@ -32,19 +33,47 @@ namespace MediaBrowser.ServerApplication
private static ILogger _logger;
private static bool _isRunningAsService = false;
+ private static bool _canRestartService = false;
private static bool _appHostDisposed;
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);
+ public static bool TryGetLocalFromUncDirectory(string local, out string unc)
+ {
+ if ((local == null) || (local == ""))
+ {
+ unc = "";
+ throw new ArgumentNullException("local");
+ }
+
+ ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_share WHERE path ='" + local.Replace("\\", "\\\\") + "'");
+ ManagementObjectCollection coll = searcher.Get();
+ if (coll.Count == 1)
+ {
+ foreach (ManagementObject share in searcher.Get())
+ {
+ unc = share["Name"] as String;
+ unc = "\\\\" + SystemInformation.ComputerName + "\\" + unc;
+ return true;
+ }
+ }
+ unc = "";
+ return false;
+ }
/// <summary>
- /// Defines the entry point of the application.
- /// </summary>
+ /// Defines the entry point of the application.
+ /// </summary>
public static void Main()
{
var options = new StartupOptions();
_isRunningAsService = options.ContainsOption("-service");
+ if (_isRunningAsService)
+ {
+ _canRestartService = CanRestartWindowsService();
+ }
+
var currentProcess = Process.GetCurrentProcess();
var applicationPath = currentProcess.MainModule.FileName;
@@ -238,7 +267,14 @@ namespace MediaBrowser.ServerApplication
{
get
{
- return !_isRunningAsService;
+ if (_isRunningAsService)
+ {
+ return _canRestartService;
+ }
+ else
+ {
+ return true;
+ }
}
}
@@ -250,7 +286,14 @@ namespace MediaBrowser.ServerApplication
{
get
{
- return !_isRunningAsService;
+ if (_isRunningAsService)
+ {
+ return _canRestartService;
+ }
+ else
+ {
+ return true;
+ }
}
}
@@ -331,7 +374,7 @@ namespace MediaBrowser.ServerApplication
Application.Run();
}
- private static SplashForm _splash;
+ internal static SplashForm _splash;
private static Thread _splashThread;
private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
{
@@ -591,7 +634,11 @@ namespace MediaBrowser.ServerApplication
{
DisposeAppHost();
- if (!_isRunningAsService)
+ if (_isRunningAsService)
+ {
+ RestartWindowsService();
+ }
+ else
{
//_logger.Info("Hiding server notify icon");
//_serverNotifyIcon.Visible = false;
@@ -646,6 +693,47 @@ namespace MediaBrowser.ServerApplication
}
}
+ private static void RestartWindowsService()
+ {
+ _logger.Info("Restarting background service");
+
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = "cmd.exe",
+ CreateNoWindow = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ Verb = "runas",
+ ErrorDialog = false,
+ Arguments = String.Format("/c sc stop {0} & sc start {0}", BackgroundService.GetExistingServiceName())
+ };
+ Process.Start(startInfo);
+ }
+
+ private static bool CanRestartWindowsService()
+ {
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = "cmd.exe",
+ CreateNoWindow = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ Verb = "runas",
+ ErrorDialog = false,
+ Arguments = String.Format("/c sc query {0}", BackgroundService.GetExistingServiceName())
+ };
+ using (var process = Process.Start(startInfo))
+ {
+ process.WaitForExit();
+ if (process.ExitCode == 0)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ }
+
private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
{
// Reference
diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj
index a32312493..0a7a3a6a5 100644
--- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj
+++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj
@@ -83,8 +83,8 @@
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
- <Reference Include="System.Data.SQLite, Version=1.0.102.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
- <HintPath>..\packages\System.Data.SQLite.Core.1.0.102.0\lib\net46\System.Data.SQLite.dll</HintPath>
+ <Reference Include="System.Data.SQLite, Version=1.0.103.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
+ <HintPath>..\packages\System.Data.SQLite.Core.1.0.103\lib\net46\System.Data.SQLite.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Drawing" />
@@ -123,7 +123,6 @@
<Compile Include="Native\Standby.cs" />
<Compile Include="Native\ServerAuthorization.cs" />
<Compile Include="Native\WindowsApp.cs" />
- <Compile Include="Native\WindowsPowerManagement.cs" />
<Compile Include="Networking\CertificateGenerator.cs" />
<Compile Include="Networking\NativeMethods.cs" />
<Compile Include="Networking\NetworkManager.cs" />
@@ -1114,12 +1113,12 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
- <Import Project="..\packages\System.Data.SQLite.Core.1.0.102.0\build\net46\System.Data.SQLite.Core.targets" Condition="Exists('..\packages\System.Data.SQLite.Core.1.0.102.0\build\net46\System.Data.SQLite.Core.targets')" />
+ <Import Project="..\packages\System.Data.SQLite.Core.1.0.103\build\net46\System.Data.SQLite.Core.targets" Condition="Exists('..\packages\System.Data.SQLite.Core.1.0.103\build\net46\System.Data.SQLite.Core.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
- <Error Condition="!Exists('..\packages\System.Data.SQLite.Core.1.0.102.0\build\net46\System.Data.SQLite.Core.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.Data.SQLite.Core.1.0.102.0\build\net46\System.Data.SQLite.Core.targets'))" />
+ <Error Condition="!Exists('..\packages\System.Data.SQLite.Core.1.0.103\build\net46\System.Data.SQLite.Core.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.Data.SQLite.Core.1.0.103\build\net46\System.Data.SQLite.Core.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
diff --git a/MediaBrowser.ServerApplication/Native/RegisterServer.bat b/MediaBrowser.ServerApplication/Native/RegisterServer.bat
index 27f863d58..85baa0d03 100644
--- a/MediaBrowser.ServerApplication/Native/RegisterServer.bat
+++ b/MediaBrowser.ServerApplication/Native/RegisterServer.bat
@@ -20,7 +20,9 @@ netsh advfirewall firewall add rule name="Port %3" dir=in action=allow protocol=
if [%4]==[] GOTO DONE
+netsh advfirewall firewall delete rule name="mediabrowser.serverapplication.exe"
netsh advfirewall firewall delete rule name="Emby Server"
+
netsh advfirewall firewall add rule name="Emby Server" dir=in action=allow protocol=TCP program=%4 enable=yes
netsh advfirewall firewall add rule name="Emby Server" dir=in action=allow protocol=UDP program=%4 enable=yes
diff --git a/MediaBrowser.ServerApplication/Native/WindowsApp.cs b/MediaBrowser.ServerApplication/Native/WindowsApp.cs
index 139471f11..1e50ac85e 100644
--- a/MediaBrowser.ServerApplication/Native/WindowsApp.cs
+++ b/MediaBrowser.ServerApplication/Native/WindowsApp.cs
@@ -7,8 +7,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
+using System.Windows.Forms;
using CommonIO;
-using MediaBrowser.Controller.Power;
using MediaBrowser.Model.System;
using MediaBrowser.Server.Implementations.Persistence;
using MediaBrowser.Server.Startup.Common.FFMpeg;
@@ -147,11 +147,6 @@ namespace MediaBrowser.ServerApplication.Native
MainStartup.Invoke(Standby.AllowSleep);
}
- public IPowerManagement GetPowerManagement()
- {
- return new WindowsPowerManagement(_logger);
- }
-
public FFMpegInstallInfo GetFfmpegInstallInfo()
{
var info = new FFMpegInstallInfo();
@@ -208,5 +203,71 @@ namespace MediaBrowser.ServerApplication.Native
{
LoopUtil.Run(appName);
}
+
+ private bool Confirm()
+ {
+ if (MainStartup._splash == null)
+ {
+ return false;
+ }
+
+ return MessageBox.Show(MainStartup._splash, "Emby has detected that a rule has been added to Windows Firewall that may prevent your other devices from accessing Emby Server. Click OK to remove this rule, or cancel to proceed anyway.", "Windows Firewall", MessageBoxButtons.OKCancel) == DialogResult.OK;
+ }
+
+ public bool PortsRequireAuthorization(string applicationPath)
+ {
+ var appNameSrch = Path.GetFileName(applicationPath);
+
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = "netsh",
+
+ Arguments = "advfirewall firewall show rule \"" + appNameSrch + "\"",
+
+ CreateNoWindow = true,
+ UseShellExecute = false,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false,
+ RedirectStandardOutput = true
+ };
+
+ using (var process = Process.Start(startInfo))
+ {
+ process.Start();
+
+ try
+ {
+ var data = process.StandardOutput.ReadToEnd() ?? string.Empty;
+
+ if (data.IndexOf("Block", StringComparison.OrdinalIgnoreCase) != -1)
+ {
+ _logger.Info("Found potential windows firewall rule blocking Emby Server: " + data);
+ return Confirm();
+ }
+
+ //var parts = data.Split('\n');
+
+ //return parts.Length > 4;
+ //return Confirm();
+ return false;
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error querying windows firewall", ex);
+
+ // Hate having to do this
+ try
+ {
+ process.Kill();
+ }
+ catch (Exception ex1)
+ {
+ _logger.ErrorException("Error killing process", ex1);
+ }
+
+ throw;
+ }
+ }
+ }
}
} \ No newline at end of file
diff --git a/MediaBrowser.ServerApplication/Native/WindowsPowerManagement.cs b/MediaBrowser.ServerApplication/Native/WindowsPowerManagement.cs
deleted file mode 100644
index 866272639..000000000
--- a/MediaBrowser.ServerApplication/Native/WindowsPowerManagement.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using System.ComponentModel;
-using System.Runtime.InteropServices;
-using System.Threading;
-using MediaBrowser.Controller.Power;
-using MediaBrowser.Model.Logging;
-using Microsoft.Win32.SafeHandles;
-
-namespace MediaBrowser.ServerApplication.Native
-{
- public class WindowsPowerManagement : IPowerManagement
- {
- [DllImport("kernel32.dll")]
- public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes,
- bool bManualReset,
- string lpTimerName);
-
- [DllImport("kernel32.dll", SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool SetWaitableTimer(SafeWaitHandle hTimer,
- [In] ref long pDueTime,
- int lPeriod,
- IntPtr pfnCompletionRoutine,
- IntPtr lpArgToCompletionRoutine,
- bool fResume);
-
- private BackgroundWorker _bgWorker;
- private readonly ILogger _logger;
- private readonly object _initLock = new object();
-
- public WindowsPowerManagement(ILogger logger)
- {
- _logger = logger;
- }
-
- public void ScheduleWake(DateTime utcTime)
- {
- //Initialize();
- //_bgWorker.RunWorkerAsync(utcTime.ToFileTime());
- throw new NotImplementedException();
- }
-
- private void Initialize()
- {
- lock (_initLock)
- {
- if (_bgWorker == null)
- {
- _bgWorker = new BackgroundWorker();
-
- _bgWorker.DoWork += bgWorker_DoWork;
- _bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
- }
- }
- }
-
- void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- //if (Woken != null)
- //{
- // Woken(this, new EventArgs());
- //}
- }
-
- private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
- {
- try
- {
- long waketime = (long)e.Argument;
-
- using (SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, true, GetType().Assembly.GetName().Name + "Timer"))
- {
- if (SetWaitableTimer(handle, ref waketime, 0, IntPtr.Zero, IntPtr.Zero, true))
- {
- using (EventWaitHandle wh = new EventWaitHandle(false,
- EventResetMode.AutoReset))
- {
- wh.SafeWaitHandle = handle;
- wh.WaitOne();
- }
- }
- else
- {
- throw new Win32Exception(Marshal.GetLastWin32Error());
- }
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error scheduling wake timer", ex);
- }
- }
- }
-}
diff --git a/MediaBrowser.ServerApplication/packages.config b/MediaBrowser.ServerApplication/packages.config
index a573c6fd9..63d3bab8a 100644
--- a/MediaBrowser.ServerApplication/packages.config
+++ b/MediaBrowser.ServerApplication/packages.config
@@ -3,5 +3,5 @@
<package id="CommonIO" version="1.0.0.9" targetFramework="net45" />
<package id="ImageMagickSharp" version="1.0.0.18" targetFramework="net45" />
<package id="Patterns.Logging" version="1.0.0.2" targetFramework="net45" />
- <package id="System.Data.SQLite.Core" version="1.0.102.0" targetFramework="net46" />
+ <package id="System.Data.SQLite.Core" version="1.0.103" targetFramework="net462" />
</packages> \ No newline at end of file
diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs
index aec4632ae..4850b6fe0 100644
--- a/MediaBrowser.WebDashboard/Api/DashboardService.cs
+++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs
@@ -58,11 +58,6 @@ namespace MediaBrowser.WebDashboard.Api
{
}
- [Route("/web/staticfiles", "GET")]
- public class GetCacheFiles
- {
- }
-
/// <summary>
/// Class GetDashboardResource
/// </summary>
@@ -145,37 +140,6 @@ namespace MediaBrowser.WebDashboard.Api
return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml("dummy.html", page.GetHtmlStream(), null, _appHost.ApplicationVersion.ToString(), null, false));
}
- public object Get(GetCacheFiles request)
- {
- var allFiles = GetCacheFileList();
-
- return ResultFactory.GetOptimizedResult(Request, _jsonSerializer.SerializeToString(allFiles));
- }
-
- private List<string> GetCacheFileList()
- {
- var creator = GetPackageCreator();
- var directory = creator.DashboardUIPath;
-
- var skipExtensions = GetDeployIgnoreExtensions();
- var skipNames = GetDeployIgnoreFilenames();
-
- return
- Directory.GetFiles(directory, "*", SearchOption.AllDirectories)
- .Where(i => !skipExtensions.Contains(Path.GetExtension(i) ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- .Where(i => !skipNames.Any(s =>
- {
- if (s.Item2)
- {
- return string.Equals(s.Item1, Path.GetFileName(i), StringComparison.OrdinalIgnoreCase);
- }
-
- return (Path.GetFileName(i) ?? string.Empty).IndexOf(s.Item1, StringComparison.OrdinalIgnoreCase) != -1;
- }))
- .Select(i => i.Replace(directory, string.Empty, StringComparison.OrdinalIgnoreCase).Replace("\\", "/").TrimStart('/') + "?v=" + _appHost.ApplicationVersion.ToString())
- .ToList();
- }
-
/// <summary>
/// Gets the specified request.
/// </summary>
@@ -325,7 +289,7 @@ namespace MediaBrowser.WebDashboard.Api
return list;
}
- private List<Tuple<string,bool>> GetDeployIgnoreFilenames()
+ private List<Tuple<string, bool>> GetDeployIgnoreFilenames()
{
var list = new List<Tuple<string, bool>>();
@@ -349,8 +313,11 @@ namespace MediaBrowser.WebDashboard.Api
public async Task<object> Get(GetDashboardPackage request)
{
- var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
- "webclient-dump");
+ var mode = request.Mode;
+
+ var path = string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ?
+ Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath, "webclient-dump")
+ : "C:\\dev\\emby-web-mobile\\src";
try
{
@@ -369,10 +336,6 @@ namespace MediaBrowser.WebDashboard.Api
var appVersion = _appHost.ApplicationVersion.ToString();
- File.WriteAllText(Path.Combine(path, "staticfiles"), _jsonSerializer.SerializeToString(GetCacheFileList()));
-
- var mode = request.Mode;
-
// Try to trim the output size a bit
var bowerPath = Path.Combine(path, "bower_components");
@@ -410,11 +373,6 @@ namespace MediaBrowser.WebDashboard.Api
// Delete things that are unneeded in an attempt to keep the output as trim as possible
_fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
}
- else
- {
- MinifyCssDirectory(path);
- MinifyJsDirectory(path);
- }
await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
@@ -482,78 +440,6 @@ namespace MediaBrowser.WebDashboard.Api
}
}
- private void MinifyCssDirectory(string path)
- {
- foreach (var file in Directory.GetFiles(path, "*.css", SearchOption.AllDirectories))
- {
- if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
- {
- continue;
- }
- if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
- {
- continue;
- }
-
- try
- {
- var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
-
- var result = new KristensenCssMinifier().Minify(text, false, Encoding.UTF8);
-
- if (result.Errors.Count > 0)
- {
- Logger.Error("Error minifying css: " + result.Errors[0].Message);
- }
- else
- {
- text = result.MinifiedContent;
- _fileSystem.WriteAllText(file, text, Encoding.UTF8);
- }
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error minifying css", ex);
- }
- }
- }
-
- private void MinifyJsDirectory(string path)
- {
- foreach (var file in Directory.GetFiles(path, "*.js", SearchOption.AllDirectories))
- {
- if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
- {
- continue;
- }
- if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
- {
- continue;
- }
-
- try
- {
- var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
-
- var result = new CrockfordJsMinifier().Minify(text, false, Encoding.UTF8);
-
- if (result.Errors.Count > 0)
- {
- Logger.Error("Error minifying javascript: " + result.Errors[0].Message);
- }
- else
- {
- text = result.MinifiedContent;
- _fileSystem.WriteAllText(file, text, Encoding.UTF8);
- }
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error minifying css", ex);
- }
- }
- }
-
private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
{
foreach (var file in Directory.GetFiles(source, "*", SearchOption.TopDirectoryOnly))
@@ -566,7 +452,7 @@ namespace MediaBrowser.WebDashboard.Api
private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
{
- using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false))
+ using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, false).ConfigureAwait(false))
{
using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs
index e7247a11f..eaac3e2a0 100644
--- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs
+++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs
@@ -346,7 +346,7 @@ namespace MediaBrowser.WebDashboard.Api
if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
{
- sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem:; connect-src ws: *\">");
+ sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem: ws: wss:;\">");
}
else
{
diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
index d1308a501..b57416fab 100644
--- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
+++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj
@@ -104,6 +104,12 @@
<Content Include="dashboard-ui\camerauploadsettings.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
+ <Content Include="dashboard-ui\components\accessschedule\accessschedule.js">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="dashboard-ui\components\accessschedule\accessschedule.template.html">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
<Content Include="dashboard-ui\components\appfooter\appfooter.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -437,18 +443,6 @@
<Content Include="dashboard-ui\scripts\sections.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.checkbox.css">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.collapsible.css">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.collapsible.js">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.controlgroup.css">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.listview.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -470,18 +464,9 @@
<Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.slider.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.checkbox.js">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jqm.widget.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jquery.mobile.custom.icons.css">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="dashboard-ui\thirdparty\jquerymobile-1.4.5\jquery.mobile.custom.theme.css">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\thirdparty\paper-button-style.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -755,9 +740,6 @@
<Content Include="dashboard-ui\reports.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\livetvrecordinglist.html">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\livetvseriestimer.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -944,9 +926,6 @@
<Content Include="dashboard-ui\scripts\livetvchannel.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\scripts\livetvrecordinglist.js">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\scripts\livetvseriestimer.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -989,9 +968,6 @@
<Content Include="dashboard-ui\scripts\nowplayingpage.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
- <Content Include="dashboard-ui\scripts\ratingdialog.js">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
<Content Include="dashboard-ui\scripts\episodes.js">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs
index 0844f1f74..bf3d3c303 100644
--- a/MediaBrowser.XbmcMetadata/EntryPoint.cs
+++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs
@@ -91,6 +91,16 @@ namespace MediaBrowser.XbmcMetadata
return;
}
+ if (!item.SupportsLocalMetadata)
+ {
+ return;
+ }
+
+ if (!item.IsSaveLocalMetadataEnabled())
+ {
+ return;
+ }
+
try
{
await _providerManager.SaveMetadata(item, updateReason, new[] { BaseNfoSaver.SaverName }).ConfigureAwait(false);
diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
index 290ea588e..dc208d495 100644
--- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs
@@ -1040,12 +1040,7 @@ namespace MediaBrowser.XbmcMetadata.Savers
private static string GetPathToSave(string path, ILibraryManager libraryManager, IServerConfigurationManager config)
{
- foreach (var map in config.Configuration.PathSubstitutions)
- {
- path = libraryManager.SubstitutePath(path, map.From, map.To);
- }
-
- return path;
+ return libraryManager.GetPathAfterNetworkSubstitution(path);
}
private static bool IsPersonType(PersonInfo person, string type)
diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
index d57d22d5c..0795b97d2 100644
--- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
+++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs
@@ -64,21 +64,21 @@ namespace MediaBrowser.XbmcMetadata.Savers
writer.WriteElementString("aired", episode.PremiereDate.Value.ToLocalTime().ToString(formatString));
}
- if (episode.AirsAfterSeasonNumber.HasValue && episode.AirsAfterSeasonNumber.Value != -1)
+ if (!episode.ParentIndexNumber.HasValue || episode.ParentIndexNumber.Value == 0)
{
- writer.WriteElementString("airsafter_season", episode.AirsAfterSeasonNumber.Value.ToString(UsCulture));
- }
- if (episode.AirsBeforeEpisodeNumber.HasValue && episode.AirsBeforeEpisodeNumber.Value != -1)
- {
- writer.WriteElementString("airsbefore_episode", episode.AirsBeforeEpisodeNumber.Value.ToString(UsCulture));
- }
- if (episode.AirsBeforeSeasonNumber.HasValue && episode.AirsBeforeSeasonNumber.Value != -1)
- {
- writer.WriteElementString("airsbefore_season", episode.AirsBeforeSeasonNumber.Value.ToString(UsCulture));
- }
+ if (episode.AirsAfterSeasonNumber.HasValue && episode.AirsAfterSeasonNumber.Value != -1)
+ {
+ writer.WriteElementString("airsafter_season", episode.AirsAfterSeasonNumber.Value.ToString(UsCulture));
+ }
+ if (episode.AirsBeforeEpisodeNumber.HasValue && episode.AirsBeforeEpisodeNumber.Value != -1)
+ {
+ writer.WriteElementString("airsbefore_episode", episode.AirsBeforeEpisodeNumber.Value.ToString(UsCulture));
+ }
+ if (episode.AirsBeforeSeasonNumber.HasValue && episode.AirsBeforeSeasonNumber.Value != -1)
+ {
+ writer.WriteElementString("airsbefore_season", episode.AirsBeforeSeasonNumber.Value.ToString(UsCulture));
+ }
- if (episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value == 0)
- {
if (episode.AirsBeforeEpisodeNumber.HasValue && episode.AirsBeforeEpisodeNumber.Value != -1)
{
writer.WriteElementString("displayepisode", episode.AirsBeforeEpisodeNumber.Value.ToString(UsCulture));
diff --git a/MediaBrowser.sln b/MediaBrowser.sln
index 90b318492..22e990e8b 100644
--- a/MediaBrowser.sln
+++ b/MediaBrowser.sln
@@ -64,6 +64,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Server.Startup
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Nat", "Mono.Nat\Mono.Nat.csproj", "{D7453B88-2266-4805-B39B-2B5A2A33E1BA}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -519,6 +521,36 @@ Global
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Win32.ActiveCfg = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x64.ActiveCfg = Release|Any CPU
{08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Win32.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|Win32.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x64.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Debug|x86.Build.0 = Debug|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Any CPU.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Mixed Platforms.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Win32.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|Win32.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x64.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x64.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release Mono|x86.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Win32.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|Win32.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x64.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x64.Build.0 = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x86.ActiveCfg = Release|Any CPU
+ {D7453B88-2266-4805-B39B-2B5A2A33E1BA}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/Mono.Nat/AbstractNatDevice.cs b/Mono.Nat/AbstractNatDevice.cs
new file mode 100644
index 000000000..046cfc10f
--- /dev/null
+++ b/Mono.Nat/AbstractNatDevice.cs
@@ -0,0 +1,97 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+
+namespace Mono.Nat
+{
+ public abstract class AbstractNatDevice : INatDevice
+ {
+ private DateTime lastSeen;
+
+ protected AbstractNatDevice ()
+ {
+
+ }
+
+ public abstract IPAddress LocalAddress { get; }
+
+ public DateTime LastSeen
+ {
+ get { return lastSeen; }
+ set { lastSeen = value; }
+ }
+
+ public virtual void CreatePortMap (Mapping mapping)
+ {
+ IAsyncResult result = BeginCreatePortMap (mapping, null, null);
+ EndCreatePortMap(result);
+ }
+
+ public virtual void DeletePortMap (Mapping mapping)
+ {
+ IAsyncResult result = BeginDeletePortMap (mapping, null, mapping);
+ EndDeletePortMap(result);
+ }
+
+ public virtual Mapping[] GetAllMappings ()
+ {
+ IAsyncResult result = BeginGetAllMappings (null, null);
+ return EndGetAllMappings (result);
+ }
+
+ public virtual IPAddress GetExternalIP ()
+ {
+ IAsyncResult result = BeginGetExternalIP(null, null);
+ return EndGetExternalIP(result);
+ }
+
+ public virtual Mapping GetSpecificMapping (Protocol protocol, int port)
+ {
+ IAsyncResult result = this.BeginGetSpecificMapping (protocol, port, null, null);
+ return this.EndGetSpecificMapping(result);
+ }
+
+ public abstract IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState);
+ public abstract IAsyncResult BeginDeletePortMap (Mapping mapping, AsyncCallback callback, object asyncState);
+
+ public abstract IAsyncResult BeginGetAllMappings (AsyncCallback callback, object asyncState);
+ public abstract IAsyncResult BeginGetExternalIP (AsyncCallback callback, object asyncState);
+ public abstract IAsyncResult BeginGetSpecificMapping(Protocol protocol, int externalPort, AsyncCallback callback, object asyncState);
+
+ public abstract void EndCreatePortMap (IAsyncResult result);
+ public abstract void EndDeletePortMap (IAsyncResult result);
+
+ public abstract Mapping[] EndGetAllMappings (IAsyncResult result);
+ public abstract IPAddress EndGetExternalIP (IAsyncResult result);
+ public abstract Mapping EndGetSpecificMapping (IAsyncResult result);
+ }
+}
diff --git a/Mono.Nat/AsyncResults/AsyncResult.cs b/Mono.Nat/AsyncResults/AsyncResult.cs
new file mode 100644
index 000000000..e98e7d7ca
--- /dev/null
+++ b/Mono.Nat/AsyncResults/AsyncResult.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading;
+
+namespace Mono.Nat
+{
+ internal class AsyncResult : IAsyncResult
+ {
+ private object asyncState;
+ private AsyncCallback callback;
+ private bool completedSynchronously;
+ private bool isCompleted;
+ private Exception storedException;
+ private ManualResetEvent waitHandle;
+
+ public AsyncResult(AsyncCallback callback, object asyncState)
+ {
+ this.callback = callback;
+ this.asyncState = asyncState;
+ waitHandle = new ManualResetEvent(false);
+ }
+
+ public object AsyncState
+ {
+ get { return asyncState; }
+ }
+
+ public ManualResetEvent AsyncWaitHandle
+ {
+ get { return waitHandle; }
+ }
+
+ WaitHandle IAsyncResult.AsyncWaitHandle
+ {
+ get { return waitHandle; }
+ }
+
+ public bool CompletedSynchronously
+ {
+ get { return completedSynchronously; }
+ protected internal set { completedSynchronously = value; }
+ }
+
+ public bool IsCompleted
+ {
+ get { return isCompleted; }
+ protected internal set { isCompleted = value; }
+ }
+
+ public Exception StoredException
+ {
+ get { return storedException; }
+ }
+
+ public void Complete()
+ {
+ Complete(storedException);
+ }
+
+ public void Complete(Exception ex)
+ {
+ storedException = ex;
+ isCompleted = true;
+ waitHandle.Set();
+
+ if (callback != null)
+ callback(this);
+ }
+ }
+}
diff --git a/Mono.Nat/Enums/MapState.cs b/Mono.Nat/Enums/MapState.cs
new file mode 100644
index 000000000..5ed2abd8f
--- /dev/null
+++ b/Mono.Nat/Enums/MapState.cs
@@ -0,0 +1,36 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat
+{
+ public enum MapState
+ {
+ AlreadyMapped,
+ Available
+ }
+} \ No newline at end of file
diff --git a/Mono.Nat/Enums/ProtocolType.cs b/Mono.Nat/Enums/ProtocolType.cs
new file mode 100644
index 000000000..a1f5cbb0e
--- /dev/null
+++ b/Mono.Nat/Enums/ProtocolType.cs
@@ -0,0 +1,36 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat
+{
+ public enum Protocol
+ {
+ Tcp,
+ Udp
+ }
+} \ No newline at end of file
diff --git a/Mono.Nat/EventArgs/DeviceEventArgs.cs b/Mono.Nat/EventArgs/DeviceEventArgs.cs
new file mode 100644
index 000000000..fbbbf63e3
--- /dev/null
+++ b/Mono.Nat/EventArgs/DeviceEventArgs.cs
@@ -0,0 +1,45 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat
+{
+ public class DeviceEventArgs : EventArgs
+ {
+ private INatDevice device;
+
+ public DeviceEventArgs(INatDevice device)
+ {
+ this.device = device;
+ }
+
+ public INatDevice Device
+ {
+ get { return this.device; }
+ }
+ }
+} \ No newline at end of file
diff --git a/Mono.Nat/Exceptions/MappingException.cs b/Mono.Nat/Exceptions/MappingException.cs
new file mode 100644
index 000000000..bb2e6a69d
--- /dev/null
+++ b/Mono.Nat/Exceptions/MappingException.cs
@@ -0,0 +1,87 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Security.Permissions;
+
+namespace Mono.Nat
+{
+ [Serializable]
+ public class MappingException : Exception
+ {
+ private int errorCode;
+ private string errorText;
+
+ public int ErrorCode
+ {
+ get { return this.errorCode; }
+ }
+
+ public string ErrorText
+ {
+ get { return this.errorText; }
+ }
+
+ #region Constructors
+ public MappingException()
+ : base()
+ {
+ }
+
+ public MappingException(string message)
+ : base(message)
+ {
+ }
+
+ public MappingException(int errorCode, string errorText)
+ : base (string.Format ("Error {0}: {1}", errorCode, errorText))
+ {
+ this.errorCode = errorCode;
+ this.errorText = errorText;
+ }
+
+ public MappingException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ protected MappingException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
+ : base(info, context)
+ {
+ }
+ #endregion
+
+ [SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
+ public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
+ {
+ if(info==null) throw new ArgumentNullException("info");
+
+ this.errorCode = info.GetInt32("errorCode");
+ this.errorText = info.GetString("errorText");
+ base.GetObjectData(info, context);
+ }
+ }
+}
diff --git a/Mono.Nat/IMapper.cs b/Mono.Nat/IMapper.cs
new file mode 100644
index 000000000..b18e6cff2
--- /dev/null
+++ b/Mono.Nat/IMapper.cs
@@ -0,0 +1,50 @@
+//
+// Authors:
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+
+namespace Mono.Nat
+{
+ public enum MapperType
+ {
+ Pmp,
+ Upnp
+ }
+
+ internal interface IMapper
+ {
+ event EventHandler<DeviceEventArgs> DeviceFound;
+
+ void Map(IPAddress gatewayAddress);
+
+ void Handle(IPAddress localAddres, byte[] response);
+ }
+}
diff --git a/Mono.Nat/INatDevice.cs b/Mono.Nat/INatDevice.cs
new file mode 100644
index 000000000..c9f27055b
--- /dev/null
+++ b/Mono.Nat/INatDevice.cs
@@ -0,0 +1,62 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+
+namespace Mono.Nat
+{
+ public interface INatDevice
+ {
+ void CreatePortMap (Mapping mapping);
+ void DeletePortMap (Mapping mapping);
+
+ IPAddress LocalAddress { get; }
+ Mapping[] GetAllMappings ();
+ IPAddress GetExternalIP ();
+ Mapping GetSpecificMapping (Protocol protocol, int port);
+
+ IAsyncResult BeginCreatePortMap (Mapping mapping, AsyncCallback callback, object asyncState);
+ IAsyncResult BeginDeletePortMap (Mapping mapping, AsyncCallback callback, object asyncState);
+
+ IAsyncResult BeginGetAllMappings (AsyncCallback callback, object asyncState);
+ IAsyncResult BeginGetExternalIP (AsyncCallback callback, object asyncState);
+ IAsyncResult BeginGetSpecificMapping (Protocol protocol, int externalPort, AsyncCallback callback, object asyncState);
+
+ void EndCreatePortMap (IAsyncResult result);
+ void EndDeletePortMap (IAsyncResult result);
+
+ Mapping[] EndGetAllMappings (IAsyncResult result);
+ IPAddress EndGetExternalIP (IAsyncResult result);
+ Mapping EndGetSpecificMapping (IAsyncResult result);
+
+ DateTime LastSeen { get; set; }
+ }
+}
diff --git a/Mono.Nat/ISearcher.cs b/Mono.Nat/ISearcher.cs
new file mode 100644
index 000000000..56e438105
--- /dev/null
+++ b/Mono.Nat/ISearcher.cs
@@ -0,0 +1,51 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net.Sockets;
+using System.Net;
+
+namespace Mono.Nat
+{
+ public delegate void NatDeviceCallback(INatDevice device);
+
+ internal interface ISearcher
+ {
+ event EventHandler<DeviceEventArgs> DeviceFound;
+ event EventHandler<DeviceEventArgs> DeviceLost;
+
+ void Search();
+ void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint);
+ DateTime NextSearch { get; }
+ NatProtocol Protocol { get; }
+ }
+}
diff --git a/Mono.Nat/Mapping.cs b/Mono.Nat/Mapping.cs
new file mode 100644
index 000000000..dd49404c6
--- /dev/null
+++ b/Mono.Nat/Mapping.cs
@@ -0,0 +1,123 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat
+{
+ public class Mapping
+ {
+ private string description;
+ private DateTime expiration;
+ private int lifetime;
+ private int privatePort;
+ private Protocol protocol;
+ private int publicPort;
+
+
+
+ public Mapping (Protocol protocol, int privatePort, int publicPort)
+ : this (protocol, privatePort, publicPort, 0)
+ {
+ }
+
+ public Mapping (Protocol protocol, int privatePort, int publicPort, int lifetime)
+ {
+ this.protocol = protocol;
+ this.privatePort = privatePort;
+ this.publicPort = publicPort;
+ this.lifetime = lifetime;
+
+ if (lifetime == int.MaxValue)
+ this.expiration = DateTime.MaxValue;
+ else if (lifetime == 0)
+ this.expiration = DateTime.Now;
+ else
+ this.expiration = DateTime.Now.AddSeconds (lifetime);
+ }
+
+ public string Description
+ {
+ get { return description; }
+ set { description = value; }
+ }
+
+ public Protocol Protocol
+ {
+ get { return protocol; }
+ internal set { protocol = value; }
+ }
+
+ public int PrivatePort
+ {
+ get { return privatePort; }
+ internal set { privatePort = value; }
+ }
+
+ public int PublicPort
+ {
+ get { return publicPort; }
+ internal set { publicPort = value; }
+ }
+
+ public int Lifetime
+ {
+ get { return lifetime; }
+ internal set { lifetime = value; }
+ }
+
+ public DateTime Expiration
+ {
+ get { return expiration; }
+ internal set { expiration = value; }
+ }
+
+ public bool IsExpired ()
+ {
+ return expiration < DateTime.Now;
+ }
+
+ public override bool Equals (object obj)
+ {
+ Mapping other = obj as Mapping;
+ return other == null ? false : this.protocol == other.protocol &&
+ this.privatePort == other.privatePort && this.publicPort == other.publicPort;
+ }
+
+ public override int GetHashCode()
+ {
+ return this.protocol.GetHashCode() ^ this.privatePort.GetHashCode() ^ this.publicPort.GetHashCode();
+ }
+
+ public override string ToString( )
+ {
+ return String.Format( "Protocol: {0}, Public Port: {1}, Private Port: {2}, Description: {3}, Expiration: {4}, Lifetime: {5}",
+ this.protocol, this.publicPort, this.privatePort, this.description, this.expiration, this.lifetime );
+ }
+ }
+}
diff --git a/Mono.Nat/Mono.Nat.csproj b/Mono.Nat/Mono.Nat.csproj
new file mode 100644
index 000000000..9c2781433
--- /dev/null
+++ b/Mono.Nat/Mono.Nat.csproj
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{D7453B88-2266-4805-B39B-2B5A2A33E1BA}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Mono.Nat</RootNamespace>
+ <AssemblyName>Mono.Nat</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <TargetFrameworkProfile />
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Net.Http" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="..\SharedVersion.cs">
+ <Link>Properties\SharedVersion.cs</Link>
+ </Compile>
+ <Compile Include="AbstractNatDevice.cs" />
+ <Compile Include="AsyncResults\AsyncResult.cs" />
+ <Compile Include="Enums\MapState.cs" />
+ <Compile Include="Enums\ProtocolType.cs" />
+ <Compile Include="EventArgs\DeviceEventArgs.cs" />
+ <Compile Include="Exceptions\MappingException.cs" />
+ <Compile Include="IMapper.cs" />
+ <Compile Include="INatDevice.cs" />
+ <Compile Include="ISearcher.cs" />
+ <Compile Include="Mapping.cs" />
+ <Compile Include="NatProtocol.cs" />
+ <Compile Include="NatUtility.cs" />
+ <Compile Include="Pmp\AsyncResults\PortMapAsyncResult.cs" />
+ <Compile Include="Pmp\Mappers\PmpMapper.cs" />
+ <Compile Include="Pmp\Pmp.cs" />
+ <Compile Include="Pmp\PmpConstants.cs" />
+ <Compile Include="Pmp\PmpNatDevice.cs" />
+ <Compile Include="Pmp\Searchers\PmpSearcher.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Upnp\AsyncResults\GetAllMappingsAsyncResult.cs" />
+ <Compile Include="Upnp\AsyncResults\PortMapAsyncResult.cs" />
+ <Compile Include="Upnp\Mappers\UpnpMapper.cs" />
+ <Compile Include="Upnp\Messages\DiscoverDeviceMessage.cs" />
+ <Compile Include="Upnp\Messages\ErrorMessage.cs" />
+ <Compile Include="Upnp\Messages\GetServicesMessage.cs" />
+ <Compile Include="Upnp\Messages\Requests\CreatePortMappingMessage.cs" />
+ <Compile Include="Upnp\Messages\Requests\DeletePortMappingMessage.cs" />
+ <Compile Include="Upnp\Messages\Requests\GetExternalIPAddressMessage.cs" />
+ <Compile Include="Upnp\Messages\Requests\GetGenericPortMappingEntry.cs" />
+ <Compile Include="Upnp\Messages\Requests\GetSpecificPortMappingEntryMessage.cs" />
+ <Compile Include="Upnp\Messages\Responses\CreatePortMappingResponseMessage.cs" />
+ <Compile Include="Upnp\Messages\Responses\DeletePortMappingResponseMessage.cs" />
+ <Compile Include="Upnp\Messages\Responses\GetExternalIPAddressResponseMessage.cs" />
+ <Compile Include="Upnp\Messages\Responses\GetGenericPortMappingEntryResponseMessage.cs" />
+ <Compile Include="Upnp\Messages\UpnpMessage.cs" />
+ <Compile Include="Upnp\Searchers\UpnpSearcher.cs" />
+ <Compile Include="Upnp\Upnp.cs" />
+ <Compile Include="Upnp\UpnpNatDevice.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj">
+ <Project>{17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2}</Project>
+ <Name>MediaBrowser.Controller</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj">
+ <Project>{7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}</Project>
+ <Name>MediaBrowser.Model</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file
diff --git a/Mono.Nat/NatProtocol.cs b/Mono.Nat/NatProtocol.cs
new file mode 100644
index 000000000..ade8d921c
--- /dev/null
+++ b/Mono.Nat/NatProtocol.cs
@@ -0,0 +1,9 @@
+
+namespace Mono.Nat
+{
+ public enum NatProtocol
+ {
+ Upnp = 0,
+ Pmp = 1
+ }
+}
diff --git a/Mono.Nat/NatUtility.cs b/Mono.Nat/NatUtility.cs
new file mode 100644
index 000000000..6d91d2513
--- /dev/null
+++ b/Mono.Nat/NatUtility.cs
@@ -0,0 +1,264 @@
+//
+// Authors:
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using System.Linq;
+using System.Collections.Generic;
+using System.IO;
+using System.Net.NetworkInformation;
+using MediaBrowser.Controller.Dlna;
+using MediaBrowser.Model.Logging;
+using Mono.Nat.Pmp.Mappers;
+using Mono.Nat.Upnp.Mappers;
+
+namespace Mono.Nat
+{
+ public static class NatUtility
+ {
+ private static ManualResetEvent searching;
+ public static event EventHandler<DeviceEventArgs> DeviceFound;
+ public static event EventHandler<DeviceEventArgs> DeviceLost;
+
+ public static event EventHandler<UnhandledExceptionEventArgs> UnhandledException;
+
+ private static List<ISearcher> controllers;
+ private static bool verbose;
+
+ public static List<NatProtocol> EnabledProtocols { get; set; }
+
+ public static ILogger Logger { get; set; }
+
+ public static bool Verbose
+ {
+ get { return verbose; }
+ set { verbose = value; }
+ }
+
+ static NatUtility()
+ {
+ EnabledProtocols = new List<NatProtocol>
+ {
+ NatProtocol.Upnp,
+ NatProtocol.Pmp
+ };
+
+ searching = new ManualResetEvent(false);
+
+ controllers = new List<ISearcher>();
+ controllers.Add(UpnpSearcher.Instance);
+ controllers.Add(PmpSearcher.Instance);
+
+ controllers.ForEach(searcher =>
+ {
+ searcher.DeviceFound += (sender, args) =>
+ {
+ if (DeviceFound != null)
+ DeviceFound(sender, args);
+ };
+ searcher.DeviceLost += (sender, args) =>
+ {
+ if (DeviceLost != null)
+ DeviceLost(sender, args);
+ };
+ });
+ Thread t = new Thread(SearchAndListen);
+ t.IsBackground = true;
+ t.Start();
+ }
+
+ internal static void Log(string format, params object[] args)
+ {
+ var logger = Logger;
+ if (logger != null)
+ logger.Debug(format, args);
+ }
+
+ private static void SearchAndListen()
+ {
+ while (true)
+ {
+ searching.WaitOne();
+
+ try
+ {
+ var enabledProtocols = EnabledProtocols.ToList();
+
+ if (enabledProtocols.Contains(UpnpSearcher.Instance.Protocol))
+ {
+ Receive(UpnpSearcher.Instance, UpnpSearcher.sockets);
+ }
+ if (enabledProtocols.Contains(PmpSearcher.Instance.Protocol))
+ {
+ Receive(PmpSearcher.Instance, PmpSearcher.sockets);
+ }
+
+ foreach (ISearcher s in controllers)
+ if (s.NextSearch < DateTime.Now && enabledProtocols.Contains(s.Protocol))
+ {
+ Log("Searching for: {0}", s.GetType().Name);
+ s.Search();
+ }
+ }
+ catch (Exception e)
+ {
+ if (UnhandledException != null)
+ UnhandledException(typeof(NatUtility), new UnhandledExceptionEventArgs(e, false));
+ }
+ Thread.Sleep(10);
+ }
+ }
+
+ static void Receive (ISearcher searcher, List<UdpClient> clients)
+ {
+ IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
+ foreach (UdpClient client in clients)
+ {
+ if (client.Available > 0)
+ {
+ IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
+ byte[] data = client.Receive(ref received);
+ searcher.Handle(localAddress, data, received);
+ }
+ }
+ }
+
+ static void Receive(IMapper mapper, List<UdpClient> clients)
+ {
+ IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
+ foreach (UdpClient client in clients)
+ {
+ if (client.Available > 0)
+ {
+ IPAddress localAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
+ byte[] data = client.Receive(ref received);
+ mapper.Handle(localAddress, data);
+ }
+ }
+ }
+
+ public static void StartDiscovery ()
+ {
+ searching.Set();
+ }
+
+ public static void StopDiscovery ()
+ {
+ searching.Reset();
+ }
+
+ //This is for when you know the Gateway IP and want to skip the costly search...
+ public static void DirectMap(IPAddress gatewayAddress, MapperType type)
+ {
+ IMapper mapper;
+ switch (type)
+ {
+ case MapperType.Pmp:
+ mapper = new PmpMapper();
+ break;
+ case MapperType.Upnp:
+ mapper = new UpnpMapper();
+ mapper.DeviceFound += (sender, args) =>
+ {
+ if (DeviceFound != null)
+ DeviceFound(sender, args);
+ };
+ mapper.Map(gatewayAddress);
+ break;
+ default:
+ throw new InvalidOperationException("Unsuported type given");
+
+ }
+ searching.Reset();
+
+ }
+
+ //So then why is it here? -Nick
+ [Obsolete ("This method serves no purpose and shouldn't be used")]
+ public static IPAddress[] GetLocalAddresses (bool includeIPv6)
+ {
+ List<IPAddress> addresses = new List<IPAddress> ();
+
+ IPHostEntry hostInfo = Dns.GetHostEntry (Dns.GetHostName ());
+ foreach (IPAddress address in hostInfo.AddressList) {
+ if (address.AddressFamily == AddressFamily.InterNetwork ||
+ (includeIPv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) {
+ addresses.Add (address);
+ }
+ }
+
+ return addresses.ToArray ();
+ }
+
+ //checks if an IP address is a private address space as defined by RFC 1918
+ public static bool IsPrivateAddressSpace (IPAddress address)
+ {
+ byte[] ba = address.GetAddressBytes ();
+
+ switch ((int)ba[0]) {
+ case 10:
+ return true; //10.x.x.x
+ case 172:
+ return ((int)ba[1] & 16) != 0; //172.16-31.x.x
+ case 192:
+ return (int)ba[1] == 168; //192.168.x.x
+ default:
+ return false;
+ }
+ }
+
+ public static void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint, NatProtocol protocol)
+ {
+ switch (protocol)
+ {
+ case NatProtocol.Upnp:
+ UpnpSearcher.Instance.Handle(localAddress, response, endpoint);
+ break;
+ case NatProtocol.Pmp:
+ PmpSearcher.Instance.Handle(localAddress, response, endpoint);
+ break;
+ default:
+ throw new ArgumentException("Unexpected protocol: " + protocol);
+ }
+ }
+
+ public static void Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint, NatProtocol protocol)
+ {
+ switch (protocol)
+ {
+ case NatProtocol.Upnp:
+ UpnpSearcher.Instance.Handle(localAddress, deviceInfo, endpoint);
+ break;
+ default:
+ throw new ArgumentException("Unexpected protocol: " + protocol);
+ }
+ }
+ }
+}
diff --git a/Mono.Nat/Pmp/AsyncResults/PortMapAsyncResult.cs b/Mono.Nat/Pmp/AsyncResults/PortMapAsyncResult.cs
new file mode 100644
index 000000000..c8ccf5435
--- /dev/null
+++ b/Mono.Nat/Pmp/AsyncResults/PortMapAsyncResult.cs
@@ -0,0 +1,52 @@
+//
+// Authors:
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat.Pmp
+{
+ internal class PortMapAsyncResult : AsyncResult
+ {
+ private Mapping mapping;
+
+ internal PortMapAsyncResult (Mapping mapping, AsyncCallback callback, object asyncState)
+ : base (callback, asyncState)
+ {
+ this.mapping = mapping;
+ }
+
+ internal PortMapAsyncResult (Protocol protocol, int port, int lifetime, AsyncCallback callback, object asyncState)
+ : base (callback, asyncState)
+ {
+ this.mapping = new Mapping (protocol, port, port, lifetime);
+ }
+
+ internal Mapping Mapping
+ {
+ get { return mapping; }
+ }
+ }
+}
diff --git a/Mono.Nat/Pmp/Mappers/PmpMapper.cs b/Mono.Nat/Pmp/Mappers/PmpMapper.cs
new file mode 100644
index 000000000..f33ca44c3
--- /dev/null
+++ b/Mono.Nat/Pmp/Mappers/PmpMapper.cs
@@ -0,0 +1,83 @@
+//
+// Authors:
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using Mono.Nat.Pmp;
+
+namespace Mono.Nat.Pmp.Mappers
+{
+ internal class PmpMapper : Pmp, IMapper
+ {
+ public event EventHandler<DeviceEventArgs> DeviceFound;
+
+ static PmpMapper()
+ {
+ CreateSocketsAndAddGateways();
+ }
+
+ public void Map(IPAddress gatewayAddress)
+ {
+ sockets.ForEach(x => Map(x, gatewayAddress));
+ }
+
+ void Map(UdpClient client, IPAddress gatewayAddress)
+ {
+ // The nat-pmp search message. Must be sent to GatewayIP:53531
+ byte[] buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
+
+ client.Send(buffer, buffer.Length, new IPEndPoint(gatewayAddress, PmpConstants.ServerPort));
+ }
+
+ public void Handle(IPAddress localAddres, byte[] response)
+ {
+ //if (!IsSearchAddress(endpoint.Address))
+ // return;
+ if (response.Length != 12)
+ return;
+ if (response[0] != PmpConstants.Version)
+ return;
+ if (response[1] != PmpConstants.ServerNoop)
+ return;
+ int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
+ if (errorcode != 0)
+ NatUtility.Log("Non zero error: {0}", errorcode);
+
+ IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
+ OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(localAddres, publicIp)));
+ }
+
+ private void OnDeviceFound(DeviceEventArgs args)
+ {
+ if (DeviceFound != null)
+ DeviceFound(this, args);
+ }
+ }
+}
diff --git a/Mono.Nat/Pmp/Pmp.cs b/Mono.Nat/Pmp/Pmp.cs
new file mode 100644
index 000000000..6795561b1
--- /dev/null
+++ b/Mono.Nat/Pmp/Pmp.cs
@@ -0,0 +1,118 @@
+//
+// Authors:
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Text;
+
+namespace Mono.Nat.Pmp
+{
+ internal abstract class Pmp
+ {
+ public static List<UdpClient> sockets;
+ protected static Dictionary<UdpClient, List<IPEndPoint>> gatewayLists;
+
+ internal static void CreateSocketsAndAddGateways()
+ {
+ sockets = new List<UdpClient>();
+ gatewayLists = new Dictionary<UdpClient, List<IPEndPoint>>();
+
+ try
+ {
+ foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces())
+ {
+ if (n.OperationalStatus != OperationalStatus.Up && n.OperationalStatus != OperationalStatus.Unknown)
+ continue;
+ IPInterfaceProperties properties = n.GetIPProperties();
+ List<IPEndPoint> gatewayList = new List<IPEndPoint>();
+
+ foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
+ {
+ if (gateway.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ gatewayList.Add(new IPEndPoint(gateway.Address, PmpConstants.ServerPort));
+ }
+ }
+ if (gatewayList.Count == 0)
+ {
+ /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
+ foreach (var gw2 in properties.DnsAddresses)
+ {
+ if (gw2.AddressFamily == AddressFamily.InterNetwork)
+ {
+ gatewayList.Add(new IPEndPoint(gw2, PmpConstants.ServerPort));
+ }
+ }
+ foreach (var unicast in properties.UnicastAddresses)
+ {
+ if (/*unicast.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
+ && unicast.AddressPreferredLifetime != UInt32.MaxValue
+ && */unicast.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ var bytes = unicast.Address.GetAddressBytes();
+ bytes[3] = 1;
+ gatewayList.Add(new IPEndPoint(new IPAddress(bytes), PmpConstants.ServerPort));
+ }
+ }
+ }
+
+ if (gatewayList.Count > 0)
+ {
+ foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)
+ {
+ if (address.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ UdpClient client;
+
+ try
+ {
+ client = new UdpClient(new IPEndPoint(address.Address, 0));
+ }
+ catch (SocketException)
+ {
+ continue; // Move on to the next address.
+ }
+
+ gatewayLists.Add(client, gatewayList);
+ sockets.Add(client);
+ }
+ }
+ }
+ }
+ }
+ catch (Exception)
+ {
+ // NAT-PMP does not use multicast, so there isn't really a good fallback.
+ }
+ }
+ }
+}
diff --git a/Mono.Nat/Pmp/PmpConstants.cs b/Mono.Nat/Pmp/PmpConstants.cs
new file mode 100644
index 000000000..ff3eb6230
--- /dev/null
+++ b/Mono.Nat/Pmp/PmpConstants.cs
@@ -0,0 +1,56 @@
+//
+// Authors:
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat.Pmp
+{
+ internal static class PmpConstants
+ {
+ public const byte Version = (byte)0;
+
+ public const byte OperationCode = (byte)0;
+ public const byte OperationCodeUdp = (byte)1;
+ public const byte OperationCodeTcp = (byte)2;
+ public const byte ServerNoop = (byte)128;
+
+ public const int ClientPort = 5350;
+ public const int ServerPort = 5351;
+
+ public const int RetryDelay = 250;
+ public const int RetryAttempts = 9;
+
+ public const int RecommendedLeaseTime = 60 * 60;
+ public const int DefaultLeaseTime = RecommendedLeaseTime;
+
+ public const short ResultCodeSuccess = 0;
+ public const short ResultCodeUnsupportedVersion = 1;
+ public const short ResultCodeNotAuthorized = 2;
+ public const short ResultCodeNetworkFailure = 3;
+ public const short ResultCodeOutOfResources = 4;
+ public const short ResultCodeUnsupportedOperationCode = 5;
+ }
+} \ No newline at end of file
diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs
new file mode 100644
index 000000000..9a2962c4d
--- /dev/null
+++ b/Mono.Nat/Pmp/PmpNatDevice.cs
@@ -0,0 +1,347 @@
+//
+// Authors:
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace Mono.Nat.Pmp
+{
+ internal sealed class PmpNatDevice : AbstractNatDevice, IEquatable<PmpNatDevice>
+ {
+ private AsyncResult externalIpResult;
+ private bool pendingOp;
+ private IPAddress localAddress;
+ private IPAddress publicAddress;
+
+ internal PmpNatDevice (IPAddress localAddress, IPAddress publicAddress)
+ {
+ this.localAddress = localAddress;
+ this.publicAddress = publicAddress;
+ }
+
+ public override IPAddress LocalAddress
+ {
+ get { return localAddress; }
+ }
+
+ public override IPAddress GetExternalIP ()
+ {
+ return publicAddress;
+ }
+
+ public override IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
+ {
+ PortMapAsyncResult pmar = new PortMapAsyncResult (mapping.Protocol, mapping.PublicPort, PmpConstants.DefaultLeaseTime, callback, asyncState);
+ ThreadPool.QueueUserWorkItem (delegate
+ {
+ try
+ {
+ CreatePortMap(pmar.Mapping, true);
+ pmar.Complete();
+ }
+ catch (Exception e)
+ {
+ pmar.Complete(e);
+ }
+ });
+ return pmar;
+ }
+
+ public override IAsyncResult BeginDeletePortMap (Mapping mapping, AsyncCallback callback, object asyncState)
+ {
+ PortMapAsyncResult pmar = new PortMapAsyncResult (mapping, callback, asyncState);
+ ThreadPool.QueueUserWorkItem (delegate {
+ try {
+ CreatePortMap(pmar.Mapping, false);
+ pmar.Complete();
+ } catch (Exception e) {
+ pmar.Complete(e);
+ }
+ });
+ return pmar;
+ }
+
+ public override void EndCreatePortMap (IAsyncResult result)
+ {
+ PortMapAsyncResult pmar = result as PortMapAsyncResult;
+ pmar.AsyncWaitHandle.WaitOne ();
+ }
+
+ public override void EndDeletePortMap (IAsyncResult result)
+ {
+ PortMapAsyncResult pmar = result as PortMapAsyncResult;
+ pmar.AsyncWaitHandle.WaitOne ();
+ }
+
+ public override IAsyncResult BeginGetAllMappings (AsyncCallback callback, object asyncState)
+ {
+ //NAT-PMP does not specify a way to get all port mappings
+ throw new NotSupportedException ();
+ }
+
+ public override IAsyncResult BeginGetExternalIP (AsyncCallback callback, object asyncState)
+ {
+ StartOp(ref externalIpResult, callback, asyncState);
+ AsyncResult result = externalIpResult;
+ result.Complete();
+ return result;
+ }
+
+ public override IAsyncResult BeginGetSpecificMapping (Protocol protocol, int port, AsyncCallback callback, object asyncState)
+ {
+ //NAT-PMP does not specify a way to get a specific port map
+ throw new NotSupportedException ();
+ }
+
+ public override Mapping[] EndGetAllMappings (IAsyncResult result)
+ {
+ //NAT-PMP does not specify a way to get all port mappings
+ throw new NotSupportedException ();
+ }
+
+ public override IPAddress EndGetExternalIP (IAsyncResult result)
+ {
+ EndOp(result, ref externalIpResult);
+ return publicAddress;
+ }
+
+ private void StartOp(ref AsyncResult result, AsyncCallback callback, object asyncState)
+ {
+ if (pendingOp == true)
+ throw new InvalidOperationException("Can only have one simultaenous async operation");
+
+ pendingOp = true;
+ result = new AsyncResult(callback, asyncState);
+ }
+
+ private void EndOp(IAsyncResult supplied, ref AsyncResult actual)
+ {
+ if (supplied == null)
+ throw new ArgumentNullException("result");
+
+ if (supplied != actual)
+ throw new ArgumentException("Supplied IAsyncResult does not match the stored result");
+
+ if (!supplied.IsCompleted)
+ supplied.AsyncWaitHandle.WaitOne();
+
+ if (actual.StoredException != null)
+ throw actual.StoredException;
+
+ pendingOp = false;
+ actual = null;
+ }
+
+ public override Mapping EndGetSpecificMapping (IAsyncResult result)
+ {
+ //NAT-PMP does not specify a way to get a specific port map
+ throw new NotSupportedException ();
+ }
+
+ public override bool Equals(object obj)
+ {
+ PmpNatDevice device = obj as PmpNatDevice;
+ return (device == null) ? false : this.Equals(device);
+ }
+
+ public override int GetHashCode ()
+ {
+ return this.publicAddress.GetHashCode();
+ }
+
+ public bool Equals (PmpNatDevice other)
+ {
+ return (other == null) ? false : this.publicAddress.Equals(other.publicAddress);
+ }
+
+ private Mapping CreatePortMap (Mapping mapping, bool create)
+ {
+ List<byte> package = new List<byte> ();
+
+ package.Add (PmpConstants.Version);
+ package.Add (mapping.Protocol == Protocol.Tcp ? PmpConstants.OperationCodeTcp : PmpConstants.OperationCodeUdp);
+ package.Add ((byte)0); //reserved
+ package.Add ((byte)0); //reserved
+ package.AddRange (BitConverter.GetBytes (IPAddress.HostToNetworkOrder((short)mapping.PrivatePort)));
+ package.AddRange (BitConverter.GetBytes (create ? IPAddress.HostToNetworkOrder((short)mapping.PublicPort) : (short)0));
+ package.AddRange (BitConverter.GetBytes (IPAddress.HostToNetworkOrder(mapping.Lifetime)));
+
+ CreatePortMapAsyncState state = new CreatePortMapAsyncState ();
+ state.Buffer = package.ToArray ();
+ state.Mapping = mapping;
+
+ ThreadPool.QueueUserWorkItem (new WaitCallback (CreatePortMapAsync), state);
+ WaitHandle.WaitAll (new WaitHandle[] {state.ResetEvent});
+
+ if (!state.Success) {
+ string type = create ? "create" : "delete";
+ throw new MappingException (String.Format ("Failed to {0} portmap (protocol={1}, private port={2}", type, mapping.Protocol, mapping.PrivatePort));
+ }
+
+ return state.Mapping;
+ }
+
+ private void CreatePortMapAsync (object obj)
+ {
+ CreatePortMapAsyncState state = obj as CreatePortMapAsyncState;
+
+ UdpClient udpClient = new UdpClient ();
+ CreatePortMapListenState listenState = new CreatePortMapListenState (state, udpClient);
+
+ int attempt = 0;
+ int delay = PmpConstants.RetryDelay;
+
+ ThreadPool.QueueUserWorkItem (new WaitCallback (CreatePortMapListen), listenState);
+
+ while (attempt < PmpConstants.RetryAttempts && !listenState.Success) {
+ udpClient.Send (state.Buffer, state.Buffer.Length, new IPEndPoint (localAddress, PmpConstants.ServerPort));
+ listenState.UdpClientReady.Set();
+
+ attempt++;
+ delay *= 2;
+ Thread.Sleep (delay);
+ }
+
+ state.Success = listenState.Success;
+
+ udpClient.Close ();
+ state.ResetEvent.Set ();
+ }
+
+ private void CreatePortMapListen (object obj)
+ {
+ CreatePortMapListenState state = obj as CreatePortMapListenState;
+
+ UdpClient udpClient = state.UdpClient;
+ state.UdpClientReady.WaitOne(); // Evidently UdpClient has some lazy-init Send/Receive race?
+ IPEndPoint endPoint = new IPEndPoint (localAddress, PmpConstants.ServerPort);
+
+ while (!state.Success)
+ {
+ byte[] data;
+ try
+ {
+ data = udpClient.Receive(ref endPoint);
+ }
+ catch (SocketException)
+ {
+ state.Success = false;
+ return;
+ }
+
+ catch (ObjectDisposedException)
+ {
+ state.Success = false;
+ return;
+ }
+
+ if (data.Length < 16)
+ continue;
+
+ if (data[0] != PmpConstants.Version)
+ continue;
+
+ byte opCode = (byte)(data[1] & (byte)127);
+
+ Protocol protocol = Protocol.Tcp;
+ if (opCode == PmpConstants.OperationCodeUdp)
+ protocol = Protocol.Udp;
+
+ short resultCode = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 2));
+ uint epoch = (uint)IPAddress.NetworkToHostOrder (BitConverter.ToInt32 (data, 4));
+
+ int privatePort = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 8));
+ int publicPort = IPAddress.NetworkToHostOrder (BitConverter.ToInt16 (data, 10));
+
+ uint lifetime = (uint)IPAddress.NetworkToHostOrder (BitConverter.ToInt32 (data, 12));
+
+ if (publicPort < 0 || privatePort < 0 || resultCode != PmpConstants.ResultCodeSuccess)
+ {
+ state.Success = false;
+ return;
+ }
+
+ if (lifetime == 0)
+ {
+ //mapping was deleted
+ state.Success = true;
+ state.Mapping = null;
+ return;
+ }
+ else
+ {
+ //mapping was created
+ //TODO: verify that the private port+protocol are a match
+ Mapping mapping = state.Mapping;
+ mapping.PublicPort = publicPort;
+ mapping.Protocol = protocol;
+ mapping.Expiration = DateTime.Now.AddSeconds (lifetime);
+
+ state.Success = true;
+ }
+ }
+ }
+
+
+ /// <summary>
+ /// Overridden.
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString( )
+ {
+ return String.Format( "PmpNatDevice - Local Address: {0}, Public IP: {1}, Last Seen: {2}",
+ this.localAddress, this.publicAddress, this.LastSeen );
+ }
+
+
+ private class CreatePortMapAsyncState
+ {
+ internal byte[] Buffer;
+ internal ManualResetEvent ResetEvent = new ManualResetEvent (false);
+ internal Mapping Mapping;
+
+ internal bool Success;
+ }
+
+ private class CreatePortMapListenState
+ {
+ internal volatile bool Success;
+ internal Mapping Mapping;
+ internal UdpClient UdpClient;
+ internal ManualResetEvent UdpClientReady;
+
+ internal CreatePortMapListenState (CreatePortMapAsyncState state, UdpClient client)
+ {
+ Mapping = state.Mapping;
+ UdpClient = client; UdpClientReady = new ManualResetEvent(false);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/Mono.Nat/Pmp/Searchers/PmpSearcher.cs b/Mono.Nat/Pmp/Searchers/PmpSearcher.cs
new file mode 100644
index 000000000..df0273ccb
--- /dev/null
+++ b/Mono.Nat/Pmp/Searchers/PmpSearcher.cs
@@ -0,0 +1,149 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+using Mono.Nat.Pmp;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Linq;
+
+namespace Mono.Nat
+{
+ internal class PmpSearcher : Pmp.Pmp, ISearcher
+ {
+ static PmpSearcher instance = new PmpSearcher();
+
+
+ public static PmpSearcher Instance
+ {
+ get { return instance; }
+ }
+
+ private int timeout;
+ private DateTime nextSearch;
+ public event EventHandler<DeviceEventArgs> DeviceFound;
+ public event EventHandler<DeviceEventArgs> DeviceLost;
+
+ static PmpSearcher()
+ {
+ CreateSocketsAndAddGateways();
+ }
+
+ PmpSearcher()
+ {
+ timeout = 250;
+ }
+
+ public void Search()
+ {
+ foreach (UdpClient s in sockets)
+ {
+ try
+ {
+ Search(s);
+ }
+ catch
+ {
+ // Ignore any search errors
+ }
+ }
+ }
+
+ void Search (UdpClient client)
+ {
+ // Sort out the time for the next search first. The spec says the
+ // timeout should double after each attempt. Once it reaches 64 seconds
+ // (and that attempt fails), assume no devices available
+ nextSearch = DateTime.Now.AddMilliseconds(timeout);
+ timeout *= 2;
+
+ // We've tried 9 times as per spec, try searching again in 5 minutes
+ if (timeout == 128 * 1000)
+ {
+ timeout = 250;
+ nextSearch = DateTime.Now.AddMinutes(10);
+ return;
+ }
+
+ // The nat-pmp search message. Must be sent to GatewayIP:53531
+ byte[] buffer = new byte[] { PmpConstants.Version, PmpConstants.OperationCode };
+ foreach (IPEndPoint gatewayEndpoint in gatewayLists[client])
+ client.Send(buffer, buffer.Length, gatewayEndpoint);
+ }
+
+ bool IsSearchAddress(IPAddress address)
+ {
+ foreach (List<IPEndPoint> gatewayList in gatewayLists.Values)
+ foreach (IPEndPoint gatewayEndpoint in gatewayList)
+ if (gatewayEndpoint.Address.Equals(address))
+ return true;
+ return false;
+ }
+
+ public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
+ {
+ if (!IsSearchAddress(endpoint.Address))
+ return;
+ if (response.Length != 12)
+ return;
+ if (response[0] != PmpConstants.Version)
+ return;
+ if (response[1] != PmpConstants.ServerNoop)
+ return;
+ int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2));
+ if (errorcode != 0)
+ NatUtility.Log("Non zero error: {0}", errorcode);
+
+ IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] });
+ nextSearch = DateTime.Now.AddMinutes(5);
+ timeout = 250;
+ OnDeviceFound(new DeviceEventArgs(new PmpNatDevice(endpoint.Address, publicIp)));
+ }
+
+ public DateTime NextSearch
+ {
+ get { return nextSearch; }
+ }
+ private void OnDeviceFound(DeviceEventArgs args)
+ {
+ if (DeviceFound != null)
+ DeviceFound(this, args);
+ }
+
+ public NatProtocol Protocol
+ {
+ get { return NatProtocol.Pmp; }
+ }
+ }
+}
diff --git a/Mono.Nat/Properties/AssemblyInfo.cs b/Mono.Nat/Properties/AssemblyInfo.cs
new file mode 100644
index 000000000..c3c3101de
--- /dev/null
+++ b/Mono.Nat/Properties/AssemblyInfo.cs
@@ -0,0 +1,31 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Mono.Nat")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Mono.Nat")]
+[assembly: AssemblyCopyright("Copyright © 2016")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("d7453b88-2266-4805-b39b-2b5a2a33e1ba")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+// \ No newline at end of file
diff --git a/Mono.Nat/Upnp/AsyncResults/GetAllMappingsAsyncResult.cs b/Mono.Nat/Upnp/AsyncResults/GetAllMappingsAsyncResult.cs
new file mode 100644
index 000000000..51ecfbaf0
--- /dev/null
+++ b/Mono.Nat/Upnp/AsyncResults/GetAllMappingsAsyncResult.cs
@@ -0,0 +1,56 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetAllMappingsAsyncResult : PortMapAsyncResult
+ {
+ private List<Mapping> mappings;
+ private Mapping specificMapping;
+
+ public GetAllMappingsAsyncResult(WebRequest request, AsyncCallback callback, object asyncState)
+ : base(request, callback, asyncState)
+ {
+ mappings = new List<Mapping>();
+ }
+
+ public List<Mapping> Mappings
+ {
+ get { return this.mappings; }
+ }
+
+ public Mapping SpecificMapping
+ {
+ get { return this.specificMapping; }
+ set { this.specificMapping = value; }
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/AsyncResults/PortMapAsyncResult.cs b/Mono.Nat/Upnp/AsyncResults/PortMapAsyncResult.cs
new file mode 100644
index 000000000..d8ac3fe61
--- /dev/null
+++ b/Mono.Nat/Upnp/AsyncResults/PortMapAsyncResult.cs
@@ -0,0 +1,75 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+
+using System;
+using System.Net;
+using System.Threading;
+
+namespace Mono.Nat.Upnp
+{
+ internal class PortMapAsyncResult : AsyncResult
+ {
+ private WebRequest request;
+ private MessageBase savedMessage;
+
+ protected PortMapAsyncResult(WebRequest request, AsyncCallback callback, object asyncState)
+ : base (callback, asyncState)
+ {
+ this.request = request;
+ }
+
+ internal WebRequest Request
+ {
+ get { return this.request; }
+ set { this.request = value; }
+ }
+
+ internal MessageBase SavedMessage
+ {
+ get { return this.savedMessage; }
+ set { this.savedMessage = value; }
+ }
+
+ internal static PortMapAsyncResult Create (MessageBase message, WebRequest request, AsyncCallback storedCallback, object asyncState)
+ {
+ if (message is GetGenericPortMappingEntry)
+ return new GetAllMappingsAsyncResult(request, storedCallback, asyncState);
+
+ if (message is GetSpecificPortMappingEntryMessage)
+ {
+ GetSpecificPortMappingEntryMessage mapMessage = (GetSpecificPortMappingEntryMessage)message;
+ GetAllMappingsAsyncResult result = new GetAllMappingsAsyncResult(request, storedCallback, asyncState);
+
+ result.SpecificMapping = new Mapping(mapMessage.protocol, 0, mapMessage.externalPort, 0);
+ return result;
+ }
+
+ return new PortMapAsyncResult(request, storedCallback, asyncState);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Mappers/UpnpMapper.cs b/Mono.Nat/Upnp/Mappers/UpnpMapper.cs
new file mode 100644
index 000000000..6f2716805
--- /dev/null
+++ b/Mono.Nat/Upnp/Mappers/UpnpMapper.cs
@@ -0,0 +1,110 @@
+//
+// Authors:
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+
+namespace Mono.Nat.Upnp.Mappers
+{
+ internal class UpnpMapper : Upnp, IMapper
+ {
+
+ public event EventHandler<DeviceEventArgs> DeviceFound;
+
+ public UdpClient Client { get; set; }
+
+ public UpnpMapper()
+ {
+ //Bind to local port 1900 for ssdp responses
+ Client = new UdpClient(1900);
+ }
+
+ public void Map(IPAddress gatewayAddress)
+ {
+ //Get the httpu request payload
+ byte[] data = DiscoverDeviceMessage.EncodeUnicast(gatewayAddress);
+
+ Client.Send(data, data.Length, new IPEndPoint(gatewayAddress, 1900));
+
+ new Thread(Receive).Start();
+ }
+
+ public void Receive()
+ {
+ while (true)
+ {
+ IPEndPoint received = new IPEndPoint(IPAddress.Parse("192.168.0.1"), 5351);
+ if (Client.Available > 0)
+ {
+ IPAddress localAddress = ((IPEndPoint)Client.Client.LocalEndPoint).Address;
+ byte[] data = Client.Receive(ref received);
+ Handle(localAddress, data, received);
+ }
+ }
+ }
+
+ public void Handle(IPAddress localAddres, byte[] response)
+ {
+ Handle(localAddres, response, null);
+ }
+
+ public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
+ {
+ // No matter what, this method should never throw an exception. If something goes wrong
+ // we should still be in a position to handle the next reply correctly.
+ try
+ {
+ UpnpNatDevice d = base.Handle(localAddress, response, endpoint);
+ d.GetServicesList(DeviceSetupComplete);
+ }
+ catch (Exception ex)
+ {
+ Trace.WriteLine("Unhandled exception when trying to decode a device's response Send me the following data: ");
+ Trace.WriteLine("ErrorMessage:");
+ Trace.WriteLine(ex.Message);
+ Trace.WriteLine("Data string:");
+ Trace.WriteLine(Encoding.UTF8.GetString(response));
+ }
+ }
+
+ private void DeviceSetupComplete(INatDevice device)
+ {
+ OnDeviceFound(new DeviceEventArgs(device));
+ }
+
+ private void OnDeviceFound(DeviceEventArgs args)
+ {
+ if (DeviceFound != null)
+ DeviceFound(this, args);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/DiscoverDeviceMessage.cs b/Mono.Nat/Upnp/Messages/DiscoverDeviceMessage.cs
new file mode 100644
index 000000000..87f5835a6
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/DiscoverDeviceMessage.cs
@@ -0,0 +1,60 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Net;
+using System.Text;
+
+namespace Mono.Nat.Upnp
+{
+ internal static class DiscoverDeviceMessage
+ {
+ /// <summary>
+ /// The message sent to discover all uPnP devices on the network
+ /// </summary>
+ /// <returns></returns>
+ public static byte[] EncodeSSDP()
+ {
+ string s = "M-SEARCH * HTTP/1.1\r\n"
+ + "HOST: 239.255.255.250:1900\r\n"
+ + "MAN: \"ssdp:discover\"\r\n"
+ + "MX: 3\r\n"
+ + "ST: ssdp:all\r\n\r\n";
+ return UTF8Encoding.ASCII.GetBytes(s);
+ }
+
+ public static byte[] EncodeUnicast(IPAddress gatewayAddress)
+ {
+ //Format obtained from http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf pg 31
+ //This method only works with upnp 1.1 routers... unfortunately
+ string s = "M-SEARCH * HTTP/1.1\r\n"
+ + "HOST: " + gatewayAddress + ":1900\r\n"
+ + "MAN: \"ssdp:discover\"\r\n"
+ + "ST: ssdp:all\r\n\r\n";
+ //+ "USER-AGENT: unix/5.1 UPnP/1.1 MyProduct/1.0\r\n\r\n";
+ return UTF8Encoding.ASCII.GetBytes(s);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/ErrorMessage.cs b/Mono.Nat/Upnp/Messages/ErrorMessage.cs
new file mode 100644
index 000000000..ce5270e9b
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/ErrorMessage.cs
@@ -0,0 +1,63 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Nat.Upnp
+{
+ internal class ErrorMessage : MessageBase
+ {
+ #region Member Variables
+ public string Description
+ {
+ get { return this.description; }
+ }
+ private string description;
+
+ public int ErrorCode
+ {
+ get { return this.errorCode; }
+ }
+ private int errorCode;
+ #endregion
+
+
+ #region Constructors
+ public ErrorMessage(int errorCode, string description)
+ :base(null)
+ {
+ this.description = description;
+ this.errorCode = errorCode;
+ }
+ #endregion
+
+
+ public override System.Net.WebRequest Encode(out byte[] body)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
new file mode 100644
index 000000000..c5d7bce70
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs
@@ -0,0 +1,62 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Diagnostics;
+using System.Net;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetServicesMessage : MessageBase
+ {
+ private string servicesDescriptionUrl;
+ private EndPoint hostAddress;
+
+ public GetServicesMessage(string description, EndPoint hostAddress)
+ :base(null)
+ {
+ if (string.IsNullOrEmpty(description))
+ Trace.WriteLine("Description is null");
+
+ if (hostAddress == null)
+ Trace.WriteLine("hostaddress is null");
+
+ this.servicesDescriptionUrl = description;
+ this.hostAddress = hostAddress;
+ }
+
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://" + this.hostAddress.ToString() + this.servicesDescriptionUrl);
+ req.Headers.Add("ACCEPT-LANGUAGE", "en");
+ req.Method = "GET";
+
+ body = new byte[0];
+ return req;
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs b/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs
new file mode 100644
index 000000000..da650fb41
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Requests/CreatePortMappingMessage.cs
@@ -0,0 +1,75 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Net;
+using System.IO;
+using System.Globalization;
+using System.Text;
+using System.Xml;
+
+namespace Mono.Nat.Upnp
+{
+ internal class CreatePortMappingMessage : MessageBase
+ {
+ #region Private Fields
+
+ private IPAddress localIpAddress;
+ private Mapping mapping;
+
+ #endregion
+
+
+ #region Constructors
+ public CreatePortMappingMessage(Mapping mapping, IPAddress localIpAddress, UpnpNatDevice device)
+ : base(device)
+ {
+ this.mapping = mapping;
+ this.localIpAddress = localIpAddress;
+ }
+ #endregion
+
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ CultureInfo culture = CultureInfo.InvariantCulture;
+
+ StringBuilder builder = new StringBuilder(256);
+ XmlWriter writer = CreateWriter(builder);
+
+ WriteFullElement(writer, "NewRemoteHost", string.Empty);
+ WriteFullElement(writer, "NewExternalPort", this.mapping.PublicPort.ToString(culture));
+ WriteFullElement(writer, "NewProtocol", this.mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP");
+ WriteFullElement(writer, "NewInternalPort", this.mapping.PrivatePort.ToString(culture));
+ WriteFullElement(writer, "NewInternalClient", this.localIpAddress.ToString());
+ WriteFullElement(writer, "NewEnabled", "1");
+ WriteFullElement(writer, "NewPortMappingDescription", string.IsNullOrEmpty(mapping.Description) ? "Mono.Nat" : mapping.Description);
+ WriteFullElement(writer, "NewLeaseDuration", mapping.Lifetime.ToString());
+
+ writer.Flush();
+ return CreateRequest("AddPortMapping", builder.ToString(), out body);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Requests/DeletePortMappingMessage.cs b/Mono.Nat/Upnp/Messages/Requests/DeletePortMappingMessage.cs
new file mode 100644
index 000000000..d9be89a69
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Requests/DeletePortMappingMessage.cs
@@ -0,0 +1,57 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Net;
+using System.IO;
+using System.Text;
+using System.Xml;
+
+namespace Mono.Nat.Upnp
+{
+ internal class DeletePortMappingMessage : MessageBase
+ {
+ private Mapping mapping;
+
+ public DeletePortMappingMessage(Mapping mapping, UpnpNatDevice device)
+ : base(device)
+ {
+ this.mapping = mapping;
+ }
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ StringBuilder builder = new StringBuilder(256);
+ XmlWriter writer = CreateWriter(builder);
+
+ WriteFullElement(writer, "NewRemoteHost", string.Empty);
+ WriteFullElement(writer, "NewExternalPort", mapping.PublicPort.ToString(MessageBase.Culture));
+ WriteFullElement(writer, "NewProtocol", mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP");
+
+ writer.Flush();
+ return CreateRequest("DeletePortMapping", builder.ToString(), out body);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Requests/GetExternalIPAddressMessage.cs b/Mono.Nat/Upnp/Messages/Requests/GetExternalIPAddressMessage.cs
new file mode 100644
index 000000000..8f97002ea
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Requests/GetExternalIPAddressMessage.cs
@@ -0,0 +1,51 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+using System.IO;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetExternalIPAddressMessage : MessageBase
+ {
+
+ #region Constructors
+ public GetExternalIPAddressMessage(UpnpNatDevice device)
+ :base(device)
+ {
+ }
+ #endregion
+
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ return CreateRequest("GetExternalIPAddress", string.Empty, out body);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Requests/GetGenericPortMappingEntry.cs b/Mono.Nat/Upnp/Messages/Requests/GetGenericPortMappingEntry.cs
new file mode 100644
index 000000000..c0c555881
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Requests/GetGenericPortMappingEntry.cs
@@ -0,0 +1,55 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetGenericPortMappingEntry : MessageBase
+ {
+ private int index;
+
+ public GetGenericPortMappingEntry(int index, UpnpNatDevice device)
+ :base(device)
+ {
+ this.index = index;
+ }
+
+ public override System.Net.WebRequest Encode(out byte[] body)
+ {
+ StringBuilder sb = new StringBuilder(128);
+ XmlWriter writer = CreateWriter(sb);
+
+ WriteFullElement(writer, "NewPortMappingIndex", index.ToString());
+
+ writer.Flush();
+ return CreateRequest("GetGenericPortMappingEntry", sb.ToString(), out body);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Requests/GetSpecificPortMappingEntryMessage.cs b/Mono.Nat/Upnp/Messages/Requests/GetSpecificPortMappingEntryMessage.cs
new file mode 100644
index 000000000..314468ece
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Requests/GetSpecificPortMappingEntryMessage.cs
@@ -0,0 +1,60 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+using System.Net;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetSpecificPortMappingEntryMessage : MessageBase
+ {
+ internal Protocol protocol;
+ internal int externalPort;
+
+ public GetSpecificPortMappingEntryMessage(Protocol protocol, int externalPort, UpnpNatDevice device)
+ : base(device)
+ {
+ this.protocol = protocol;
+ this.externalPort = externalPort;
+ }
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ StringBuilder sb = new StringBuilder(64);
+ XmlWriter writer = CreateWriter(sb);
+
+ WriteFullElement(writer, "NewRemoteHost", string.Empty);
+ WriteFullElement(writer, "NewExternalPort", externalPort.ToString());
+ WriteFullElement(writer, "NewProtocol", protocol == Protocol.Tcp ? "TCP" : "UDP");
+ writer.Flush();
+
+ return CreateRequest("GetSpecificPortMappingEntry", sb.ToString(), out body);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Responses/CreatePortMappingResponseMessage.cs b/Mono.Nat/Upnp/Messages/Responses/CreatePortMappingResponseMessage.cs
new file mode 100644
index 000000000..e75926b09
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Responses/CreatePortMappingResponseMessage.cs
@@ -0,0 +1,46 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+
+using System;
+namespace Mono.Nat.Upnp
+{
+ internal class CreatePortMappingResponseMessage : MessageBase
+ {
+ #region Constructors
+ public CreatePortMappingResponseMessage()
+ :base(null)
+ {
+ }
+ #endregion
+
+ public override System.Net.WebRequest Encode(out byte[] body)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Responses/DeletePortMappingResponseMessage.cs b/Mono.Nat/Upnp/Messages/Responses/DeletePortMappingResponseMessage.cs
new file mode 100644
index 000000000..1fce4eb04
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Responses/DeletePortMappingResponseMessage.cs
@@ -0,0 +1,44 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+
+using System;
+namespace Mono.Nat.Upnp
+{
+ internal class DeletePortMapResponseMessage : MessageBase
+ {
+ public DeletePortMapResponseMessage()
+ :base(null)
+ {
+ }
+
+ public override System.Net.WebRequest Encode(out byte[] body)
+ {
+ throw new NotSupportedException();
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Responses/GetExternalIPAddressResponseMessage.cs b/Mono.Nat/Upnp/Messages/Responses/GetExternalIPAddressResponseMessage.cs
new file mode 100644
index 000000000..ee4b18cd1
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Responses/GetExternalIPAddressResponseMessage.cs
@@ -0,0 +1,53 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetExternalIPAddressResponseMessage : MessageBase
+ {
+ public IPAddress ExternalIPAddress
+ {
+ get { return this.externalIPAddress; }
+ }
+ private IPAddress externalIPAddress;
+
+ public GetExternalIPAddressResponseMessage(string ip)
+ :base(null)
+ {
+ this.externalIPAddress = IPAddress.Parse(ip);
+ }
+
+ public override WebRequest Encode(out byte[] body)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/Responses/GetGenericPortMappingEntryResponseMessage.cs b/Mono.Nat/Upnp/Messages/Responses/GetGenericPortMappingEntryResponseMessage.cs
new file mode 100644
index 000000000..b11bfa027
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/Responses/GetGenericPortMappingEntryResponseMessage.cs
@@ -0,0 +1,108 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Xml;
+
+namespace Mono.Nat.Upnp
+{
+ internal class GetGenericPortMappingEntryResponseMessage : MessageBase
+ {
+ private string remoteHost;
+ private int externalPort;
+ private Protocol protocol;
+ private int internalPort;
+ private string internalClient;
+ private bool enabled;
+ private string portMappingDescription;
+ private int leaseDuration;
+
+ public string RemoteHost
+ {
+ get { return this.remoteHost; }
+ }
+
+ public int ExternalPort
+ {
+ get { return this.externalPort; }
+ }
+
+ public Protocol Protocol
+ {
+ get { return this.protocol; }
+ }
+
+ public int InternalPort
+ {
+ get { return this.internalPort; }
+ }
+
+ public string InternalClient
+ {
+ get { return this.internalClient; }
+ }
+
+ public bool Enabled
+ {
+ get { return this.enabled; }
+ }
+
+ public string PortMappingDescription
+ {
+ get { return this.portMappingDescription; }
+ }
+
+ public int LeaseDuration
+ {
+ get { return this.leaseDuration; }
+ }
+
+
+ public GetGenericPortMappingEntryResponseMessage(XmlNode data, bool genericMapping)
+ : base(null)
+ {
+ remoteHost = (genericMapping) ? data["NewRemoteHost"].InnerText : string.Empty;
+ externalPort = (genericMapping) ? Convert.ToInt32(data["NewExternalPort"].InnerText) : -1;
+ if (genericMapping)
+ protocol = data["NewProtocol"].InnerText.Equals("TCP", StringComparison.InvariantCultureIgnoreCase) ? Protocol.Tcp : Protocol.Udp;
+ else
+ protocol = Protocol.Udp;
+
+ internalPort = Convert.ToInt32(data["NewInternalPort"].InnerText);
+ internalClient = data["NewInternalClient"].InnerText;
+ enabled = data["NewEnabled"].InnerText == "1" ? true : false;
+ portMappingDescription = data["NewPortMappingDescription"].InnerText;
+ leaseDuration = Convert.ToInt32(data["NewLeaseDuration"].InnerText);
+ }
+
+ public override System.Net.WebRequest Encode(out byte[] body)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Messages/UpnpMessage.cs b/Mono.Nat/Upnp/Messages/UpnpMessage.cs
new file mode 100644
index 000000000..44c16eec6
--- /dev/null
+++ b/Mono.Nat/Upnp/Messages/UpnpMessage.cs
@@ -0,0 +1,132 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+//
+// Copyright (C) 2006 Alan McGovern
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Diagnostics;
+using System.Xml;
+using System.Net;
+using System.IO;
+using System.Text;
+using System.Globalization;
+
+namespace Mono.Nat.Upnp
+{
+ internal abstract class MessageBase
+ {
+ internal static readonly CultureInfo Culture = CultureInfo.InvariantCulture;
+ protected UpnpNatDevice device;
+
+ protected MessageBase(UpnpNatDevice device)
+ {
+ this.device = device;
+ }
+
+ protected WebRequest CreateRequest(string upnpMethod, string methodParameters, out byte[] body)
+ {
+ string ss = "http://" + this.device.HostEndPoint.ToString() + this.device.ControlUrl;
+ NatUtility.Log("Initiating request to: {0}", ss);
+ Uri location = new Uri(ss);
+
+ HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(location);
+ req.KeepAlive = false;
+ req.Method = "POST";
+ req.ContentType = "text/xml; charset=\"utf-8\"";
+ req.Headers.Add("SOAPACTION", "\"" + device.ServiceType + "#" + upnpMethod + "\"");
+
+ string bodyString = "<s:Envelope "
+ + "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ + "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ + "<s:Body>"
+ + "<u:" + upnpMethod + " "
+ + "xmlns:u=\"" + device.ServiceType + "\">"
+ + methodParameters
+ + "</u:" + upnpMethod + ">"
+ + "</s:Body>"
+ + "</s:Envelope>\r\n\r\n";
+
+ body = System.Text.Encoding.UTF8.GetBytes(bodyString);
+ return req;
+ }
+
+ public static MessageBase Decode(UpnpNatDevice device, string message)
+ {
+ XmlNode node;
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml(message);
+
+ XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
+
+ // Error messages should be found under this namespace
+ nsm.AddNamespace("errorNs", "urn:schemas-upnp-org:control-1-0");
+ nsm.AddNamespace("responseNs", device.ServiceType);
+
+ // Check to see if we have a fault code message.
+ if ((node = doc.SelectSingleNode("//errorNs:UPnPError", nsm)) != null) {
+ string errorCode = node["errorCode"] != null ? node["errorCode"].InnerText : "";
+ string errorDescription = node["errorDescription"] != null ? node["errorDescription"].InnerText : "";
+
+ return new ErrorMessage(Convert.ToInt32(errorCode, CultureInfo.InvariantCulture), errorDescription);
+ }
+
+ if ((doc.SelectSingleNode("//responseNs:AddPortMappingResponse", nsm)) != null)
+ return new CreatePortMappingResponseMessage();
+
+ if ((doc.SelectSingleNode("//responseNs:DeletePortMappingResponse", nsm)) != null)
+ return new DeletePortMapResponseMessage();
+
+ if ((node = doc.SelectSingleNode("//responseNs:GetExternalIPAddressResponse", nsm)) != null) {
+ string newExternalIPAddress = node["NewExternalIPAddress"] != null ? node["NewExternalIPAddress"].InnerText : "";
+ return new GetExternalIPAddressResponseMessage(newExternalIPAddress);
+ }
+
+ if ((node = doc.SelectSingleNode("//responseNs:GetGenericPortMappingEntryResponse", nsm)) != null)
+ return new GetGenericPortMappingEntryResponseMessage(node, true);
+
+ if ((node = doc.SelectSingleNode("//responseNs:GetSpecificPortMappingEntryResponse", nsm)) != null)
+ return new GetGenericPortMappingEntryResponseMessage(node, false);
+
+ NatUtility.Log("Unknown message returned. Please send me back the following XML:");
+ NatUtility.Log(message);
+ return null;
+ }
+
+ public abstract WebRequest Encode(out byte[] body);
+
+ internal static void WriteFullElement(XmlWriter writer, string element, string value)
+ {
+ writer.WriteStartElement(element);
+ writer.WriteString(value);
+ writer.WriteEndElement();
+ }
+
+ internal static XmlWriter CreateWriter(StringBuilder sb)
+ {
+ XmlWriterSettings settings = new XmlWriterSettings();
+ settings.ConformanceLevel = ConformanceLevel.Fragment;
+ return XmlWriter.Create(sb, settings);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
new file mode 100644
index 000000000..edc5a5d76
--- /dev/null
+++ b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs
@@ -0,0 +1,287 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Net;
+using Mono.Nat.Upnp;
+using System.Diagnostics;
+using System.Net.Sockets;
+using System.Net.NetworkInformation;
+using MediaBrowser.Controller.Dlna;
+
+namespace Mono.Nat
+{
+ internal class UpnpSearcher : ISearcher
+ {
+ private const int SearchPeriod = 5 * 60; // The time in seconds between each search
+ static UpnpSearcher instance = new UpnpSearcher();
+ public static List<UdpClient> sockets = CreateSockets();
+
+ public static UpnpSearcher Instance
+ {
+ get { return instance; }
+ }
+
+ public event EventHandler<DeviceEventArgs> DeviceFound;
+ public event EventHandler<DeviceEventArgs> DeviceLost;
+
+ private List<INatDevice> devices;
+ private Dictionary<IPAddress, DateTime> lastFetched;
+ private DateTime nextSearch;
+ private IPEndPoint searchEndpoint;
+
+ UpnpSearcher()
+ {
+ devices = new List<INatDevice>();
+ lastFetched = new Dictionary<IPAddress, DateTime>();
+ //searchEndpoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);
+ searchEndpoint = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900);
+ }
+
+ static List<UdpClient> CreateSockets()
+ {
+ List<UdpClient> clients = new List<UdpClient>();
+ try
+ {
+ foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces())
+ {
+ foreach (UnicastIPAddressInformation address in n.GetIPProperties().UnicastAddresses)
+ {
+ if (address.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ try
+ {
+ clients.Add(new UdpClient(new IPEndPoint(address.Address, 0)));
+ }
+ catch
+ {
+ continue; // Move on to the next address.
+ }
+ }
+ }
+ }
+ }
+ catch (Exception)
+ {
+ clients.Add(new UdpClient(0));
+ }
+ return clients;
+ }
+
+ public void Search()
+ {
+ foreach (UdpClient s in sockets)
+ {
+ try
+ {
+ Search(s);
+ }
+ catch
+ {
+ // Ignore any search errors
+ }
+ }
+ }
+
+ void Search(UdpClient client)
+ {
+ nextSearch = DateTime.Now.AddSeconds(SearchPeriod);
+ byte[] data = DiscoverDeviceMessage.EncodeSSDP();
+
+ // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
+ for (int i = 0; i < 3; i++)
+ client.Send(data, data.Length, searchEndpoint);
+ }
+
+ public IPEndPoint SearchEndpoint
+ {
+ get { return searchEndpoint; }
+ }
+
+ public void Handle(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint endpoint)
+ {
+ // No matter what, this method should never throw an exception. If something goes wrong
+ // we should still be in a position to handle the next reply correctly.
+ try
+ {
+ /* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection.
+ Any other device type is no good to us for this purpose. See the IGP overview paper
+ page 5 for an overview of device types and their hierarchy.
+ http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */
+
+ /* TODO: Currently we are assuming version 1 of the protocol. We should figure out which
+ version it is and apply the correct URN. */
+
+ /* Some routers don't correctly implement the version ID on the URN, so we only search for the type
+ prefix. */
+
+ // We have an internet gateway device now
+ UpnpNatDevice d = new UpnpNatDevice(localAddress, deviceInfo, endpoint, string.Empty);
+
+ if (devices.Contains(d))
+ {
+ // We already have found this device, so we just refresh it to let people know it's
+ // Still alive. If a device doesn't respond to a search, we dump it.
+ devices[devices.IndexOf(d)].LastSeen = DateTime.Now;
+ }
+ else
+ {
+
+ // If we send 3 requests at a time, ensure we only fetch the services list once
+ // even if three responses are received
+ if (lastFetched.ContainsKey(endpoint.Address))
+ {
+ DateTime last = lastFetched[endpoint.Address];
+ if ((DateTime.Now - last) < TimeSpan.FromSeconds(20))
+ return;
+ }
+ lastFetched[endpoint.Address] = DateTime.Now;
+
+ // Once we've parsed the information we need, we tell the device to retrieve it's service list
+ // Once we successfully receive the service list, the callback provided will be invoked.
+ NatUtility.Log("Fetching service list: {0}", d.HostEndPoint);
+ d.GetServicesList(DeviceSetupComplete);
+ }
+ }
+ catch (Exception ex)
+ {
+ NatUtility.Log("Unhandled exception when trying to decode a device's response Send me the following data: ");
+ NatUtility.Log("ErrorMessage:");
+ NatUtility.Log(ex.Message);
+ }
+ }
+
+ public void Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
+ {
+ // Convert it to a string for easy parsing
+ string dataString = null;
+
+ // No matter what, this method should never throw an exception. If something goes wrong
+ // we should still be in a position to handle the next reply correctly.
+ try {
+ string urn;
+ dataString = Encoding.UTF8.GetString(response);
+
+ if (NatUtility.Verbose)
+ NatUtility.Log("UPnP Response: {0}", dataString);
+
+ /* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection.
+ Any other device type is no good to us for this purpose. See the IGP overview paper
+ page 5 for an overview of device types and their hierarchy.
+ http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */
+
+ /* TODO: Currently we are assuming version 1 of the protocol. We should figure out which
+ version it is and apply the correct URN. */
+
+ /* Some routers don't correctly implement the version ID on the URN, so we only search for the type
+ prefix. */
+
+ string log = "UPnP Response: Router advertised a '{0}' service";
+ StringComparison c = StringComparison.OrdinalIgnoreCase;
+ if (dataString.IndexOf("urn:schemas-upnp-org:service:WANIPConnection:", c) != -1) {
+ urn = "urn:schemas-upnp-org:service:WANIPConnection:1";
+ NatUtility.Log(log, "urn:schemas-upnp-org:service:WANIPConnection:1");
+ } else if (dataString.IndexOf("urn:schemas-upnp-org:service:WANPPPConnection:", c) != -1) {
+ urn = "urn:schemas-upnp-org:service:WANPPPConnection:1";
+ NatUtility.Log(log, "urn:schemas-upnp-org:service:WANPPPConnection:");
+ } else
+ return;
+
+ // We have an internet gateway device now
+ UpnpNatDevice d = new UpnpNatDevice(localAddress, dataString, urn);
+
+ if (devices.Contains(d))
+ {
+ // We already have found this device, so we just refresh it to let people know it's
+ // Still alive. If a device doesn't respond to a search, we dump it.
+ devices[devices.IndexOf(d)].LastSeen = DateTime.Now;
+ }
+ else
+ {
+
+ // If we send 3 requests at a time, ensure we only fetch the services list once
+ // even if three responses are received
+ if (lastFetched.ContainsKey(endpoint.Address))
+ {
+ DateTime last = lastFetched[endpoint.Address];
+ if ((DateTime.Now - last) < TimeSpan.FromSeconds(20))
+ return;
+ }
+ lastFetched[endpoint.Address] = DateTime.Now;
+
+ // Once we've parsed the information we need, we tell the device to retrieve it's service list
+ // Once we successfully receive the service list, the callback provided will be invoked.
+ NatUtility.Log("Fetching service list: {0}", d.HostEndPoint);
+ d.GetServicesList(DeviceSetupComplete);
+ }
+ }
+ catch (Exception ex)
+ {
+ Trace.WriteLine("Unhandled exception when trying to decode a device's response Send me the following data: ");
+ Trace.WriteLine("ErrorMessage:");
+ Trace.WriteLine(ex.Message);
+ Trace.WriteLine("Data string:");
+ Trace.WriteLine(dataString);
+ }
+ }
+
+ public DateTime NextSearch
+ {
+ get { return nextSearch; }
+ }
+
+ private void DeviceSetupComplete(INatDevice device)
+ {
+ lock (this.devices)
+ {
+ // We don't want the same device in there twice
+ if (devices.Contains(device))
+ return;
+
+ devices.Add(device);
+ }
+
+ OnDeviceFound(new DeviceEventArgs(device));
+ }
+
+ private void OnDeviceFound(DeviceEventArgs args)
+ {
+ if (DeviceFound != null)
+ DeviceFound(this, args);
+ }
+
+ public NatProtocol Protocol
+ {
+ get { return NatProtocol.Upnp; }
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/Upnp.cs b/Mono.Nat/Upnp/Upnp.cs
new file mode 100644
index 000000000..e44a51c24
--- /dev/null
+++ b/Mono.Nat/Upnp/Upnp.cs
@@ -0,0 +1,83 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+// Nicholas Terry <nick.i.terry@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+// Copyright (C) 2014 Nicholas Terry
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+
+namespace Mono.Nat.Upnp
+{
+ internal class Upnp
+ {
+ public UpnpNatDevice Handle(IPAddress localAddress, byte[] response, IPEndPoint endpoint)
+ {
+ // Convert it to a string for easy parsing
+ string dataString = null;
+
+
+ string urn;
+ dataString = Encoding.UTF8.GetString(response);
+
+ if (NatUtility.Verbose)
+ NatUtility.Log("UPnP Response: {0}", dataString);
+
+ /* For UPnP Port Mapping we need ot find either WANPPPConnection or WANIPConnection.
+ Any other device type is no good to us for this purpose. See the IGP overview paper
+ page 5 for an overview of device types and their hierarchy.
+ http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf */
+
+ /* TODO: Currently we are assuming version 1 of the protocol. We should figure out which
+ version it is and apply the correct URN. */
+
+ /* Some routers don't correctly implement the version ID on the URN, so we only search for the type
+ prefix. */
+
+ string log = "UPnP Response: Router advertised a '{0}' service";
+ StringComparison c = StringComparison.OrdinalIgnoreCase;
+ if (dataString.IndexOf("urn:schemas-upnp-org:service:WANIPConnection:", c) != -1)
+ {
+ urn = "urn:schemas-upnp-org:service:WANIPConnection:1";
+ NatUtility.Log(log, "urn:schemas-upnp-org:service:WANIPConnection:1");
+ }
+ else if (dataString.IndexOf("urn:schemas-upnp-org:service:WANPPPConnection:", c) != -1)
+ {
+ urn = "urn:schemas-upnp-org:service:WANPPPConnection:1";
+ NatUtility.Log(log, "urn:schemas-upnp-org:service:WANPPPConnection:");
+ }
+ else
+ throw new NotSupportedException("Received non-supported device type");
+
+ // We have an internet gateway device now
+ return new UpnpNatDevice(localAddress, dataString, urn);
+ }
+ }
+}
diff --git a/Mono.Nat/Upnp/UpnpNatDevice.cs b/Mono.Nat/Upnp/UpnpNatDevice.cs
new file mode 100644
index 000000000..1160d3ac2
--- /dev/null
+++ b/Mono.Nat/Upnp/UpnpNatDevice.cs
@@ -0,0 +1,651 @@
+//
+// Authors:
+// Alan McGovern alan.mcgovern@gmail.com
+// Ben Motmans <ben.motmans@gmail.com>
+//
+// Copyright (C) 2006 Alan McGovern
+// Copyright (C) 2007 Ben Motmans
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Net;
+using System.Xml;
+using System.Text;
+using System.Diagnostics;
+using MediaBrowser.Controller.Dlna;
+
+namespace Mono.Nat.Upnp
+{
+ public sealed class UpnpNatDevice : AbstractNatDevice, IEquatable<UpnpNatDevice>
+ {
+ private EndPoint hostEndPoint;
+ private IPAddress localAddress;
+ private string serviceDescriptionUrl;
+ private string controlUrl;
+ private string serviceType;
+
+ public override IPAddress LocalAddress
+ {
+ get { return localAddress; }
+ }
+
+ /// <summary>
+ /// The callback to invoke when we are finished setting up the device
+ /// </summary>
+ private NatDeviceCallback callback;
+
+ internal UpnpNatDevice(IPAddress localAddress, UpnpDeviceInfo deviceInfo, IPEndPoint hostEndPoint, string serviceType)
+ {
+ this.LastSeen = DateTime.Now;
+ this.localAddress = localAddress;
+
+ // Split the string at the "location" section so i can extract the ipaddress and service description url
+ string locationDetails = deviceInfo.Location.ToString();
+ this.serviceType = serviceType;
+
+ // Make sure we have no excess whitespace
+ locationDetails = locationDetails.Trim();
+
+ // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
+ // Are we going to get addresses with the "http://" attached?
+ if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
+ {
+ NatUtility.Log("Found device at: {0}", locationDetails);
+ // This bit strings out the "http://" from the string
+ locationDetails = locationDetails.Substring(7);
+
+ this.hostEndPoint = hostEndPoint;
+
+ NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString());
+
+ // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
+ // and port information
+ this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
+ }
+ else
+ {
+ NatUtility.Log("Couldn't decode address. Please send following string to the developer: ");
+ }
+ }
+
+ internal UpnpNatDevice (IPAddress localAddress, string deviceDetails, string serviceType)
+ {
+ this.LastSeen = DateTime.Now;
+ this.localAddress = localAddress;
+
+ // Split the string at the "location" section so i can extract the ipaddress and service description url
+ string locationDetails = deviceDetails.Substring(deviceDetails.IndexOf("Location", StringComparison.InvariantCultureIgnoreCase) + 9).Split('\r')[0];
+ this.serviceType = serviceType;
+
+ // Make sure we have no excess whitespace
+ locationDetails = locationDetails.Trim();
+
+ // FIXME: Is this reliable enough. What if we get a hostname as opposed to a proper http address
+ // Are we going to get addresses with the "http://" attached?
+ if (locationDetails.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
+ {
+ NatUtility.Log("Found device at: {0}", locationDetails);
+ // This bit strings out the "http://" from the string
+ locationDetails = locationDetails.Substring(7);
+
+ // We then split off the end of the string to get something like: 192.168.0.3:241 in our string
+ string hostAddressAndPort = locationDetails.Remove(locationDetails.IndexOf('/'));
+
+ // From this we parse out the IP address and Port
+ if (hostAddressAndPort.IndexOf(':') > 0)
+ {
+ this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort.Remove(hostAddressAndPort.IndexOf(':'))),
+ Convert.ToUInt16(hostAddressAndPort.Substring(hostAddressAndPort.IndexOf(':') + 1), System.Globalization.CultureInfo.InvariantCulture));
+ }
+ else
+ {
+ // there is no port specified, use default port (80)
+ this.hostEndPoint = new IPEndPoint(IPAddress.Parse(hostAddressAndPort), 80);
+ }
+
+ NatUtility.Log("Parsed device as: {0}", this.hostEndPoint.ToString());
+
+ // The service description URL is the remainder of the "locationDetails" string. The bit that was originally after the ip
+ // and port information
+ this.serviceDescriptionUrl = locationDetails.Substring(locationDetails.IndexOf('/'));
+ }
+ else
+ {
+ Trace.WriteLine("Couldn't decode address. Please send following string to the developer: ");
+ Trace.WriteLine(deviceDetails);
+ }
+ }
+
+ /// <summary>
+ /// The EndPoint that the device is at
+ /// </summary>
+ internal EndPoint HostEndPoint
+ {
+ get { return this.hostEndPoint; }
+ }
+
+ /// <summary>
+ /// The relative url of the xml file that describes the list of services is at
+ /// </summary>
+ internal string ServiceDescriptionUrl
+ {
+ get { return this.serviceDescriptionUrl; }
+ }
+
+ /// <summary>
+ /// The relative url that we can use to control the port forwarding
+ /// </summary>
+ internal string ControlUrl
+ {
+ get { return this.controlUrl; }
+ }
+
+ /// <summary>
+ /// The service type we're using on the device
+ /// </summary>
+ public string ServiceType
+ {
+ get { return serviceType; }
+ }
+
+ /// <summary>
+ /// Begins an async call to get the external ip address of the router
+ /// </summary>
+ public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState)
+ {
+ // Create the port map message
+ GetExternalIPAddressMessage message = new GetExternalIPAddressMessage(this);
+ return BeginMessageInternal(message, callback, asyncState, EndGetExternalIPInternal);
+ }
+
+ /// <summary>
+ /// Maps the specified port to this computer
+ /// </summary>
+ public override IAsyncResult BeginCreatePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
+ {
+ CreatePortMappingMessage message = new CreatePortMappingMessage(mapping, localAddress, this);
+ return BeginMessageInternal(message, callback, asyncState, EndCreatePortMapInternal);
+ }
+
+ /// <summary>
+ /// Removes a port mapping from this computer
+ /// </summary>
+ public override IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState)
+ {
+ DeletePortMappingMessage message = new DeletePortMappingMessage(mapping, this);
+ return BeginMessageInternal(message, callback, asyncState, EndDeletePortMapInternal);
+ }
+
+
+ public override IAsyncResult BeginGetAllMappings(AsyncCallback callback, object asyncState)
+ {
+ GetGenericPortMappingEntry message = new GetGenericPortMappingEntry(0, this);
+ return BeginMessageInternal(message, callback, asyncState, EndGetAllMappingsInternal);
+ }
+
+
+ public override IAsyncResult BeginGetSpecificMapping (Protocol protocol, int port, AsyncCallback callback, object asyncState)
+ {
+ GetSpecificPortMappingEntryMessage message = new GetSpecificPortMappingEntryMessage(protocol, port, this);
+ return this.BeginMessageInternal(message, callback, asyncState, new AsyncCallback(this.EndGetSpecificMappingInternal));
+ }
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="result"></param>
+ public override void EndCreatePortMap(IAsyncResult result)
+ {
+ if (result == null) throw new ArgumentNullException("result");
+
+ PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
+ if (mappingResult == null)
+ throw new ArgumentException("Invalid AsyncResult", "result");
+
+ // Check if we need to wait for the operation to finish
+ if (!result.IsCompleted)
+ result.AsyncWaitHandle.WaitOne();
+
+ // If we have a saved exception, it means something went wrong during the mapping
+ // so we just rethrow the exception and let the user figure out what they should do.
+ if (mappingResult.SavedMessage is ErrorMessage)
+ {
+ ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
+ throw new MappingException(msg.ErrorCode, msg.Description);
+ }
+
+ //return result.AsyncState as Mapping;
+ }
+
+
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="result"></param>
+ public override void EndDeletePortMap(IAsyncResult result)
+ {
+ if (result == null)
+ throw new ArgumentNullException("result");
+
+ PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
+ if (mappingResult == null)
+ throw new ArgumentException("Invalid AsyncResult", "result");
+
+ // Check if we need to wait for the operation to finish
+ if (!mappingResult.IsCompleted)
+ mappingResult.AsyncWaitHandle.WaitOne();
+
+ // If we have a saved exception, it means something went wrong during the mapping
+ // so we just rethrow the exception and let the user figure out what they should do.
+ if (mappingResult.SavedMessage is ErrorMessage)
+ {
+ ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
+ throw new MappingException(msg.ErrorCode, msg.Description);
+ }
+
+ // If all goes well, we just return
+ //return true;
+ }
+
+
+ public override Mapping[] EndGetAllMappings(IAsyncResult result)
+ {
+ if (result == null)
+ throw new ArgumentNullException("result");
+
+ GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;
+ if (mappingResult == null)
+ throw new ArgumentException("Invalid AsyncResult", "result");
+
+ if (!mappingResult.IsCompleted)
+ mappingResult.AsyncWaitHandle.WaitOne();
+
+ if (mappingResult.SavedMessage is ErrorMessage)
+ {
+ ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
+ if (msg.ErrorCode != 713)
+ throw new MappingException(msg.ErrorCode, msg.Description);
+ }
+
+ return mappingResult.Mappings.ToArray();
+ }
+
+
+ /// <summary>
+ /// Ends an async request to get the external ip address of the router
+ /// </summary>
+ public override IPAddress EndGetExternalIP(IAsyncResult result)
+ {
+ if (result == null) throw new ArgumentNullException("result");
+
+ PortMapAsyncResult mappingResult = result as PortMapAsyncResult;
+ if (mappingResult == null)
+ throw new ArgumentException("Invalid AsyncResult", "result");
+
+ if (!result.IsCompleted)
+ result.AsyncWaitHandle.WaitOne();
+
+ if (mappingResult.SavedMessage is ErrorMessage)
+ {
+ ErrorMessage msg = mappingResult.SavedMessage as ErrorMessage;
+ throw new MappingException(msg.ErrorCode, msg.Description);
+ }
+
+ if (mappingResult.SavedMessage == null)
+ return null;
+ else
+ return ((GetExternalIPAddressResponseMessage)mappingResult.SavedMessage).ExternalIPAddress;
+ }
+
+
+ public override Mapping EndGetSpecificMapping(IAsyncResult result)
+ {
+ if (result == null)
+ throw new ArgumentNullException("result");
+
+ GetAllMappingsAsyncResult mappingResult = result as GetAllMappingsAsyncResult;
+ if (mappingResult == null)
+ throw new ArgumentException("Invalid AsyncResult", "result");
+
+ if (!mappingResult.IsCompleted)
+ mappingResult.AsyncWaitHandle.WaitOne();
+
+ if (mappingResult.SavedMessage is ErrorMessage)
+ {
+ ErrorMessage message = mappingResult.SavedMessage as ErrorMessage;
+ if (message.ErrorCode != 0x2ca)
+ {
+ throw new MappingException(message.ErrorCode, message.Description);
+ }
+ }
+ if (mappingResult.Mappings.Count == 0)
+ return new Mapping (Protocol.Tcp, -1, -1);
+
+ return mappingResult.Mappings[0];
+ }
+
+
+ public override bool Equals(object obj)
+ {
+ UpnpNatDevice device = obj as UpnpNatDevice;
+ return (device == null) ? false : this.Equals((device));
+ }
+
+
+ public bool Equals(UpnpNatDevice other)
+ {
+ return (other == null) ? false : (this.hostEndPoint.Equals(other.hostEndPoint)
+ //&& this.controlUrl == other.controlUrl
+ && this.serviceDescriptionUrl == other.serviceDescriptionUrl);
+ }
+
+ public override int GetHashCode()
+ {
+ return (this.hostEndPoint.GetHashCode() ^ this.controlUrl.GetHashCode() ^ this.serviceDescriptionUrl.GetHashCode());
+ }
+
+ private IAsyncResult BeginMessageInternal(MessageBase message, AsyncCallback storedCallback, object asyncState, AsyncCallback callback)
+ {
+ byte[] body;
+ WebRequest request = message.Encode(out body);
+ PortMapAsyncResult mappingResult = PortMapAsyncResult.Create(message, request, storedCallback, asyncState);
+
+ if (body.Length > 0)
+ {
+ request.ContentLength = body.Length;
+ request.BeginGetRequestStream(delegate(IAsyncResult result) {
+ try
+ {
+ Stream s = request.EndGetRequestStream(result);
+ s.Write(body, 0, body.Length);
+ request.BeginGetResponse(callback, mappingResult);
+ }
+ catch (Exception ex)
+ {
+ mappingResult.Complete(ex);
+ }
+ }, null);
+ }
+ else
+ {
+ request.BeginGetResponse(callback, mappingResult);
+ }
+ return mappingResult;
+ }
+
+ private void CompleteMessage(IAsyncResult result)
+ {
+ PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;
+ mappingResult.CompletedSynchronously = result.CompletedSynchronously;
+ mappingResult.Complete();
+ }
+
+ private MessageBase DecodeMessageFromResponse(Stream s, long length)
+ {
+ StringBuilder data = new StringBuilder();
+ int bytesRead = 0;
+ int totalBytesRead = 0;
+ byte[] buffer = new byte[10240];
+
+ // Read out the content of the message, hopefully picking everything up in the case where we have no contentlength
+ if (length != -1)
+ {
+ while (totalBytesRead < length)
+ {
+ bytesRead = s.Read(buffer, 0, buffer.Length);
+ data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
+ totalBytesRead += bytesRead;
+ }
+ }
+ else
+ {
+ while ((bytesRead = s.Read(buffer, 0, buffer.Length)) != 0)
+ data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
+ }
+
+ // Once we have our content, we need to see what kind of message it is. It'll either a an error
+ // or a response based on the action we performed.
+ return MessageBase.Decode(this, data.ToString());
+ }
+
+ private void EndCreatePortMapInternal(IAsyncResult result)
+ {
+ EndMessageInternal(result);
+ CompleteMessage(result);
+ }
+
+ private void EndMessageInternal(IAsyncResult result)
+ {
+ HttpWebResponse response = null;
+ PortMapAsyncResult mappingResult = result.AsyncState as PortMapAsyncResult;
+
+ try
+ {
+ try
+ {
+ response = (HttpWebResponse)mappingResult.Request.EndGetResponse(result);
+ }
+ catch (WebException ex)
+ {
+ // Even if the request "failed" i want to continue on to read out the response from the router
+ response = ex.Response as HttpWebResponse;
+ if (response == null)
+ mappingResult.SavedMessage = new ErrorMessage((int)ex.Status, ex.Message);
+ }
+ if (response != null)
+ mappingResult.SavedMessage = DecodeMessageFromResponse(response.GetResponseStream(), response.ContentLength);
+ }
+
+ finally
+ {
+ if (response != null)
+ response.Close();
+ }
+ }
+
+ private void EndDeletePortMapInternal(IAsyncResult result)
+ {
+ EndMessageInternal(result);
+ CompleteMessage(result);
+ }
+
+ private void EndGetAllMappingsInternal(IAsyncResult result)
+ {
+ EndMessageInternal(result);
+
+ GetAllMappingsAsyncResult mappingResult = result.AsyncState as GetAllMappingsAsyncResult;
+ GetGenericPortMappingEntryResponseMessage message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage;
+ if (message != null)
+ {
+ Mapping mapping = new Mapping (message.Protocol, message.InternalPort, message.ExternalPort, message.LeaseDuration);
+ mapping.Description = message.PortMappingDescription;
+ mappingResult.Mappings.Add(mapping);
+ GetGenericPortMappingEntry next = new GetGenericPortMappingEntry(mappingResult.Mappings.Count, this);
+
+ // It's ok to do this synchronously because we should already be on anther thread
+ // and this won't block the user.
+ byte[] body;
+ WebRequest request = next.Encode(out body);
+ if (body.Length > 0)
+ {
+ request.ContentLength = body.Length;
+ request.GetRequestStream().Write(body, 0, body.Length);
+ }
+ mappingResult.Request = request;
+ request.BeginGetResponse(EndGetAllMappingsInternal, mappingResult);
+ return;
+ }
+
+ CompleteMessage(result);
+ }
+
+ private void EndGetExternalIPInternal(IAsyncResult result)
+ {
+ EndMessageInternal(result);
+ CompleteMessage(result);
+ }
+
+ private void EndGetSpecificMappingInternal(IAsyncResult result)
+ {
+ EndMessageInternal(result);
+
+ GetAllMappingsAsyncResult mappingResult = result.AsyncState as GetAllMappingsAsyncResult;
+ GetGenericPortMappingEntryResponseMessage message = mappingResult.SavedMessage as GetGenericPortMappingEntryResponseMessage;
+ if (message != null) {
+ Mapping mapping = new Mapping(mappingResult.SpecificMapping.Protocol, message.InternalPort, mappingResult.SpecificMapping.PublicPort, message.LeaseDuration);
+ mapping.Description = mappingResult.SpecificMapping.Description;
+ mappingResult.Mappings.Add(mapping);
+ }
+
+ CompleteMessage(result);
+ }
+
+ internal void GetServicesList(NatDeviceCallback callback)
+ {
+ // Save the callback so i can use it again later when i've finished parsing the services available
+ this.callback = callback;
+
+ // Create a HTTPWebRequest to download the list of services the device offers
+ byte[] body;
+ WebRequest request = new GetServicesMessage(this.serviceDescriptionUrl, this.hostEndPoint).Encode(out body);
+ if (body.Length > 0)
+ NatUtility.Log("Error: Services Message contained a body");
+ request.BeginGetResponse(this.ServicesReceived, request);
+ }
+
+ private void ServicesReceived(IAsyncResult result)
+ {
+ HttpWebResponse response = null;
+ try
+ {
+ int abortCount = 0;
+ int bytesRead = 0;
+ byte[] buffer = new byte[10240];
+ StringBuilder servicesXml = new StringBuilder();
+ XmlDocument xmldoc = new XmlDocument();
+ HttpWebRequest request = result.AsyncState as HttpWebRequest;
+ response = request.EndGetResponse(result) as HttpWebResponse;
+ Stream s = response.GetResponseStream();
+
+ if (response.StatusCode != HttpStatusCode.OK) {
+ NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
+ return; // FIXME: This the best thing to do??
+ }
+
+ while (true)
+ {
+ bytesRead = s.Read(buffer, 0, buffer.Length);
+ servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
+ try
+ {
+ xmldoc.LoadXml(servicesXml.ToString());
+ response.Close();
+ break;
+ }
+ catch (XmlException)
+ {
+ // If we can't receive the entire XML within 500ms, then drop the connection
+ // Unfortunately not all routers supply a valid ContentLength (mine doesn't)
+ // so this hack is needed to keep testing our recieved data until it gets successfully
+ // parsed by the xmldoc. Without this, the code will never pick up my router.
+ if (abortCount++ > 50)
+ {
+ response.Close();
+ return;
+ }
+ NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint);
+ System.Threading.Thread.Sleep(10);
+ }
+ }
+
+ NatUtility.Log("{0}: Parsed services list", HostEndPoint);
+ XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
+ ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
+ XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns);
+
+ foreach (XmlNode node in nodes)
+ {
+ //Go through each service there
+ foreach (XmlNode service in node.ChildNodes)
+ {
+ //If the service is a WANIPConnection, then we have what we want
+ string type = service["serviceType"].InnerText;
+ NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type);
+ StringComparison c = StringComparison.OrdinalIgnoreCase;
+ // TODO: Add support for version 2 of UPnP.
+ if (type.Equals("urn:schemas-upnp-org:service:WANPPPConnection:1", c) ||
+ type.Equals("urn:schemas-upnp-org:service:WANIPConnection:1", c))
+ {
+ this.controlUrl = service["controlURL"].InnerText;
+ NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
+ try
+ {
+ Uri u = new Uri(controlUrl);
+ if (u.IsAbsoluteUri)
+ {
+ EndPoint old = hostEndPoint;
+ this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port);
+ NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
+ this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
+ NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl);
+ }
+ }
+ catch
+ {
+ NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
+ }
+ NatUtility.Log("{0}: Handshake Complete", HostEndPoint);
+ this.callback(this);
+ return;
+ }
+ }
+ }
+
+ //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding
+ //So we don't invoke the callback, so this device is never added to our lists
+ }
+ catch (WebException ex)
+ {
+ // Just drop the connection, FIXME: Should i retry?
+ NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex);
+ }
+ finally
+ {
+ if (response != null)
+ response.Close();
+ }
+ }
+
+ /// <summary>
+ /// Overridden.
+ /// </summary>
+ /// <returns></returns>
+ public override string ToString( )
+ {
+ //GetExternalIP is blocking and can throw exceptions, can't use it here.
+ return String.Format(
+ "UpnpNatDevice - EndPoint: {0}, External IP: {1}, Control Url: {2}, Service Description Url: {3}, Service Type: {4}, Last Seen: {5}",
+ this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen);
+ }
+ }
+} \ No newline at end of file
diff --git a/Nuget/MediaBrowser.Common.Internal.nuspec b/Nuget/MediaBrowser.Common.Internal.nuspec
index 06159dadb..369bc40c8 100644
--- a/Nuget/MediaBrowser.Common.Internal.nuspec
+++ b/Nuget/MediaBrowser.Common.Internal.nuspec
@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>MediaBrowser.Common.Internal</id>
- <version>3.0.657</version>
+ <version>3.0.659</version>
<title>MediaBrowser.Common.Internal</title>
<authors>Luke</authors>
<owners>ebr,Luke,scottisafool</owners>
@@ -12,9 +12,9 @@
<description>Contains common components shared by Emby Theater and Emby Server. Not intended for plugin developer consumption.</description>
<copyright>Copyright © Emby 2013</copyright>
<dependencies>
- <dependency id="MediaBrowser.Common" version="3.0.657" />
- <dependency id="NLog" version="4.3.6" />
- <dependency id="SimpleInjector" version="3.2.0" />
+ <dependency id="MediaBrowser.Common" version="3.0.659" />
+ <dependency id="NLog" version="4.3.8" />
+ <dependency id="SimpleInjector" version="3.2.2" />
</dependencies>
</metadata>
<files>
diff --git a/Nuget/MediaBrowser.Common.nuspec b/Nuget/MediaBrowser.Common.nuspec
index de1af036d..c0b1be7a5 100644
--- a/Nuget/MediaBrowser.Common.nuspec
+++ b/Nuget/MediaBrowser.Common.nuspec
@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>MediaBrowser.Common</id>
- <version>3.0.657</version>
+ <version>3.0.659</version>
<title>MediaBrowser.Common</title>
<authors>Emby Team</authors>
<owners>ebr,Luke,scottisafool</owners>
diff --git a/Nuget/MediaBrowser.Server.Core.nuspec b/Nuget/MediaBrowser.Server.Core.nuspec
index d21fefc86..4af1edbd4 100644
--- a/Nuget/MediaBrowser.Server.Core.nuspec
+++ b/Nuget/MediaBrowser.Server.Core.nuspec
@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>MediaBrowser.Server.Core</id>
- <version>3.0.657</version>
+ <version>3.0.659</version>
<title>Media Browser.Server.Core</title>
<authors>Emby Team</authors>
<owners>ebr,Luke,scottisafool</owners>
@@ -12,7 +12,7 @@
<description>Contains core components required to build plugins for Emby Server.</description>
<copyright>Copyright © Emby 2013</copyright>
<dependencies>
- <dependency id="MediaBrowser.Common" version="3.0.657" />
+ <dependency id="MediaBrowser.Common" version="3.0.659" />
<dependency id="Interfaces.IO" version="1.0.0.5" />
</dependencies>
</metadata>