From 3c55747cd63fd8a69f02efbe9ac48ce76d373b81 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 13 Nov 2016 15:27:09 -0500 Subject: fixes #2285 - [BUG] VAAPI Transcoding (Does not work with certain codecs) --- MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.MediaEncoding/Encoder') diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs index f811a8d48..e197bdb6f 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs @@ -606,9 +606,12 @@ namespace MediaBrowser.MediaEncoding.Encoder { // vaapi will throw an error with this input // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99. - if (string.Equals(videoStream.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase) && videoStream.Level == -99) + if (string.Equals(videoStream.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase)) { - return false; + if (videoStream.Level == -99 || videoStream.Level == 15) + { + return false; + } } } return true; -- cgit v1.2.3 From 0e9cd51f9c64d4cfad5cb5c7b0ddae6af8d18ac6 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 13 Nov 2016 16:04:21 -0500 Subject: update .net core startup --- Emby.Common.Implementations/BaseApplicationHost.cs | 4 +- .../BaseApplicationPaths.cs | 10 +- .../EnvironmentInfo/EnvironmentInfo.cs | 10 + .../IO/ManagedFileSystem.cs | 8 + Emby.Common.Implementations/Net/NetSocket.cs | 9 + Emby.Common.Implementations/Net/SocketAcceptor.cs | 24 ++- Emby.Common.Implementations/Net/SocketFactory.cs | 7 +- Emby.Server.Core/ApplicationHost.cs | 14 +- Emby.Server.Core/Data/DataExtensions.cs | 4 +- Emby.Server.Core/Data/SqliteItemRepository.cs | 19 +- .../Notifications/SqliteNotificationsRepository.cs | 2 +- Emby.Server.Core/ServerApplicationPaths.cs | 4 +- .../Channels/ChannelManager.cs | 16 +- .../HttpServer/HttpListenerHost.cs | 2 + .../LiveTv/EmbyTV/EmbyTV.cs | 90 +++++++-- .../LiveTv/EmbyTV/ItemDataProvider.cs | 3 +- .../LiveTv/LiveTvDtoService.cs | 20 +- .../LiveTv/LiveTvManager.cs | 67 +++++-- .../LiveTv/ProgramImageProvider.cs | 14 +- MediaBrowser.Api/ApiEntryPoint.cs | 6 +- .../Configuration/IApplicationPaths.cs | 6 - MediaBrowser.Controller/Entities/BaseItem.cs | 19 +- .../Encoder/EncoderValidator.cs | 16 +- MediaBrowser.Model/IO/IFileSystem.cs | 1 + MediaBrowser.Model/System/IEnvironmentInfo.cs | 2 + MediaBrowser.Server.Mono/MonoAppHost.cs | 2 +- MediaBrowser.Server.Mono/Program.cs | 10 +- .../Persistence/SqliteExtensions.cs | 6 +- MediaBrowser.ServerApplication/MainStartup.cs | 28 +-- .../Updates/ApplicationUpdater.cs | 2 +- MediaBrowser.ServerApplication/WindowsAppHost.cs | 9 +- MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs | 2 - Nuget/MediaBrowser.Common.nuspec | 2 +- Nuget/MediaBrowser.Server.Core.nuspec | 4 +- src/Emby.Server/ApplicationPathHelper.cs | 11 +- src/Emby.Server/CoreAppHost.cs | 2 +- src/Emby.Server/Program.cs | 213 ++++----------------- src/Emby.Server/project.json | 8 +- 38 files changed, 353 insertions(+), 323 deletions(-) (limited to 'MediaBrowser.MediaEncoding/Encoder') diff --git a/Emby.Common.Implementations/BaseApplicationHost.cs b/Emby.Common.Implementations/BaseApplicationHost.cs index f0309511e..1f194968c 100644 --- a/Emby.Common.Implementations/BaseApplicationHost.cs +++ b/Emby.Common.Implementations/BaseApplicationHost.cs @@ -326,7 +326,7 @@ namespace Emby.Common.Implementations builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount)); builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath)); - builder.AppendLine(string.Format("Application Path: {0}", appPaths.ApplicationPath)); + builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath)); return builder; } @@ -548,7 +548,7 @@ return null; TimerFactory = new TimerFactory(); RegisterSingleInstance(TimerFactory); - SocketFactory = new SocketFactory(null); + SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory")); RegisterSingleInstance(SocketFactory); RegisterSingleInstance(CryptographyProvider); diff --git a/Emby.Common.Implementations/BaseApplicationPaths.cs b/Emby.Common.Implementations/BaseApplicationPaths.cs index 628d62bd4..8792778ba 100644 --- a/Emby.Common.Implementations/BaseApplicationPaths.cs +++ b/Emby.Common.Implementations/BaseApplicationPaths.cs @@ -12,22 +12,18 @@ namespace Emby.Common.Implementations /// /// Initializes a new instance of the class. /// - protected BaseApplicationPaths(string programDataPath, string applicationPath) + protected BaseApplicationPaths(string programDataPath, string appFolderPath) { ProgramDataPath = programDataPath; - ApplicationPath = applicationPath; + ProgramSystemPath = appFolderPath; } - public string ApplicationPath { get; private set; } public string ProgramDataPath { get; private set; } /// /// Gets the path to the system folder /// - public string ProgramSystemPath - { - get { return Path.GetDirectoryName(ApplicationPath); } - } + public string ProgramSystemPath { get; private set; } /// /// The _data directory diff --git a/Emby.Common.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Common.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 6a1b3ef74..c040e3931 100644 --- a/Emby.Common.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Common.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -95,5 +95,15 @@ namespace Emby.Common.Implementations.EnvironmentInfo return MediaBrowser.Model.System.Architecture.X64; } } + + public string GetEnvironmentVariable(string name) + { + return Environment.GetEnvironmentVariable(name); + } + + public virtual string GetUserId() + { + return null; + } } } diff --git a/Emby.Common.Implementations/IO/ManagedFileSystem.cs b/Emby.Common.Implementations/IO/ManagedFileSystem.cs index 1f0aa55fa..83bb50f94 100644 --- a/Emby.Common.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Common.Implementations/IO/ManagedFileSystem.cs @@ -57,6 +57,14 @@ namespace Emby.Common.Implementations.IO } } + public char PathSeparator + { + get + { + return Path.DirectorySeparatorChar; + } + } + public string GetFullPath(string path) { return Path.GetFullPath(path); diff --git a/Emby.Common.Implementations/Net/NetSocket.cs b/Emby.Common.Implementations/Net/NetSocket.cs index faa1a81e2..62ca3d6ac 100644 --- a/Emby.Common.Implementations/Net/NetSocket.cs +++ b/Emby.Common.Implementations/Net/NetSocket.cs @@ -15,6 +15,15 @@ namespace Emby.Common.Implementations.Net public NetSocket(Socket socket, ILogger logger) { + if (socket == null) + { + throw new ArgumentNullException("socket"); + } + if (logger == null) + { + throw new ArgumentNullException("logger"); + } + Socket = socket; _logger = logger; } diff --git a/Emby.Common.Implementations/Net/SocketAcceptor.cs b/Emby.Common.Implementations/Net/SocketAcceptor.cs index fd65e9fbc..bddb7a079 100644 --- a/Emby.Common.Implementations/Net/SocketAcceptor.cs +++ b/Emby.Common.Implementations/Net/SocketAcceptor.cs @@ -14,6 +14,23 @@ namespace Emby.Common.Implementations.Net public SocketAcceptor(ILogger logger, Socket originalSocket, Action onAccept, Func isClosed) { + if (logger == null) + { + throw new ArgumentNullException("logger"); + } + if (originalSocket == null) + { + throw new ArgumentNullException("originalSocket"); + } + if (onAccept == null) + { + throw new ArgumentNullException("onAccept"); + } + if (isClosed == null) + { + throw new ArgumentNullException("isClosed"); + } + _logger = logger; _originalSocket = originalSocket; _isClosed = isClosed; @@ -101,11 +118,8 @@ namespace Emby.Common.Implementations.Net _onAccept(new NetSocket(acceptSocket, _logger)); } - if (_originalSocket != null) - { - // Accept the next connection request - StartAccept(e, ref acceptSocket); - } + // Accept the next connection request + StartAccept(e, ref acceptSocket); } } } diff --git a/Emby.Common.Implementations/Net/SocketFactory.cs b/Emby.Common.Implementations/Net/SocketFactory.cs index 922b0f3cc..f26137683 100644 --- a/Emby.Common.Implementations/Net/SocketFactory.cs +++ b/Emby.Common.Implementations/Net/SocketFactory.cs @@ -23,10 +23,15 @@ namespace Emby.Common.Implementations.Net /// private IPAddress _LocalIP; - private ILogger _logger; + private readonly ILogger _logger; public SocketFactory(ILogger logger) { + if (logger == null) + { + throw new ArgumentNullException("logger"); + } + _logger = logger; _LocalIP = IPAddress.Any; } diff --git a/Emby.Server.Core/ApplicationHost.cs b/Emby.Server.Core/ApplicationHost.cs index 7f795a68d..d3d292ca5 100644 --- a/Emby.Server.Core/ApplicationHost.cs +++ b/Emby.Server.Core/ApplicationHost.cs @@ -725,6 +725,11 @@ namespace Emby.Server.Core try { + if (!FileSystemManager.FileExists(certificateLocation)) + { + return null; + } + X509Certificate2 localCert = new X509Certificate2(certificateLocation); //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) @@ -1438,12 +1443,7 @@ namespace Emby.Server.Core try { - AuthorizeServer( - UdpServerEntryPoint.PortNumber, - ServerConfigurationManager.Configuration.HttpServerPortNumber, - ServerConfigurationManager.Configuration.HttpsPortNumber, - ConfigurationManager.CommonApplicationPaths.ApplicationPath, - ConfigurationManager.CommonApplicationPaths.TempDirectory); + AuthorizeServer(); } catch (Exception ex) { @@ -1451,7 +1451,7 @@ namespace Emby.Server.Core } } - protected abstract void AuthorizeServer(int udpPort, int httpServerPort, int httpsServerPort, string applicationPath, string tempDirectory); + protected abstract void AuthorizeServer(); protected abstract IDbConnector GetDbConnector(); public event EventHandler HasUpdateAvailableChanged; diff --git a/Emby.Server.Core/Data/DataExtensions.cs b/Emby.Server.Core/Data/DataExtensions.cs index b633d9217..631c1c500 100644 --- a/Emby.Server.Core/Data/DataExtensions.cs +++ b/Emby.Server.Core/Data/DataExtensions.cs @@ -40,7 +40,7 @@ namespace Emby.Server.Core.Data public static IDataParameter Add(this IDataParameterCollection paramCollection, IDbCommand cmd, string name) { var param = cmd.CreateParameter(); - + param.ParameterName = name; paramCollection.Add(param); @@ -173,7 +173,7 @@ namespace Emby.Server.Core.Data var builder = new StringBuilder(); builder.AppendLine("alter table " + table); - builder.AppendLine("add column " + columnName + " " + type); + builder.AppendLine("add column " + columnName + " " + type + " NULL"); connection.RunQueries(new[] { builder.ToString() }, logger); } diff --git a/Emby.Server.Core/Data/SqliteItemRepository.cs b/Emby.Server.Core/Data/SqliteItemRepository.cs index 2ca86c831..6ed409aa1 100644 --- a/Emby.Server.Core/Data/SqliteItemRepository.cs +++ b/Emby.Server.Core/Data/SqliteItemRepository.cs @@ -157,7 +157,7 @@ namespace Emby.Server.Core.Data string[] queries = { - "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB, ParentId GUID, Path TEXT)", + "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)", "create table if not exists AncestorIds (ItemId GUID, AncestorId GUID, AncestorIdText TEXT, PRIMARY KEY (ItemId, AncestorId))", "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)", @@ -286,6 +286,7 @@ namespace Emby.Server.Core.Data _connection.AddColumn(Logger, "TypedBaseItems", "ExtraType", "Text"); _connection.AddColumn(Logger, "TypedBaseItems", "Artists", "Text"); _connection.AddColumn(Logger, "TypedBaseItems", "AlbumArtists", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "ExternalId", "Text"); _connection.AddColumn(Logger, "ItemValues", "CleanValue", "Text"); @@ -440,7 +441,8 @@ namespace Emby.Server.Core.Data "TotalBitrate", "ExtraType", "Artists", - "AlbumArtists" + "AlbumArtists", + "ExternalId" }; private readonly string[] _mediaStreamSaveColumns = @@ -575,7 +577,8 @@ namespace Emby.Server.Core.Data "TotalBitrate", "ExtraType", "Artists", - "AlbumArtists" + "AlbumArtists", + "ExternalId" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -1084,6 +1087,10 @@ namespace Emby.Server.Core.Data } } + _saveItemCommand.GetParameter(index++).Value = item.ExternalId; + + //Logger.Debug(_saveItemCommand.CommandText); + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); @@ -1967,6 +1974,12 @@ namespace Emby.Server.Core.Data } index++; + if (!reader.IsDBNull(index)) + { + item.ExternalId = reader.GetString(index); + } + index++; + if (string.IsNullOrWhiteSpace(item.Tagline)) { var movie = item as Movie; diff --git a/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs b/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs index 8a7fc9270..dee0d4cfd 100644 --- a/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs +++ b/Emby.Server.Core/Notifications/SqliteNotificationsRepository.cs @@ -30,7 +30,7 @@ namespace Emby.Server.Core.Notifications { string[] queries = { - "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))", + "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT NULL, Url TEXT NULL, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT NULL, PRIMARY KEY (Id, UserId))", "create index if not exists idx_Notifications1 on Notifications(Id)", "create index if not exists idx_Notifications2 on Notifications(UserId)" }; diff --git a/Emby.Server.Core/ServerApplicationPaths.cs b/Emby.Server.Core/ServerApplicationPaths.cs index d59dd89d9..dc80b773c 100644 --- a/Emby.Server.Core/ServerApplicationPaths.cs +++ b/Emby.Server.Core/ServerApplicationPaths.cs @@ -12,8 +12,8 @@ namespace Emby.Server.Core /// /// Initializes a new instance of the class. /// - public ServerApplicationPaths(string programDataPath, string applicationPath, string applicationResourcesPath) - : base(programDataPath, applicationPath) + public ServerApplicationPaths(string programDataPath, string appFolderPath, string applicationResourcesPath) + : base(programDataPath, appFolderPath) { ApplicationResourcesPath = applicationResourcesPath; } diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 2ce880c93..94ff7c342 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -326,7 +326,7 @@ namespace Emby.Server.Implementations.Channels if (requiresCallback != null) { - results = await GetChannelItemMediaSourcesInternal(requiresCallback, item.ExternalId, cancellationToken) + results = await GetChannelItemMediaSourcesInternal(requiresCallback, GetItemExternalId(item), cancellationToken) .ConfigureAwait(false); } else @@ -1075,6 +1075,18 @@ namespace Emby.Server.Implementations.Channels return result; } + private string GetItemExternalId(BaseItem item) + { + var externalId = item.ExternalId; + + if (string.IsNullOrWhiteSpace(externalId)) + { + externalId = item.GetProviderId("ProviderExternalId"); + } + + return externalId; + } + private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1); private async Task GetChannelItems(IChannel channel, User user, @@ -1145,7 +1157,7 @@ namespace Emby.Server.Implementations.Channels { var categoryItem = _libraryManager.GetItemById(new Guid(folderId)); - query.FolderId = categoryItem.ExternalId; + query.FolderId = GetItemExternalId(categoryItem); } var result = await channel.GetChannelItems(query, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 41b7a4622..876d140ec 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -396,6 +396,8 @@ namespace Emby.Server.Implementations.HttpServer if (_disposed) { httpRes.StatusCode = 503; + httpRes.ContentType = "text/plain"; + Write(httpRes, "Server shutting down"); return; } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 63356a845..aaf74b5c6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1551,13 +1551,28 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { + if (timer.IsSports) + { + AddGenre(timer.Genres, "Sports"); + } + if (timer.IsKids) + { + AddGenre(timer.Genres, "Kids"); + AddGenre(timer.Genres, "Children"); + } + if (timer.IsNews) + { + AddGenre(timer.Genres, "News"); + } + if (timer.IsProgramSeries) { SaveSeriesNfo(timer, recordingPath, seriesPath); + SaveVideoNfo(timer, recordingPath, false); } else if (!timer.IsMovie || timer.IsSports || timer.IsNews) { - SaveVideoNfo(timer, recordingPath); + SaveVideoNfo(timer, recordingPath, true); } } catch (Exception ex) @@ -1594,6 +1609,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV writer.WriteElementString("title", timer.Name); } + if (!string.IsNullOrEmpty(timer.OfficialRating)) + { + writer.WriteElementString("mpaa", timer.OfficialRating); + } + + foreach (var genre in timer.Genres) + { + writer.WriteElementString("genre", genre); + } + writer.WriteEndElement(); writer.WriteEndDocument(); } @@ -1601,7 +1626,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss"; - private void SaveVideoNfo(TimerInfo timer, string recordingPath) + private void SaveVideoNfo(TimerInfo timer, string recordingPath, bool lockData) { var nfoPath = Path.ChangeExtension(recordingPath, ".nfo"); @@ -1622,11 +1647,41 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV using (XmlWriter writer = XmlWriter.Create(stream, settings)) { writer.WriteStartDocument(true); - writer.WriteStartElement("movie"); - if (!string.IsNullOrWhiteSpace(timer.Name)) + if (timer.IsProgramSeries) { - writer.WriteElementString("title", timer.Name); + writer.WriteStartElement("episodedetails"); + + if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle)) + { + writer.WriteElementString("title", timer.EpisodeTitle); + } + + if (timer.OriginalAirDate.HasValue) + { + var formatString = _config.GetNfoConfiguration().ReleaseDateFormat; + + writer.WriteElementString("aired", timer.OriginalAirDate.Value.ToLocalTime().ToString(formatString)); + } + + if (timer.EpisodeNumber.HasValue) + { + writer.WriteElementString("episode", timer.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture)); + } + + if (timer.SeasonNumber.HasValue) + { + writer.WriteElementString("season", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); + } + } + else + { + writer.WriteStartElement("movie"); + + if (!string.IsNullOrWhiteSpace(timer.Name)) + { + writer.WriteElementString("title", timer.Name); + } } writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat)); @@ -1645,25 +1700,15 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV .Replace(""", "'"); writer.WriteElementString("plot", overview); - writer.WriteElementString("lockdata", true.ToString().ToLower()); - if (timer.CommunityRating.HasValue) + if (lockData) { - writer.WriteElementString("rating", timer.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)); + writer.WriteElementString("lockdata", true.ToString().ToLower()); } - if (timer.IsSports) - { - AddGenre(timer.Genres, "Sports"); - } - if (timer.IsKids) - { - AddGenre(timer.Genres, "Kids"); - AddGenre(timer.Genres, "Children"); - } - if (timer.IsNews) + if (timer.CommunityRating.HasValue) { - AddGenre(timer.Genres, "News"); + writer.WriteElementString("rating", timer.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)); } foreach (var genre in timer.Genres) @@ -1968,4 +2013,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public CancellationTokenSource CancellationTokenSource { get; set; } } } + public static class ConfigurationExtension + { + public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager) + { + return manager.GetConfiguration("xbmcmetadata"); + } + } } \ No newline at end of file diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index ded4f04c4..16ae26d45 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -54,9 +54,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV catch (FileNotFoundException) { } - catch (IOException ex) + catch (IOException) { - Logger.ErrorException("Error deserializing {0}", ex, jsonFile); } catch (Exception ex) { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index 4e7161521..d3e30a46b 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -269,6 +269,18 @@ namespace Emby.Server.Implementations.LiveTv return _libraryManager.GetNewItemId(name.ToLower(), typeof(ILiveTvRecording)); } + private string GetItemExternalId(BaseItem item) + { + var externalId = item.ExternalId; + + if (string.IsNullOrWhiteSpace(externalId)) + { + externalId = item.GetProviderId("ProviderExternalId"); + } + + return externalId; + } + public async Task GetTimerInfo(TimerInfoDto dto, bool isNew, LiveTvManager liveTv, CancellationToken cancellationToken) { var info = new TimerInfo @@ -304,7 +316,7 @@ namespace Emby.Server.Implementations.LiveTv if (channel != null) { - info.ChannelId = channel.ExternalId; + info.ChannelId = GetItemExternalId(channel); } } @@ -314,7 +326,7 @@ namespace Emby.Server.Implementations.LiveTv if (program != null) { - info.ProgramId = program.ExternalId; + info.ProgramId = GetItemExternalId(program); } } @@ -370,7 +382,7 @@ namespace Emby.Server.Implementations.LiveTv if (channel != null) { - info.ChannelId = channel.ExternalId; + info.ChannelId = GetItemExternalId(channel); } } @@ -380,7 +392,7 @@ namespace Emby.Server.Implementations.LiveTv if (program != null) { - info.ProgramId = program.ExternalId; + info.ProgramId = GetItemExternalId(program); } } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index adec66858..3a6f23fe9 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -251,12 +251,24 @@ namespace Emby.Server.Implementations.LiveTv return await GetLiveStream(id, mediaSourceId, true, cancellationToken).ConfigureAwait(false); } + private string GetItemExternalId(BaseItem item) + { + var externalId = item.ExternalId; + + if (string.IsNullOrWhiteSpace(externalId)) + { + externalId = item.GetProviderId("ProviderExternalId"); + } + + return externalId; + } + public async Task> GetRecordingMediaSources(IHasMediaSources item, CancellationToken cancellationToken) { var baseItem = (BaseItem)item; var service = GetService(baseItem); - return await service.GetRecordingStreamMediaSources(baseItem.ExternalId, cancellationToken).ConfigureAwait(false); + return await service.GetRecordingStreamMediaSources(GetItemExternalId(baseItem), cancellationToken).ConfigureAwait(false); } public async Task> GetChannelMediaSources(IHasMediaSources item, CancellationToken cancellationToken) @@ -313,18 +325,18 @@ namespace Emby.Server.Implementations.LiveTv var channel = GetInternalChannel(id); isVideo = channel.ChannelType == ChannelType.TV; service = GetService(channel); - _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); + _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, GetItemExternalId(channel)); var supportsManagedStream = service as ISupportsDirectStreamProvider; if (supportsManagedStream != null) { - var streamInfo = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false); + var streamInfo = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(GetItemExternalId(channel), mediaSourceId, cancellationToken).ConfigureAwait(false); info = streamInfo.Item1; directStreamProvider = streamInfo.Item2; } else { - info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false); + info = await service.GetChannelStream(GetItemExternalId(channel), mediaSourceId, cancellationToken).ConfigureAwait(false); } info.RequiresClosing = true; @@ -341,8 +353,8 @@ namespace Emby.Server.Implementations.LiveTv isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase); service = GetService(recording); - _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.ExternalId); - info = await service.GetRecordingStream(recording.ExternalId, null, cancellationToken).ConfigureAwait(false); + _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, GetItemExternalId(recording)); + info = await service.GetRecordingStream(GetItemExternalId(recording), null, cancellationToken).ConfigureAwait(false); info.RequiresClosing = true; if (info.RequiresClosing) @@ -493,7 +505,7 @@ namespace Emby.Server.Implementations.LiveTv isNew = true; } - if (!string.Equals(channelInfo.Id, item.ExternalId)) + if (!string.Equals(channelInfo.Id, item.ExternalId, StringComparison.Ordinal)) { isNew = true; } @@ -601,7 +613,6 @@ namespace Emby.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)) { @@ -841,6 +852,13 @@ namespace Emby.Server.Implementations.LiveTv return item.Id; } + + + private string GetExternalSeriesIdLegacy(BaseItem item) + { + return item.GetProviderId("ProviderExternalSeriesId"); + } + public async Task GetProgram(string id, CancellationToken cancellationToken, User user = null) { var program = GetInternalProgram(id); @@ -848,7 +866,15 @@ namespace Emby.Server.Implementations.LiveTv var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user); var list = new List>(); - list.Add(new Tuple(dto, program.ServiceName, program.ExternalId, program.ExternalSeriesIdLegacy)); + + var externalSeriesId = program.ExternalSeriesId; + + if (string.IsNullOrWhiteSpace(externalSeriesId)) + { + externalSeriesId = GetExternalSeriesIdLegacy(program); + } + + list.Add(new Tuple(dto, program.ServiceName, GetItemExternalId(program), externalSeriesId)); await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false); @@ -1283,7 +1309,7 @@ namespace Emby.Server.Implementations.LiveTv var isKids = false; var iSSeries = false; - var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false); + var channelPrograms = await service.GetProgramsAsync(GetItemExternalId(currentChannel), start, end, cancellationToken).ConfigureAwait(false); var existingPrograms = _libraryManager.GetItemList(new InternalItemsQuery { @@ -1830,7 +1856,14 @@ namespace Emby.Server.Implementations.LiveTv dto.ServiceName = serviceName; } - programTuples.Add(new Tuple(dto, serviceName, program.ExternalId, program.ExternalSeriesIdLegacy)); + var externalSeriesId = program.ExternalSeriesId; + + if (string.IsNullOrWhiteSpace(externalSeriesId)) + { + externalSeriesId = GetExternalSeriesIdLegacy(program); + } + + programTuples.Add(new Tuple(dto, serviceName, GetItemExternalId(program), externalSeriesId)); } await AddRecordingInfo(programTuples, CancellationToken.None).ConfigureAwait(false); @@ -2006,7 +2039,7 @@ namespace Emby.Server.Implementations.LiveTv if (service is EmbyTV.EmbyTV) { // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says - return service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None); + return service.DeleteRecordingAsync(GetItemExternalId(recording), CancellationToken.None); } return Task.FromResult(true); @@ -2030,7 +2063,7 @@ namespace Emby.Server.Implementations.LiveTv try { - await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false); + await service.DeleteRecordingAsync(GetItemExternalId(recording), CancellationToken.None).ConfigureAwait(false); } catch (ResourceNotFoundException) { @@ -2289,12 +2322,12 @@ namespace Emby.Server.Implementations.LiveTv programInfo = new ProgramInfo { Audio = program.Audio, - ChannelId = channel.ExternalId, + ChannelId = GetItemExternalId(channel), CommunityRating = program.CommunityRating, EndDate = program.EndDate ?? DateTime.MinValue, EpisodeTitle = program.EpisodeTitle, Genres = program.Genres, - Id = program.ExternalId, + Id = GetItemExternalId(program), IsHD = program.IsHD, IsKids = program.IsKids, IsLive = program.IsLive, @@ -2360,7 +2393,7 @@ namespace Emby.Server.Implementations.LiveTv info.Name = program.Name; info.Overview = program.Overview; info.ProgramId = programDto.Id; - info.ExternalProgramId = program.ExternalId; + info.ExternalProgramId = GetItemExternalId(program); if (program.EndDate.HasValue) { @@ -2804,7 +2837,7 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { - info = _jsonSerializer.DeserializeFromString< ListingsProviderInfo>(_jsonSerializer.SerializeToString(info)); + info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); diff --git a/Emby.Server.Implementations/LiveTv/ProgramImageProvider.cs b/Emby.Server.Implementations/LiveTv/ProgramImageProvider.cs index f5d298af4..5a0389b16 100644 --- a/Emby.Server.Implementations/LiveTv/ProgramImageProvider.cs +++ b/Emby.Server.Implementations/LiveTv/ProgramImageProvider.cs @@ -24,6 +24,18 @@ namespace Emby.Server.Implementations.LiveTv return new[] { ImageType.Primary }; } + private string GetItemExternalId(BaseItem item) + { + var externalId = item.ExternalId; + + if (string.IsNullOrWhiteSpace(externalId)) + { + externalId = item.GetProviderId("ProviderExternalId"); + } + + return externalId; + } + public async Task GetImage(IHasImages item, ImageType type, CancellationToken cancellationToken) { var liveTvItem = (LiveTvProgram)item; @@ -38,7 +50,7 @@ namespace Emby.Server.Implementations.LiveTv { var channel = _liveTvManager.GetInternalChannel(liveTvItem.ChannelId); - var response = await service.GetProgramImageAsync(liveTvItem.ExternalId, channel.ExternalId, cancellationToken).ConfigureAwait(false); + var response = await service.GetProgramImageAsync(GetItemExternalId(liveTvItem), GetItemExternalId(channel), cancellationToken).ConfigureAwait(false); if (response != null) { diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index bc0241766..37ab12366 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -128,7 +128,11 @@ namespace MediaBrowser.Api { // Don't clutter the log } - catch (IOException ex) + catch (IOException) + { + // Don't clutter the log + } + catch (Exception ex) { Logger.ErrorException("Error deleting encoded media cache", ex); } diff --git a/MediaBrowser.Common/Configuration/IApplicationPaths.cs b/MediaBrowser.Common/Configuration/IApplicationPaths.cs index d3bf03302..d2446ce46 100644 --- a/MediaBrowser.Common/Configuration/IApplicationPaths.cs +++ b/MediaBrowser.Common/Configuration/IApplicationPaths.cs @@ -6,12 +6,6 @@ namespace MediaBrowser.Common.Configuration /// public interface IApplicationPaths { - /// - /// Gets the application path. - /// - /// The application path. - string ApplicationPath { get; } - /// /// Gets the path to the program data folder /// diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index b079da97c..10cac7992 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -296,28 +296,11 @@ namespace MediaBrowser.Controller.Entities /// If this content came from an external service, the id of the content on that service /// [IgnoreDataMember] - public string ExternalId - { - get { return this.GetProviderId("ProviderExternalId"); } - set - { - this.SetProviderId("ProviderExternalId", value); - } - } + public string ExternalId { get; set; } [IgnoreDataMember] public string ExternalSeriesId { get; set; } - [IgnoreDataMember] - public string ExternalSeriesIdLegacy - { - get { return this.GetProviderId("ProviderExternalSeriesId"); } - set - { - this.SetProviderId("ProviderExternalSeriesId", value); - } - } - /// /// Gets or sets the etag. /// diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 6acdccf3d..1b8b3feec 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -37,20 +37,22 @@ namespace MediaBrowser.MediaEncoding.Encoder { output = GetProcessOutput(encoderAppPath, "-version"); } - catch + catch (Exception ex) { + if (logOutput) + { + _logger.ErrorException("Error validating encoder", ex); + } } - output = output ?? string.Empty; - - if (logOutput) + if (string.IsNullOrWhiteSpace(output)) { - _logger.Info("ffmpeg info: {0}", output); + return false; } - if (string.IsNullOrWhiteSpace(output)) + if (logOutput) { - return false; + _logger.Info("ffmpeg info: {0}", output); } if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1) diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index f219d9295..22e1e7758 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -308,6 +308,7 @@ namespace MediaBrowser.Model.IO void SetReadOnly(string path, bool isHidden); char DirectorySeparatorChar { get; } + char PathSeparator { get; } string GetFullPath(string path); diff --git a/MediaBrowser.Model/System/IEnvironmentInfo.cs b/MediaBrowser.Model/System/IEnvironmentInfo.cs index c5f493e7c..7e7d81e30 100644 --- a/MediaBrowser.Model/System/IEnvironmentInfo.cs +++ b/MediaBrowser.Model/System/IEnvironmentInfo.cs @@ -12,6 +12,8 @@ namespace MediaBrowser.Model.System string OperatingSystemName { get; } string OperatingSystemVersion { get; } Architecture SystemArchitecture { get; } + string GetEnvironmentVariable(string name); + string GetUserId(); } public enum OperatingSystem diff --git a/MediaBrowser.Server.Mono/MonoAppHost.cs b/MediaBrowser.Server.Mono/MonoAppHost.cs index 5f0ecde24..fd3c9f506 100644 --- a/MediaBrowser.Server.Mono/MonoAppHost.cs +++ b/MediaBrowser.Server.Mono/MonoAppHost.cs @@ -91,7 +91,7 @@ namespace MediaBrowser.Server.Mono MainClass.Shutdown(); } - protected override void AuthorizeServer(int udpPort, int httpServerPort, int httpsServerPort, string applicationPath, string tempDirectory) + protected override void AuthorizeServer() { throw new NotImplementedException(); } diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 48390f078..470525ece 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -5,6 +5,7 @@ using MediaBrowser.Server.Startup.Common; using Microsoft.Win32; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -74,7 +75,9 @@ namespace MediaBrowser.Server.Mono programDataPath = ApplicationPathHelper.GetProgramDataPath(applicationPath); } - return new ServerApplicationPaths(programDataPath, applicationPath, Path.GetDirectoryName(applicationPath)); + var appFolderPath = Path.GetDirectoryName(applicationPath); + + return new ServerApplicationPaths(programDataPath, appFolderPath, Path.GetDirectoryName(applicationPath)); } private static readonly TaskCompletionSource ApplicationTaskCompletionSource = new TaskCompletionSource(); @@ -305,5 +308,10 @@ namespace MediaBrowser.Server.Mono public class MonoEnvironmentInfo : EnvironmentInfo { public bool IsBsd { get; set; } + + public virtual string GetUserId() + { + return Syscall.getuid().ToString(CultureInfo.InvariantCulture); + } } } diff --git a/MediaBrowser.Server.Startup.Common/Persistence/SqliteExtensions.cs b/MediaBrowser.Server.Startup.Common/Persistence/SqliteExtensions.cs index 72ecfc1bf..22aeb53dd 100644 --- a/MediaBrowser.Server.Startup.Common/Persistence/SqliteExtensions.cs +++ b/MediaBrowser.Server.Startup.Common/Persistence/SqliteExtensions.cs @@ -14,7 +14,11 @@ namespace Emby.Server.Core.Data /// /// Connects to db. /// - public static async Task ConnectToDb(string dbPath, bool isReadOnly, bool enablePooling, int? cacheSize, ILogger logger) + public static async Task ConnectToDb(string dbPath, + bool isReadOnly, + bool enablePooling, + int? cacheSize, + ILogger logger) { if (string.IsNullOrEmpty(dbPath)) { diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index ab0a36aff..c0ebcde74 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -44,6 +44,8 @@ namespace MediaBrowser.ServerApplication [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetDllDirectory(string lpPathName); + public static string ApplicationPath; + public static bool TryGetLocalFromUncDirectory(string local, out string unc) { if ((local == null) || (local == "")) @@ -81,14 +83,14 @@ namespace MediaBrowser.ServerApplication var currentProcess = Process.GetCurrentProcess(); - var applicationPath = currentProcess.MainModule.FileName; - var architecturePath = Path.Combine(Path.GetDirectoryName(applicationPath), Environment.Is64BitProcess ? "x64" : "x86"); + ApplicationPath = currentProcess.MainModule.FileName; + var architecturePath = Path.Combine(Path.GetDirectoryName(ApplicationPath), Environment.Is64BitProcess ? "x64" : "x86"); Wand.SetMagickCoderModulePath(architecturePath); var success = SetDllDirectory(architecturePath); - var appPaths = CreateApplicationPaths(applicationPath, IsRunningAsService); + var appPaths = CreateApplicationPaths(ApplicationPath, IsRunningAsService); var logManager = new NlogManager(appPaths.LogDirectoryPath, "server"); logManager.ReloadLogger(LogSeverity.Debug); @@ -102,7 +104,7 @@ namespace MediaBrowser.ServerApplication if (options.ContainsOption("-installservice")) { logger.Info("Performing service installation"); - InstallService(applicationPath, logger); + InstallService(ApplicationPath, logger); return; } @@ -110,7 +112,7 @@ namespace MediaBrowser.ServerApplication if (options.ContainsOption("-installserviceasadmin")) { logger.Info("Performing service installation"); - RunServiceInstallation(applicationPath); + RunServiceInstallation(ApplicationPath); return; } @@ -118,7 +120,7 @@ namespace MediaBrowser.ServerApplication if (options.ContainsOption("-uninstallservice")) { logger.Info("Performing service uninstallation"); - UninstallService(applicationPath, logger); + UninstallService(ApplicationPath, logger); return; } @@ -126,15 +128,15 @@ namespace MediaBrowser.ServerApplication if (options.ContainsOption("-uninstallserviceasadmin")) { logger.Info("Performing service uninstallation"); - RunServiceUninstallation(applicationPath); + RunServiceUninstallation(ApplicationPath); return; } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - RunServiceInstallationIfNeeded(applicationPath); + RunServiceInstallationIfNeeded(ApplicationPath); - if (IsAlreadyRunning(applicationPath, currentProcess)) + if (IsAlreadyRunning(ApplicationPath, currentProcess)) { logger.Info("Shutting down because another instance of Emby Server is already running."); return; @@ -250,6 +252,8 @@ namespace MediaBrowser.ServerApplication /// ServerApplicationPaths. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService) { + var appFolderPath = Path.GetDirectoryName(applicationPath); + var resourcesPath = Path.GetDirectoryName(applicationPath); if (runAsService) @@ -258,10 +262,10 @@ namespace MediaBrowser.ServerApplication var programDataPath = Path.GetDirectoryName(systemPath); - return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath); + return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath); } - return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath); + return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath); } /// @@ -663,7 +667,7 @@ namespace MediaBrowser.ServerApplication _logger.Info("Starting new instance"); //Application.Restart(); - Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath); + Process.Start(ApplicationPath); ShutdownWindowsApplication(); } diff --git a/MediaBrowser.ServerApplication/Updates/ApplicationUpdater.cs b/MediaBrowser.ServerApplication/Updates/ApplicationUpdater.cs index c426395b7..97537b27d 100644 --- a/MediaBrowser.ServerApplication/Updates/ApplicationUpdater.cs +++ b/MediaBrowser.ServerApplication/Updates/ApplicationUpdater.cs @@ -44,7 +44,7 @@ namespace MediaBrowser.ServerApplication.Updates // startpath = executable to launch // systempath = folder containing installation var args = string.Format("product={0} archive=\"{1}\" caller={2} pismo=false version={3} service={4} installpath=\"{5}\" startpath=\"{6}\" systempath=\"{7}\"", - product, archive, Process.GetCurrentProcess().Id, version, restartServiceName ?? string.Empty, appPaths.ProgramDataPath, appPaths.ApplicationPath, systemPath); + product, archive, Process.GetCurrentProcess().Id, version, restartServiceName ?? string.Empty, appPaths.ProgramDataPath, MainStartup.ApplicationPath, systemPath); logger.Info("Args: {0}", args); Process.Start(tempUpdater, args); diff --git a/MediaBrowser.ServerApplication/WindowsAppHost.cs b/MediaBrowser.ServerApplication/WindowsAppHost.cs index 8fd718432..d9bead6b7 100644 --- a/MediaBrowser.ServerApplication/WindowsAppHost.cs +++ b/MediaBrowser.ServerApplication/WindowsAppHost.cs @@ -6,6 +6,7 @@ using System.Reflection; using Emby.Server.Core; using Emby.Server.Core.Data; using Emby.Server.Core.FFMpeg; +using Emby.Server.Implementations.EntryPoints; using MediaBrowser.Model.IO; using MediaBrowser.Model.Logging; using MediaBrowser.Model.System; @@ -60,9 +61,13 @@ namespace MediaBrowser.ServerApplication MainStartup.Shutdown(); } - protected override void AuthorizeServer(int udpPort, int httpServerPort, int httpsServerPort, string applicationPath, string tempDirectory) + protected override void AuthorizeServer() { - ServerAuthorization.AuthorizeServer(udpPort, httpServerPort, httpsServerPort, applicationPath, tempDirectory); + ServerAuthorization.AuthorizeServer(UdpServerEntryPoint.PortNumber, + ServerConfigurationManager.Configuration.HttpServerPortNumber, + ServerConfigurationManager.Configuration.HttpsPortNumber, + MainStartup.ApplicationPath, + ConfigurationManager.CommonApplicationPaths.TempDirectory); } protected override IDbConnector GetDbConnector() diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs index 4c22f0246..b512939a7 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs @@ -90,8 +90,6 @@ namespace MediaBrowser.XbmcMetadata.Savers } } - private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - protected override List GetTagsUsed() { var list = new List diff --git a/Nuget/MediaBrowser.Common.nuspec b/Nuget/MediaBrowser.Common.nuspec index 464a29eb2..daeb754ba 100644 --- a/Nuget/MediaBrowser.Common.nuspec +++ b/Nuget/MediaBrowser.Common.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Common - 3.0.689 + 3.0.691 Emby.Common Emby Team ebr,Luke,scottisafool diff --git a/Nuget/MediaBrowser.Server.Core.nuspec b/Nuget/MediaBrowser.Server.Core.nuspec index 96e9a697a..a34a9bee2 100644 --- a/Nuget/MediaBrowser.Server.Core.nuspec +++ b/Nuget/MediaBrowser.Server.Core.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Server.Core - 3.0.689 + 3.0.691 Emby.Server.Core Emby Team ebr,Luke,scottisafool @@ -12,7 +12,7 @@ Contains core components required to build plugins for Emby Server. Copyright © Emby 2013 - + diff --git a/src/Emby.Server/ApplicationPathHelper.cs b/src/Emby.Server/ApplicationPathHelper.cs index 4da87b6a0..c611ff372 100644 --- a/src/Emby.Server/ApplicationPathHelper.cs +++ b/src/Emby.Server/ApplicationPathHelper.cs @@ -8,7 +8,7 @@ namespace Emby.Server { public class ApplicationPathHelper { - public static string GetProgramDataPath(string applicationPath) + public static string GetProgramDataPath(string appDirectory) { var useDebugPath = false; @@ -27,14 +27,7 @@ namespace Emby.Server // If it's a relative path, e.g. "..\" if (!Path.IsPathRooted(programDataPath)) { - var path = Path.GetDirectoryName(applicationPath); - - if (string.IsNullOrEmpty(path)) - { - throw new Exception("Unable to determine running assembly location"); - } - - programDataPath = Path.Combine(path, programDataPath); + programDataPath = Path.Combine(appDirectory, programDataPath); programDataPath = Path.GetFullPath(programDataPath); } diff --git a/src/Emby.Server/CoreAppHost.cs b/src/Emby.Server/CoreAppHost.cs index 1a1526513..21f6ae445 100644 --- a/src/Emby.Server/CoreAppHost.cs +++ b/src/Emby.Server/CoreAppHost.cs @@ -51,7 +51,7 @@ namespace Emby.Server return list; } - protected override void AuthorizeServer(int udpPort, int httpServerPort, int httpsServerPort, string applicationPath, string tempDirectory) + protected override void AuthorizeServer() { } diff --git a/src/Emby.Server/Program.cs b/src/Emby.Server/Program.cs index 64fc423a1..6f871990d 100644 --- a/src/Emby.Server/Program.cs +++ b/src/Emby.Server/Program.cs @@ -28,8 +28,6 @@ namespace Emby.Server private static ILogger _logger; - private static bool _isRunningAsService = false; - private static bool _canRestartService = false; private static bool _appHostDisposed; [DllImport("kernel32.dll", SetLastError = true)] @@ -41,39 +39,33 @@ namespace Emby.Server public static void Main(string[] args) { var options = new StartupOptions(); - _isRunningAsService = options.ContainsOption("-service"); - - if (_isRunningAsService) - { - //_canRestartService = CanRestartWindowsService(); - } var currentProcess = Process.GetCurrentProcess(); - - var applicationPath = currentProcess.MainModule.FileName; + + var baseDirectory = System.AppContext.BaseDirectory; //var architecturePath = Path.Combine(Path.GetDirectoryName(applicationPath), Environment.Is64BitProcess ? "x64" : "x86"); //Wand.SetMagickCoderModulePath(architecturePath); //var success = SetDllDirectory(architecturePath); - var appPaths = CreateApplicationPaths(applicationPath, _isRunningAsService); + var appPaths = CreateApplicationPaths(baseDirectory); var logManager = new NlogManager(appPaths.LogDirectoryPath, "server"); logManager.ReloadLogger(LogSeverity.Debug); logManager.AddConsoleOutput(); var logger = _logger = logManager.GetLogger("Main"); - + ApplicationHost.LogEnvironmentInfo(logger, appPaths, true); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - if (IsAlreadyRunning(applicationPath, currentProcess)) - { - logger.Info("Shutting down because another instance of Emby Server is already running."); - return; - } + //if (IsAlreadyRunning(applicationPath, currentProcess)) + //{ + // logger.Info("Shutting down because another instance of Emby Server is already running."); + // return; + //} if (PerformUpdateIfNeeded(appPaths, logger)) { @@ -81,14 +73,7 @@ namespace Emby.Server return; } - try - { - RunApplication(appPaths, logManager, _isRunningAsService, options); - } - finally - { - OnServiceShutdown(); - } + RunApplication(appPaths, logManager, options); } /// @@ -139,34 +124,17 @@ namespace Emby.Server } } - if (!_isRunningAsService) - { - return false; - } - return false; } /// /// Creates the application paths. /// - /// The application path. - /// if set to true [run as service]. - /// ServerApplicationPaths. - private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService) + private static ServerApplicationPaths CreateApplicationPaths(string appDirectory) { - var resourcesPath = Path.GetDirectoryName(applicationPath); - - if (runAsService) - { - var systemPath = Path.GetDirectoryName(applicationPath); - - var programDataPath = Path.GetDirectoryName(systemPath); - - return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath); - } + var resourcesPath = appDirectory; - return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), applicationPath, resourcesPath); + return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(appDirectory), appDirectory, resourcesPath); } /// @@ -177,14 +145,7 @@ namespace Emby.Server { get { - if (_isRunningAsService) - { - return _canRestartService; - } - else - { - return true; - } + return true; } } @@ -196,14 +157,7 @@ namespace Emby.Server { get { - if (_isRunningAsService) - { - return _canRestartService; - } - else - { - return true; - } + return false; } } @@ -214,9 +168,8 @@ namespace Emby.Server /// /// The app paths. /// The log manager. - /// if set to true [run service]. /// The options. - private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options) + private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options) { var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), true, true, true); @@ -240,29 +193,19 @@ namespace Emby.Server var initProgress = new Progress(); - if (!runService) - { - // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes - SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | - ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX); - } + // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes + SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | + ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX); var task = _appHost.Init(initProgress); Task.WaitAll(task); task = task.ContinueWith(new Action(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); - if (runService) - { - StartService(logManager); - } - else - { - Task.WaitAll(task); + Task.WaitAll(task); - task = ApplicationTaskCompletionSource.Task; - Task.WaitAll(task); - } + task = ApplicationTaskCompletionSource.Task; + Task.WaitAll(task); } private static void GenerateCertificate(string certPath, string certHost) @@ -270,31 +213,6 @@ namespace Emby.Server //CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger); } - /// - /// Starts the service. - /// - private static void StartService(ILogManager logManager) - { - } - - /// - /// Handles the Disposed event of the service control. - /// - /// The source of the event. - /// The instance containing the event data. - static void service_Disposed(object sender, EventArgs e) - { - ApplicationTaskCompletionSource.SetResult(true); - OnServiceShutdown(); - } - - private static void OnServiceShutdown() - { - _logger.Info("Shutting down"); - - DisposeAppHost(); - } - /// /// Handles the UnhandledException event of the CurrentDomain control. /// @@ -306,10 +224,7 @@ namespace Emby.Server new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception); - if (!_isRunningAsService) - { - ShowMessageBox("Unhandled exception: " + exception.Message); - } + ShowMessageBox("Unhandled exception: " + exception.Message); if (!Debugger.IsAttached) { @@ -325,29 +240,6 @@ namespace Emby.Server /// true if XXXX, false otherwise private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger) { - // Look for the existence of an update archive - var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip"); - if (File.Exists(updateArchive)) - { - logger.Info("An update is available from {0}", updateArchive); - - // Update is there - execute update - try - { - //var serviceName = _isRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty; - //new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName); - - // And just let the app exit so it can update - return true; - } - catch (Exception e) - { - logger.ErrorException("Error starting updater.", e); - - ShowMessageBox(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message)); - } - } - return false; } @@ -358,37 +250,25 @@ namespace Emby.Server public static void Shutdown() { - if (_isRunningAsService) - { - ShutdownWindowsService(); - } - else - { - DisposeAppHost(); + DisposeAppHost(); - ShutdownWindowsApplication(); - } + //_logger.Info("Calling Application.Exit"); + //Application.Exit(); + + _logger.Info("Calling Environment.Exit"); + Environment.Exit(0); + + _logger.Info("Calling ApplicationTaskCompletionSource.SetResult"); + ApplicationTaskCompletionSource.SetResult(true); } public static void Restart() { DisposeAppHost(); - if (_isRunningAsService) - { - RestartWindowsService(); - } - else - { - //_logger.Info("Hiding server notify icon"); - //_serverNotifyIcon.Visible = false; + // todo: start new instance - _logger.Info("Starting new instance"); - //Application.Restart(); - Process.Start(_appHost.ServerConfigurationManager.ApplicationPaths.ApplicationPath); - - ShutdownWindowsApplication(); - } + Shutdown(); } private static void DisposeAppHost() @@ -402,31 +282,6 @@ namespace Emby.Server } } - private static void ShutdownWindowsApplication() - { - //_logger.Info("Calling Application.Exit"); - //Application.Exit(); - - _logger.Info("Calling Environment.Exit"); - Environment.Exit(0); - - _logger.Info("Calling ApplicationTaskCompletionSource.SetResult"); - ApplicationTaskCompletionSource.SetResult(true); - } - - private static void ShutdownWindowsService() - { - } - - private static void RestartWindowsService() - { - } - - private static bool CanRestartWindowsService() - { - return false; - } - /// /// Sets the error mode. /// diff --git a/src/Emby.Server/project.json b/src/Emby.Server/project.json index c64db844f..55acee514 100644 --- a/src/Emby.Server/project.json +++ b/src/Emby.Server/project.json @@ -12,10 +12,10 @@ "version": "1.0.1" }, "Mono.Nat": "1.0.0-*", - "Microsoft.Win32.Registry": "4.0.0", - "System.Runtime.Extensions": "4.1.0", - "System.Diagnostics.Process": "4.1.0", - "Microsoft.Data.SQLite": "1.0.0" + "Microsoft.Win32.Registry": "4.0.0", + "System.Runtime.Extensions": "4.1.0", + "System.Diagnostics.Process": "4.1.0", + "Microsoft.Data.SQLite": "1.1.0-preview1-final" }, "frameworks": { -- cgit v1.2.3 From 635c8d50a361dc2eabbeea0ae55048d1e9f4ad8f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 13 Nov 2016 22:44:54 -0500 Subject: update character escaping --- .../Channels/ChannelManager.cs | 17 +++++++++++++-- .../Security/MBLicenseFile.cs | 12 ++++++++--- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 10 ++++----- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- MediaBrowser.ServerApplication/WindowsAppHost.cs | 25 ++++++++++++++++++++-- 5 files changed, 52 insertions(+), 14 deletions(-) (limited to 'MediaBrowser.MediaEncoding/Encoder') diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 94ff7c342..0df916ded 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -1108,7 +1108,11 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - return _jsonSerializer.DeserializeFromFile(cachePath); + var cachedResult = _jsonSerializer.DeserializeFromFile(cachePath); + if (cachedResult != null) + { + return cachedResult; + } } } } @@ -1131,7 +1135,11 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - return _jsonSerializer.DeserializeFromFile(cachePath); + var cachedResult = _jsonSerializer.DeserializeFromFile(cachePath); + if (cachedResult != null) + { + return cachedResult; + } } } } @@ -1162,6 +1170,11 @@ namespace Emby.Server.Implementations.Channels var result = await channel.GetChannelItems(query, cancellationToken).ConfigureAwait(false); + if (result == null) + { + throw new InvalidOperationException("Channel returned a null result from GetChannelItems"); + } + if (!startIndex.HasValue && !limit.HasValue) { CacheResponse(result, cachePath); diff --git a/Emby.Server.Implementations/Security/MBLicenseFile.cs b/Emby.Server.Implementations/Security/MBLicenseFile.cs index 4b6a82b6c..76741bdf8 100644 --- a/Emby.Server.Implementations/Security/MBLicenseFile.cs +++ b/Emby.Server.Implementations/Security/MBLicenseFile.cs @@ -57,9 +57,14 @@ namespace Emby.Server.Implementations.Security _updateRecords.AddOrUpdate(key, value, (k, v) => value); } + private Guid GetKey(string featureId) + { + return new Guid(_cryptographyProvider.ComputeMD5(Encoding.Unicode.GetBytes(featureId))); + } + public void AddRegCheck(string featureId) { - var key = new Guid(_cryptographyProvider.ComputeMD5(Encoding.Unicode.GetBytes(featureId))); + var key = GetKey(featureId); var value = DateTime.UtcNow; SetUpdateRecord(key, value); @@ -68,7 +73,7 @@ namespace Emby.Server.Implementations.Security public void RemoveRegCheck(string featureId) { - var key = new Guid(_cryptographyProvider.ComputeMD5(Encoding.Unicode.GetBytes(featureId))); + var key = GetKey(featureId); DateTime val; _updateRecords.TryRemove(key, out val); @@ -78,8 +83,9 @@ namespace Emby.Server.Implementations.Security public DateTime LastChecked(string featureId) { + var key = GetKey(featureId); DateTime last; - _updateRecords.TryGetValue(new Guid(_cryptographyProvider.ComputeMD5(Encoding.Unicode.GetBytes(featureId))), out last); + _updateRecords.TryGetValue(key, out last); // guard agains people just putting a large number in the file return last < DateTime.UtcNow ? last : DateTime.MinValue; diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index bae367d82..a52ac0e60 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -88,8 +88,8 @@ namespace MediaBrowser.MediaEncoding.Encoder private readonly int DefaultImageExtractionTimeoutMs; private readonly bool EnableEncoderFontFile; - 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 subtitleEncoder, Func mediaSourceManager, IHttpClient httpClient, IZipClient zipClient, IMemoryStreamFactory memoryStreamProvider, IProcessFactory processFactory, - int defaultImageExtractionTimeoutMs, + 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 subtitleEncoder, Func mediaSourceManager, IHttpClient httpClient, IZipClient zipClient, IMemoryStreamFactory memoryStreamProvider, IProcessFactory processFactory, + int defaultImageExtractionTimeoutMs, bool enableEncoderFontFile) { _logger = logger; @@ -459,7 +459,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (request.AnalyzeDurationSections > 0) { analyzeDuration = "-analyzeduration " + - (request.AnalyzeDurationSections*1000000).ToString(CultureInfo.InvariantCulture); + (request.AnalyzeDurationSections * 1000000).ToString(CultureInfo.InvariantCulture); } else { @@ -1221,9 +1221,7 @@ namespace MediaBrowser.MediaEncoding.Encoder // https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping // We need to double escape - var escapeChars = new[] {':', '\'', ','}; - - return path.Replace('\\', '/').Replace(":/", "\\:/").Replace("'", "'\\\\\\''"); + return path.Replace('\\', '/').Replace(":", "\\:").Replace("'", "'\\\\\\''"); } /// diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 06a883c06..c11cfb523 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -976,7 +976,7 @@ namespace MediaBrowser.Model.Dlna if (item.Bitrate.Value > maxBitrate.Value) { - _logger.Info("Bitrate exceeds DirectPlay limit"); + _logger.Info("Bitrate exceeds DirectPlay limit: media bitrate: {0}, max bitrate: {1}", item.Bitrate.Value.ToString(CultureInfo.InvariantCulture), maxBitrate.Value.ToString(CultureInfo.InvariantCulture)); return false; } diff --git a/MediaBrowser.ServerApplication/WindowsAppHost.cs b/MediaBrowser.ServerApplication/WindowsAppHost.cs index d9bead6b7..fa18b5229 100644 --- a/MediaBrowser.ServerApplication/WindowsAppHost.cs +++ b/MediaBrowser.ServerApplication/WindowsAppHost.cs @@ -32,11 +32,32 @@ namespace MediaBrowser.ServerApplication info.FFMpegFilename = "ffmpeg.exe"; info.FFProbeFilename = "ffprobe.exe"; - info.Version = "0"; + info.Version = "20160410"; + info.ArchiveType = "7z"; + info.DownloadUrls = GetDownloadUrls(); return info; } + private string[] GetDownloadUrls() + { + switch (EnvironmentInfo.SystemArchitecture) + { + case Architecture.X64: + return new[] + { + "https://github.com/MediaBrowser/Emby.Resources/raw/master/ffmpeg/windows/ffmpeg-20160410-win64.7z" + }; + case Architecture.X86: + return new[] + { + "https://github.com/MediaBrowser/Emby.Resources/raw/master/ffmpeg/windows/ffmpeg-20160410-win32.7z" + }; + } + + return new string[] { }; + } + protected override void RestartInternal() { MainStartup.Restart(); @@ -80,7 +101,7 @@ namespace MediaBrowser.ServerApplication var shortcutPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.StartMenu), "Emby", "Emby Server.lnk"); var startupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup); - + if (autorun) { //Copy our shortut into the startup folder for this user -- cgit v1.2.3 From 9b5a4c22e33db6d2e4554a61c49d7f6bf3375e24 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 14 Nov 2016 01:44:21 -0500 Subject: update image & subtitle extraction --- .../Emby.Server.Implementations.csproj | 1 + .../EntryPoints/SystemEvents.cs | 47 +++++++++++++ MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 68 +++++++------------ .../Subtitles/SubtitleEncoder.cs | 76 ++-------------------- MediaBrowser.Model/System/ISystemEvents.cs | 2 + MediaBrowser.Server.Mono/Program.cs | 20 +----- MediaBrowser.Server.Startup.Common/SystemEvents.cs | 16 +++++ MediaBrowser.ServerApplication/MainStartup.cs | 14 ---- 8 files changed, 95 insertions(+), 149 deletions(-) create mode 100644 Emby.Server.Implementations/EntryPoints/SystemEvents.cs (limited to 'MediaBrowser.MediaEncoding/Encoder') diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 8f92f062c..13d184b59 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -59,6 +59,7 @@ + diff --git a/Emby.Server.Implementations/EntryPoints/SystemEvents.cs b/Emby.Server.Implementations/EntryPoints/SystemEvents.cs new file mode 100644 index 000000000..021ae47ec --- /dev/null +++ b/Emby.Server.Implementations/EntryPoints/SystemEvents.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MediaBrowser.Model.System; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Common; + +namespace Emby.Server.Implementations.EntryPoints +{ + public class SystemEvents : IServerEntryPoint + { + private readonly ISystemEvents _systemEvents; + private readonly IApplicationHost _appHost; + + public SystemEvents(ISystemEvents systemEvents, IApplicationHost appHost) + { + _systemEvents = systemEvents; + _appHost = appHost; + } + + public void Run() + { + _systemEvents.SessionLogoff += _systemEvents_SessionLogoff; + _systemEvents.SystemShutdown += _systemEvents_SystemShutdown; + } + + private void _systemEvents_SessionLogoff(object sender, EventArgs e) + { + if (!_appHost.IsRunningAsService) + { + _appHost.Shutdown(); + } + } + + private void _systemEvents_SystemShutdown(object sender, EventArgs e) + { + _appHost.Shutdown(); + } + + public void Dispose() + { + _systemEvents.SystemShutdown -= _systemEvents_SystemShutdown; + } + } +} diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index a52ac0e60..ba1f23dfe 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -542,8 +542,6 @@ namespace MediaBrowser.MediaEncoding.Encoder // Must consume both or ffmpeg may hang due to deadlocks. See comments below. RedirectStandardOutput = true, - //RedirectStandardError = true, - RedirectStandardInput = false, FileName = FFProbePath, Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(), @@ -554,7 +552,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - using (var processWrapper = new ProcessWrapper(process, this, _logger, false)) + using (var processWrapper = new ProcessWrapper(process, this, _logger)) { await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -616,7 +614,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - StopProcess(processWrapper, 100, true); + StopProcess(processWrapper, 100); throw; } @@ -671,9 +669,7 @@ namespace MediaBrowser.MediaEncoding.Encoder UseShellExecute = false, // Must consume both or ffmpeg may hang due to deadlocks. See comments below. - //RedirectStandardOutput = true, RedirectStandardError = true, - RedirectStandardInput = false, FileName = FFMpegPath, Arguments = string.Format(args, probeSizeArgument, inputPath, videoStream.Index.ToString(CultureInfo.InvariantCulture)).Trim(), @@ -685,7 +681,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); var idetFoundInterlaced = false; - using (var processWrapper = new ProcessWrapper(process, this, _logger, false)) + using (var processWrapper = new ProcessWrapper(process, this, _logger)) { try { @@ -728,7 +724,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - StopProcess(processWrapper, 100, true); + StopProcess(processWrapper, 100); throw; } @@ -945,7 +941,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - using (var processWrapper = new ProcessWrapper(process, this, _logger, false)) + using (var processWrapper = new ProcessWrapper(process, this, _logger)) { await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -965,7 +961,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (!ranToCompletion) { - StopProcess(processWrapper, 1000, false); + StopProcess(processWrapper, 1000); } } @@ -1043,8 +1039,7 @@ namespace MediaBrowser.MediaEncoding.Encoder FileName = FFMpegPath, Arguments = args, IsHidden = true, - ErrorDialog = false, - RedirectStandardInput = true + ErrorDialog = false }); _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments); @@ -1053,7 +1048,7 @@ namespace MediaBrowser.MediaEncoding.Encoder bool ranToCompletion = false; - using (var processWrapper = new ProcessWrapper(process, this, _logger, true)) + using (var processWrapper = new ProcessWrapper(process, this, _logger)) { try { @@ -1085,7 +1080,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (!ranToCompletion) { - StopProcess(processWrapper, 1000, false); + StopProcess(processWrapper, 1000); } } finally @@ -1157,40 +1152,25 @@ namespace MediaBrowser.MediaEncoding.Encoder _runningProcesses.Add(process); } } - private void StopProcess(ProcessWrapper process, int waitTimeMs, bool enableForceKill) + private void StopProcess(ProcessWrapper process, int waitTimeMs) { try { - _logger.Info("Killing ffmpeg process"); - - if (process.IsRedirectingStdin) + if (process.Process.WaitForExit(waitTimeMs)) { - try - { - process.Process.StandardInput.WriteLine("q"); - } - catch (Exception) - { - _logger.Error("Error sending q command to process"); - } + return; } + } + catch (Exception ex) + { + _logger.Error("Error in WaitForExit", ex); + } - try - { - if (process.Process.WaitForExit(waitTimeMs)) - { - return; - } - } - catch (Exception ex) - { - _logger.Error("Error in WaitForExit", ex); - } + try + { + _logger.Info("Killing ffmpeg process"); - if (enableForceKill) - { - process.Process.Kill(); - } + process.Process.Kill(); } catch (Exception ex) { @@ -1211,7 +1191,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (!process.HasExited) { - StopProcess(process, 500, true); + StopProcess(process, 500); } } } @@ -1252,15 +1232,13 @@ namespace MediaBrowser.MediaEncoding.Encoder public int? ExitCode; private readonly MediaEncoder _mediaEncoder; private readonly ILogger _logger; - public bool IsRedirectingStdin { get; private set; } - public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder, ILogger logger, bool isRedirectingStdin) + public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder, ILogger logger) { Process = process; _mediaEncoder = mediaEncoder; _logger = logger; Process.Exited += Process_Exited; - IsRedirectingStdin = isRedirectingStdin; } void Process_Exited(object sender, EventArgs e) diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 5d065f528..9b31a1012 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -444,10 +444,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles var process = _processFactory.Create(new ProcessOptions { - RedirectStandardOutput = false, - RedirectStandardError = true, - RedirectStandardInput = true, - CreateNoWindow = true, UseShellExecute = false, FileName = _mediaEncoder.EncoderPath, @@ -459,26 +455,16 @@ namespace MediaBrowser.MediaEncoding.Subtitles _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt"); - _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath)); - - var logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, - true); - try { process.Start(); } catch (Exception ex) { - logFileStream.Dispose(); - _logger.ErrorException("Error starting ffmpeg", ex); throw; } - - var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream); var ranToCompletion = process.WaitForExit(60000); @@ -488,19 +474,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles { _logger.Info("Killing ffmpeg subtitle conversion process"); - process.StandardInput.WriteLine("q"); - process.WaitForExit(1000); - - await logTask.ConfigureAwait(false); + process.Kill(); } catch (Exception ex) { _logger.ErrorException("Error killing subtitle conversion process", ex); } - finally - { - logFileStream.Dispose(); - } } var exitCode = ranToCompletion ? process.ExitCode : -1; @@ -533,13 +512,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (failed) { - var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath); + var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath); _logger.Error(msg); throw new Exception(msg); } await SetAssFont(outputPath).ConfigureAwait(false); + + _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath); } /// @@ -597,10 +578,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles CreateNoWindow = true, UseShellExecute = false, - RedirectStandardOutput = false, - RedirectStandardError = true, - RedirectStandardInput = true, - FileName = _mediaEncoder.EncoderPath, Arguments = processArgs, IsHidden = true, @@ -609,28 +586,17 @@ namespace MediaBrowser.MediaEncoding.Subtitles _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt"); - _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath)); - - var logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, - true); - try { process.Start(); } catch (Exception ex) { - logFileStream.Dispose(); - _logger.ErrorException("Error starting ffmpeg", ex); throw; } - // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback - Task.Run(() => StartStreamingLog(process.StandardError.BaseStream, logFileStream)); - var ranToCompletion = process.WaitForExit(300000); if (!ranToCompletion) @@ -639,17 +605,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles { _logger.Info("Killing ffmpeg subtitle extraction process"); - process.StandardInput.WriteLine("q"); - process.WaitForExit(1000); + process.Kill(); } catch (Exception ex) { _logger.ErrorException("Error killing subtitle extraction process", ex); } - finally - { - logFileStream.Dispose(); - } } var exitCode = ranToCompletion ? process.ExitCode : -1; @@ -702,33 +663,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - private async Task StartStreamingLog(Stream source, Stream target) - { - try - { - using (var reader = new StreamReader(source)) - { - while (!reader.EndOfStream) - { - var line = await reader.ReadLineAsync().ConfigureAwait(false); - - var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line); - - await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); - await target.FlushAsync().ConfigureAwait(false); - } - } - } - catch (ObjectDisposedException) - { - // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux - } - catch (Exception ex) - { - _logger.ErrorException("Error reading ffmpeg log", ex); - } - } - /// /// Sets the ass font. /// diff --git a/MediaBrowser.Model/System/ISystemEvents.cs b/MediaBrowser.Model/System/ISystemEvents.cs index c50f8ce03..dec8ed8c0 100644 --- a/MediaBrowser.Model/System/ISystemEvents.cs +++ b/MediaBrowser.Model/System/ISystemEvents.cs @@ -6,5 +6,7 @@ namespace MediaBrowser.Model.System { event EventHandler Resume; event EventHandler Suspend; + event EventHandler SessionLogoff; + event EventHandler SystemShutdown; } } diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 470525ece..7fc3ff22e 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -1,8 +1,6 @@ using MediaBrowser.Model.Logging; -using MediaBrowser.Server.Implementations; using MediaBrowser.Server.Mono.Native; using MediaBrowser.Server.Startup.Common; -using Microsoft.Win32; using System; using System.Diagnostics; using System.Globalization; @@ -14,7 +12,6 @@ using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; using Emby.Common.Implementations.EnvironmentInfo; -using Emby.Common.Implementations.IO; using Emby.Common.Implementations.Logging; using Emby.Common.Implementations.Networking; using Emby.Common.Implementations.Security; @@ -84,8 +81,6 @@ namespace MediaBrowser.Server.Mono private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options) { - Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding; - // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); @@ -108,7 +103,7 @@ namespace MediaBrowser.Server.Mono new MemoryStreamProvider(), new NetworkManager(logManager.GetLogger("NetworkManager")), GenerateCertificate, - () => Environment.UserDomainName); + () => Environment.UserName); if (options.ContainsOption("-v")) { @@ -219,19 +214,6 @@ namespace MediaBrowser.Server.Mono public string machine = string.Empty; } - /// - /// Handles the SessionEnding event of the SystemEvents control. - /// - /// The source of the event. - /// The instance containing the event data. - static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) - { - if (e.Reason == SessionEndReasons.SystemShutdown) - { - Shutdown(); - } - } - /// /// Handles the UnhandledException event of the CurrentDomain control. /// diff --git a/MediaBrowser.Server.Startup.Common/SystemEvents.cs b/MediaBrowser.Server.Startup.Common/SystemEvents.cs index 088d04a24..8d5cd4ad8 100644 --- a/MediaBrowser.Server.Startup.Common/SystemEvents.cs +++ b/MediaBrowser.Server.Startup.Common/SystemEvents.cs @@ -9,6 +9,8 @@ namespace MediaBrowser.Server.Startup.Common { public event EventHandler Resume; public event EventHandler Suspend; + public event EventHandler SessionLogoff; + public event EventHandler SystemShutdown; private readonly ILogger _logger; @@ -16,6 +18,20 @@ namespace MediaBrowser.Server.Startup.Common { _logger = logger; Microsoft.Win32.SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; + Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding; + } + + private void SystemEvents_SessionEnding(object sender, Microsoft.Win32.SessionEndingEventArgs e) + { + switch (e.Reason) + { + case Microsoft.Win32.SessionEndReasons.Logoff: + EventHelper.FireEventIfNotNull(SessionLogoff, this, EventArgs.Empty, _logger); + break; + case Microsoft.Win32.SessionEndReasons.SystemShutdown: + EventHelper.FireEventIfNotNull(SystemShutdown, this, EventArgs.Empty, _logger); + break; + } } private void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index c0ebcde74..f5e768133 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -368,7 +368,6 @@ namespace MediaBrowser.ServerApplication task = InstallVcredist2013IfNeeded(_appHost, _logger); Task.WaitAll(task); - Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding; Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; HideSplashScreen(); @@ -569,19 +568,6 @@ namespace MediaBrowser.ServerApplication } } - /// - /// Handles the SessionEnding event of the SystemEvents control. - /// - /// The source of the event. - /// The instance containing the event data. - static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) - { - if (e.Reason == SessionEndReasons.SystemShutdown || !IsRunningAsService) - { - Shutdown(); - } - } - /// /// Handles the UnhandledException event of the CurrentDomain control. /// -- cgit v1.2.3