From 818662e051a07b15a9ac15df177835d7e4ef236b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 28 Oct 2015 00:06:13 -0400 Subject: use ImageMagick scale method --- .../MediaBrowser.Common.Implementations.csproj | 6 +++--- MediaBrowser.Common.Implementations/packages.config | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index d857e58b6..8615d4f8b 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -53,7 +53,7 @@ False - ..\packages\NLog.4.1.1\lib\net45\NLog.dll + ..\packages\NLog.4.2.0\lib\net45\NLog.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll @@ -62,9 +62,9 @@ False ..\ThirdParty\SharpCompress\SharpCompress.dll - + False - ..\packages\SimpleInjector.3.0.5\lib\net45\SimpleInjector.dll + ..\packages\SimpleInjector.3.1.0\lib\net45\SimpleInjector.dll diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index a0711a9c7..769a7c4f6 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -1,7 +1,7 @@  - + - + -- cgit v1.2.3 From 9b998a068a2622f43ac813800654e357f94d0c21 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 28 Oct 2015 15:40:38 -0400 Subject: update image encoding --- Emby.Drawing/ImageMagick/ImageMagickEncoder.cs | 3 ++ MediaBrowser.Api/Movies/MoviesService.cs | 3 +- MediaBrowser.Api/TvShowsService.cs | 35 ++++++++----- .../Logging/NlogManager.cs | 2 +- .../Security/PluginSecurityManager.cs | 9 ++++ MediaBrowser.Common/MediaBrowser.Common.csproj | 1 + .../Security/PaymentRequiredException.cs | 8 +++ MediaBrowser.Controller/Entities/BaseItem.cs | 10 +++- .../Entities/InternalItemsQuery.cs | 11 ++++ MediaBrowser.Controller/Library/ILibraryManager.cs | 8 +++ .../LiveTv/LiveTvAudioRecording.cs | 1 - MediaBrowser.Controller/LiveTv/LiveTvProgram.cs | 35 +++++-------- .../LiveTv/LiveTvVideoRecording.cs | 1 - .../MediaBrowser.Controller.csproj | 1 + .../Net/PaymentRequiredException.cs | 15 ++++++ .../Providers/MetadataStatus.cs | 14 ----- MediaBrowser.Providers/Manager/MetadataService.cs | 22 +++++--- .../Dto/DtoService.cs | 8 ++- .../HttpServer/HttpListenerHost.cs | 4 +- .../HttpServer/LoggerUtils.cs | 5 +- .../SocketSharp/WebSocketSharpListener.cs | 10 +--- .../Library/LibraryManager.cs | 12 ++--- .../Library/SearchEngine.cs | 3 +- .../LiveTv/LiveTvManager.cs | 40 +++++++-------- .../Persistence/SqliteItemRepository.cs | 60 ++++++++++++++++++++-- .../Persistence/SqliteProviderInfoRepository.cs | 13 ++--- .../TV/TVSeriesManager.cs | 20 ++++++-- 27 files changed, 232 insertions(+), 122 deletions(-) create mode 100644 MediaBrowser.Common/Security/PaymentRequiredException.cs create mode 100644 MediaBrowser.Controller/Net/PaymentRequiredException.cs (limited to 'MediaBrowser.Common.Implementations') diff --git a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs index c5ba6d9c8..d097c8da3 100644 --- a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs @@ -136,6 +136,9 @@ namespace Emby.Drawing.ImageMagick public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options) { + // Even if the caller specified 100, don't use it because it takes forever + quality = Math.Min(quality, 99); + if (string.IsNullOrWhiteSpace(options.BackgroundColor) || !HasTransparency(inputPath)) { using (var originalImage = new MagickWand(inputPath)) diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs index fe8bae1a5..1681c6fc6 100644 --- a/MediaBrowser.Api/Movies/MoviesService.cs +++ b/MediaBrowser.Api/Movies/MoviesService.cs @@ -379,9 +379,10 @@ namespace MediaBrowser.Api.Movies { foreach (var name in names) { - var itemsWithActor = _libraryManager.GetItemIds(new InternalItemsQuery + var itemsWithActor = _libraryManager.GetItemIds(new InternalItemsQuery(user) { Person = name + }); var items = allMovies diff --git a/MediaBrowser.Api/TvShowsService.cs b/MediaBrowser.Api/TvShowsService.cs index 29a4a8bb5..19d12fe65 100644 --- a/MediaBrowser.Api/TvShowsService.cs +++ b/MediaBrowser.Api/TvShowsService.cs @@ -159,7 +159,7 @@ namespace MediaBrowser.Api [ApiMember(Name = "StartItemId", Description = "Optional. Skip through the list until a given item is found.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] public string StartItemId { get; set; } - + /// /// Skips over a given number of items within the results. Use for paging. /// @@ -273,21 +273,32 @@ namespace MediaBrowser.Api { var user = _userManager.GetUserById(request.UserId); - var items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager, request.ParentId, i => i is Episode); + var minPremiereDate = DateTime.Now.Date.AddDays(-1).ToUniversalTime(); + + IEnumerable items; + + if (string.IsNullOrWhiteSpace(request.ParentId)) + { + items = _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Episode).Name }, + SortBy = new[] { "PremiereDate", "SortName" }, + SortOrder = SortOrder.Ascending, + MinPremiereDate = minPremiereDate + + }, user); + } + else + { + items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager, request.ParentId, i => i is Episode && (i.PremiereDate ?? DateTime.MinValue) >= minPremiereDate); + } var itemsList = _libraryManager .Sort(items, user, new[] { "PremiereDate", "AirTime", "SortName" }, SortOrder.Ascending) .Cast() .ToList(); - var unairedEpisodes = itemsList.Where(i => i.IsUnaired).ToList(); - - var minPremiereDate = DateTime.Now.Date.AddDays(-1).ToUniversalTime(); - var previousEpisodes = itemsList.Where(i => !i.IsUnaired && (i.PremiereDate ?? DateTime.MinValue) >= minPremiereDate).ToList(); - - previousEpisodes.AddRange(unairedEpisodes); - - var pagedItems = ApplyPaging(previousEpisodes, request.StartIndex, request.Limit); + var pagedItems = ApplyPaging(itemsList, request.StartIndex, request.Limit); var options = GetDtoOptions(request); @@ -440,7 +451,7 @@ namespace MediaBrowser.Api } episodes = season.GetEpisodes(user); - } + } else if (request.Season.HasValue) { var series = _libraryManager.GetItemById(request.Id) as Series; @@ -495,7 +506,7 @@ namespace MediaBrowser.Api .ToList(); var pagedItems = ApplyPaging(returnList, request.StartIndex, request.Limit); - + var dtoOptions = GetDtoOptions(request); var dtos = _dtoService.GetBaseItemDtos(pagedItems, dtoOptions, user) diff --git a/MediaBrowser.Common.Implementations/Logging/NlogManager.cs b/MediaBrowser.Common.Implementations/Logging/NlogManager.cs index 391e7c212..1bbcccd88 100644 --- a/MediaBrowser.Common.Implementations/Logging/NlogManager.cs +++ b/MediaBrowser.Common.Implementations/Logging/NlogManager.cs @@ -110,7 +110,7 @@ namespace MediaBrowser.Common.Implementations.Logging var logFile = new FileTarget { FileName = path, - Layout = "${longdate} ${level} - ${logger}: ${message}" + Layout = "${longdate} ${level} ${logger}: ${message}" }; logFile.Name = "ApplicationLogFile"; diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index c17a637fe..7cc31ad7a 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -219,6 +219,10 @@ namespace MediaBrowser.Common.Implementations.Security { SupporterKey = reg.key; } + else + { + throw new PaymentRequiredException(); + } } } @@ -227,6 +231,11 @@ namespace MediaBrowser.Common.Implementations.Security SaveAppStoreInfo(parameters); throw; } + catch (PaymentRequiredException) + { + SaveAppStoreInfo(parameters); + throw; + } catch (Exception e) { _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index b2f62dd21..ccdb319fe 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -89,6 +89,7 @@ + diff --git a/MediaBrowser.Common/Security/PaymentRequiredException.cs b/MediaBrowser.Common/Security/PaymentRequiredException.cs new file mode 100644 index 000000000..27b3e6961 --- /dev/null +++ b/MediaBrowser.Common/Security/PaymentRequiredException.cs @@ -0,0 +1,8 @@ +using System; + +namespace MediaBrowser.Common.Security +{ + public class PaymentRequiredException : Exception + { + } +} diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 19d5576c6..fdf035e8d 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -24,6 +24,7 @@ using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Model.LiveTv; namespace MediaBrowser.Controller.Entities { @@ -134,6 +135,13 @@ namespace MediaBrowser.Controller.Entities [IgnoreDataMember] public bool? IsHD { get; set; } + /// + /// Gets or sets the audio. + /// + /// The audio. + [IgnoreDataMember] + public ProgramAudio? Audio { get; set; } + /// /// Return the id that should be used to key display prefs for this item. /// Default is based on the type for everything except actual generic folders. @@ -178,7 +186,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Id of the program. + /// If this content came from an external service, the id of the content on that service /// [IgnoreDataMember] public string ExternalId diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 785e2fd2b..786c96d36 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -75,6 +75,7 @@ namespace MediaBrowser.Controller.Entities public string[] Tags { get; set; } public string[] OfficialRatings { get; set; } + public DateTime? MinPremiereDate { get; set; } public DateTime? MinStartDate { get; set; } public DateTime? MaxStartDate { get; set; } public DateTime? MinEndDate { get; set; } @@ -121,5 +122,15 @@ namespace MediaBrowser.Controller.Entities ChannelIds = new string[] { }; ItemIds = new string[] { }; } + + public InternalItemsQuery(User user) + : this() + { + if (user != null) + { + var policy = user.Policy; + MaxParentalRating = policy.MaxParentalRating; + } + } } } diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index c7ab88524..96bb6e2b6 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -543,5 +543,13 @@ namespace MediaBrowser.Controller.Library /// Index of the image. /// Task. Task ConvertImageToLocal(IHasImages item, ItemImageInfo image, int imageIndex); + + /// + /// Gets the items. + /// + /// The query. + /// The user. + /// List<BaseItem>. + IEnumerable GetItems(InternalItemsQuery query, User user); } } \ No newline at end of file diff --git a/MediaBrowser.Controller/LiveTv/LiveTvAudioRecording.cs b/MediaBrowser.Controller/LiveTv/LiveTvAudioRecording.cs index 03c05ec69..dd6a53d45 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvAudioRecording.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvAudioRecording.cs @@ -36,7 +36,6 @@ namespace MediaBrowser.Controller.LiveTv public bool IsLive { get; set; } [IgnoreDataMember] public bool IsPremiere { get; set; } - public ProgramAudio? Audio { get; set; } /// /// Gets the user data key. diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index 96a3743d0..aa1a3b9c2 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -32,10 +32,11 @@ namespace MediaBrowser.Controller.LiveTv } /// - /// Gets or sets the type of the channel. + /// Gets or sets the name. /// - /// The type of the channel. - public ChannelType ChannelType { get; set; } + /// The name. + [IgnoreDataMember] + public string ServiceName { get; set; } /// /// The start date of the program, in UTC. @@ -43,18 +44,6 @@ namespace MediaBrowser.Controller.LiveTv [IgnoreDataMember] public DateTime StartDate { get; set; } - /// - /// Gets or sets the audio. - /// - /// The audio. - public ProgramAudio? Audio { get; set; } - - /// - /// Gets or sets the name of the service. - /// - /// The name of the service. - public string ServiceName { get; set; } - /// /// Gets or sets a value indicating whether this instance is repeat. /// @@ -145,14 +134,14 @@ namespace MediaBrowser.Controller.LiveTv } } - [IgnoreDataMember] - public override string MediaType - { - get - { - return ChannelType == ChannelType.TV ? Model.Entities.MediaType.Video : Model.Entities.MediaType.Audio; - } - } + //[IgnoreDataMember] + //public override string MediaType + //{ + // get + // { + // return ChannelType == ChannelType.TV ? Model.Entities.MediaType.Video : Model.Entities.MediaType.Audio; + // } + //} [IgnoreDataMember] public bool IsAiring diff --git a/MediaBrowser.Controller/LiveTv/LiveTvVideoRecording.cs b/MediaBrowser.Controller/LiveTv/LiveTvVideoRecording.cs index 77404cfe8..de8764e6d 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvVideoRecording.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvVideoRecording.cs @@ -36,7 +36,6 @@ namespace MediaBrowser.Controller.LiveTv public bool IsLive { get; set; } [IgnoreDataMember] public bool IsPremiere { get; set; } - public ProgramAudio? Audio { get; set; } /// /// Gets the user data key. diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index bcf4de2a2..600674114 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -248,6 +248,7 @@ + diff --git a/MediaBrowser.Controller/Net/PaymentRequiredException.cs b/MediaBrowser.Controller/Net/PaymentRequiredException.cs new file mode 100644 index 000000000..e09fe092e --- /dev/null +++ b/MediaBrowser.Controller/Net/PaymentRequiredException.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Net +{ + /// + /// Corresponds to a 402 response code + /// + public class PaymentRequiredException : Exception + { + } +} diff --git a/MediaBrowser.Controller/Providers/MetadataStatus.cs b/MediaBrowser.Controller/Providers/MetadataStatus.cs index 9b946aee2..654d72e2a 100644 --- a/MediaBrowser.Controller/Providers/MetadataStatus.cs +++ b/MediaBrowser.Controller/Providers/MetadataStatus.cs @@ -40,22 +40,8 @@ namespace MediaBrowser.Controller.Providers /// The date last images refresh. public DateTime? DateLastImagesRefresh { get; set; } - /// - /// Gets or sets the last result error message. - /// - /// The last result error message. - public string LastErrorMessage { get; set; } - public DateTime? ItemDateModified { get; set; } - public void AddStatus(string errorMessage) - { - if (string.IsNullOrEmpty(LastErrorMessage)) - { - LastErrorMessage = errorMessage; - } - } - public bool IsDirty { get; private set; } public void SetDateLastMetadataRefresh(DateTime? date) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 6860aeff3..a7f58e32b 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -99,7 +99,6 @@ namespace MediaBrowser.Providers.Manager var updateType = ItemUpdateType.None; var refreshResult = GetLastResult(item); - refreshResult.LastErrorMessage = string.Empty; var itemImageProvider = new ItemImageProvider(Logger, ProviderManager, ServerConfigurationManager, FileSystem); var localImagesFailed = false; @@ -119,7 +118,6 @@ namespace MediaBrowser.Providers.Manager { localImagesFailed = true; Logger.ErrorException("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name"); - refreshResult.AddStatus(ex.Message); } var metadataResult = new MetadataResult @@ -150,7 +148,6 @@ namespace MediaBrowser.Providers.Manager var result = await RefreshWithProviders(metadataResult, id, refreshOptions, providers, itemImageProvider, cancellationToken).ConfigureAwait(false); updateType = updateType | result.UpdateType; - refreshResult.AddStatus(result.ErrorMessage); if (result.Failures == 0) { refreshResult.SetDateLastMetadataRefresh(DateTime.UtcNow); @@ -172,7 +169,6 @@ namespace MediaBrowser.Providers.Manager var result = await itemImageProvider.RefreshImages(itemOfType, providers, refreshOptions, config, cancellationToken).ConfigureAwait(false); updateType = updateType | result.UpdateType; - refreshResult.AddStatus(result.ErrorMessage); if (result.Failures == 0) { refreshResult.SetDateLastImagesRefresh(DateTime.UtcNow); @@ -231,22 +227,32 @@ namespace MediaBrowser.Providers.Manager private DateTime GetLastRefreshDate(IHasMetadata item) { - if (item.DateLastRefreshed != default(DateTime)) + if (EnableDateLastRefreshed(item)) { return item.DateLastRefreshed; } + return item.DateLastSaved; + } + + private bool EnableDateLastRefreshed(IHasMetadata item) + { if (ServerConfigurationManager.Configuration.EnableDateLastRefresh) { - return item.DateLastRefreshed; + return true; + } + + if (item.DateLastRefreshed != default(DateTime)) + { + return true; } if (item is BoxSet || (item is IItemByName && !(item is MusicArtist))) { - return item.DateLastRefreshed; + return true; } - return item.DateLastSaved; + return false; } protected async Task SaveItem(MetadataResult result, ItemUpdateType reason, CancellationToken cancellationToken) diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 20e1eb543..fcda802f4 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -472,7 +472,7 @@ namespace MediaBrowser.Server.Implementations.Dto // These are just far too slow. // TODO: Disable for CollectionFolder - if (!(folder is UserRootFolder) && !(folder is UserView)) + if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is IChannelItem)) { SetSpecialCounts(folder, user, dto, fields, syncProgress); } @@ -1042,7 +1042,11 @@ namespace MediaBrowser.Server.Implementations.Dto dto.IsFolder = item.IsFolder; dto.MediaType = item.MediaType; dto.LocationType = item.LocationType; - dto.IsHD = item.IsHD; + if (item.IsHD.HasValue && item.IsHD.Value) + { + dto.IsHD = item.IsHD; + } + dto.Audio = item.Audio; dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode; dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage; diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index e8bb40ba1..6abfa0674 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -92,7 +92,9 @@ namespace MediaBrowser.Server.Implementations.HttpServer {typeof (FileNotFoundException), 404}, {typeof (DirectoryNotFoundException), 404}, {typeof (SecurityException), 401}, - {typeof (UnauthorizedAccessException), 500} + {typeof (PaymentRequiredException), 402}, + {typeof (UnauthorizedAccessException), 500}, + {typeof (ApplicationException), 500} }; HostConfig.Instance.DebugMode = true; diff --git a/MediaBrowser.Server.Implementations/HttpServer/LoggerUtils.cs b/MediaBrowser.Server.Implementations/HttpServer/LoggerUtils.cs index 02ce38ef1..fae702023 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/LoggerUtils.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/LoggerUtils.cs @@ -16,7 +16,10 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The duration. public static void LogResponse(ILogger logger, int statusCode, string url, string endPoint, TimeSpan duration) { - logger.Info("HTTP Response {0} to {1}. Time: {2}ms. {3}", statusCode, endPoint, Convert.ToInt32(duration.TotalMilliseconds).ToString(CultureInfo.InvariantCulture), url); + var durationMs = duration.TotalMilliseconds; + var logSuffix = durationMs >= 1000 ? "ms (slow)" : "ms"; + + logger.Info("HTTP Response {0} to {1}. Time: {2}{3}. {4}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url); } } } diff --git a/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs b/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs index f8178c115..9f80c8ac9 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs @@ -183,15 +183,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp /// The request. private static void LogRequest(ILogger logger, HttpListenerRequest request) { - var log = new StringBuilder(); - - var headers = string.Join(",", request.Headers.AllKeys.Where(i => !string.Equals(i, "cookie", StringComparison.OrdinalIgnoreCase) && !string.Equals(i, "Referer", StringComparison.OrdinalIgnoreCase)).Select(k => k + "=" + request.Headers[k])); - - log.AppendLine("Ip: " + request.RemoteEndPoint + ". Headers: " + headers); - - var type = request.IsWebSocketRequest ? "Web Socket" : "HTTP " + request.HttpMethod; - - logger.LogMultiline(type + " " + request.Url, LogSeverity.Info, log); + logger.Info("{0} {1}. UserAgent: {2}", (request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod), request.Url, request.UserAgent ?? string.Empty); } private void HandleError(Exception ex, HttpListenerContext context) diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 92acd08d1..daa3d8ad4 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -1280,6 +1280,11 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.GetItemIdsList(query); } + public IEnumerable GetItems(InternalItemsQuery query, User user) + { + return GetItemIds(query).Select(GetItemById).Where(i => i.IsVisibleStandalone(user)); + } + /// /// Gets the intros. /// @@ -1811,14 +1816,9 @@ namespace MediaBrowser.Server.Implementations.Library isNew = true; } - if (!item.UserId.HasValue) + if (!item.UserId.HasValue || !string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) { item.UserId = user.Id; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); - } - - if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) - { item.ViewType = viewType; await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs index d6aff1192..108a891e0 100644 --- a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs +++ b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs @@ -157,12 +157,11 @@ namespace MediaBrowser.Server.Implementations.Library AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name); - var mediaItems = _libraryManager.GetItems(new InternalItemsQuery + var mediaItems = _libraryManager.GetItems(new InternalItemsQuery(user) { NameContains = searchTerm, ExcludeItemTypes = excludeItemTypes.ToArray(), IncludeItemTypes = includeItemTypes.ToArray(), - MaxParentalRating = user == null ? null : user.Policy.MaxParentalRating, Limit = (query.Limit.HasValue ? (int?)(query.Limit.Value * 3) : null), }).Items; diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index edfca0d6c..d7c9edae3 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -607,6 +607,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var item = _libraryManager.GetItemById(id) as LiveTvProgram; var isNew = false; + var forceUpdate = false; if (item == null) { @@ -621,7 +622,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv }; } - item.ChannelType = channelType; + //item.ChannelType = channelType; + if (!string.Equals(item.ServiceName, serviceName, StringComparison.Ordinal)) + { + forceUpdate = true; + } item.ServiceName = serviceName; item.Audio = info.Audio; @@ -666,7 +671,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv { await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false); } - else if (string.IsNullOrWhiteSpace(info.Etag)) + else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag)) { await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false); } @@ -814,7 +819,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv public async Task> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken) { - var internalQuery = new InternalItemsQuery + var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId); + + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, MinEndDate = query.MinEndDate, @@ -832,11 +839,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv SortOrder = query.SortOrder ?? SortOrder.Ascending }; - var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId); if (user != null) { - internalQuery.MaxParentalRating = user.Policy.MaxParentalRating; - if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram)) { internalQuery.HasParentalRating = true; @@ -874,7 +878,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv public async Task> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken) { - var internalQuery = new InternalItemsQuery + var user = _userManager.GetUserById(query.UserId); + + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, IsAiring = query.IsAiring, @@ -895,11 +901,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } - var user = _userManager.GetUserById(query.UserId); if (user != null) { - internalQuery.MaxParentalRating = user.Policy.MaxParentalRating; - if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram)) { internalQuery.HasParentalRating = true; @@ -1037,6 +1040,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv { var internalProgram = GetInternalProgram(program.Id); + if (string.IsNullOrWhiteSpace(internalProgram.ServiceName)) + { + continue; + } + List timerList; if (!timers.TryGetValue(internalProgram.ServiceName, out timerList)) { @@ -1052,7 +1060,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } - var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, internalProgram.ExternalId, StringComparison.OrdinalIgnoreCase)); if (timer != null) @@ -1429,18 +1436,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv public void AddInfoToProgramDto(BaseItem item, BaseItemDto dto, bool addChannelInfo, User user = null) { var program = (LiveTvProgram)item; - var service = GetService(program); - - dto.Id = _tvDtoService.GetInternalProgramId(service.Name, program.ExternalId).ToString("N"); dto.StartDate = program.StartDate; dto.EpisodeTitle = program.EpisodeTitle; - dto.Audio = program.Audio; - if (program.IsHD.HasValue && program.IsHD.Value) - { - dto.IsHD = program.IsHD; - } if (program.IsRepeat) { dto.IsRepeat = program.IsRepeat; @@ -1499,7 +1498,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv var info = recording; - dto.Id = item.Id.ToString("N"); dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId) ? null : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N"); @@ -1508,8 +1506,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv dto.RecordingStatus = info.Status; dto.IsRepeat = info.IsRepeat; dto.EpisodeTitle = info.EpisodeTitle; - dto.Audio = info.Audio; - dto.IsHD = info.IsHD; dto.IsMovie = info.IsMovie; dto.IsSeries = info.IsSeries; dto.IsSports = info.IsSports; diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index 256b057d9..730632bb3 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -19,6 +19,7 @@ using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Channels; +using MediaBrowser.Model.LiveTv; namespace MediaBrowser.Server.Implementations.Persistence { @@ -76,7 +77,7 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _deleteStreamsCommand; private IDbCommand _saveStreamCommand; - private const int LatestSchemaVersion = 16; + private const int LatestSchemaVersion = 17; /// /// Initializes a new instance of the class. @@ -202,7 +203,9 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.AddColumn(_logger, "TypedBaseItems", "IsInMixedFolder", "BIT"); _connection.AddColumn(_logger, "TypedBaseItems", "LockedFields", "Text"); _connection.AddColumn(_logger, "TypedBaseItems", "Studios", "Text"); - + _connection.AddColumn(_logger, "TypedBaseItems", "Audio", "Text"); + _connection.AddColumn(_logger, "TypedBaseItems", "ExternalServiceId", "Text"); + PrepareStatements(); new MediaStreamColumns(_connection, _logger).AddColumns(); @@ -311,7 +314,10 @@ namespace MediaBrowser.Server.Implementations.Persistence "DateCreated", "DateModified", "guid", - "Genres" + "Genres", + "ParentId", + "Audio", + "ExternalServiceId" }; private readonly string[] _mediaStreamSaveColumns = @@ -403,7 +409,9 @@ namespace MediaBrowser.Server.Implementations.Persistence "DateLastSaved", "IsInMixedFolder", "LockedFields", - "Studios" + "Studios", + "Audio", + "ExternalServiceId" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -637,6 +645,25 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()); _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Studios.ToArray()); + if (item.Audio.HasValue) + { + _saveItemCommand.GetParameter(index++).Value = item.Audio.Value.ToString(); + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + + var tvItem = item as ILiveTvItem; + if (tvItem != null) + { + _saveItemCommand.GetParameter(index++).Value = tvItem.ServiceName; + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); @@ -940,6 +967,25 @@ namespace MediaBrowser.Server.Implementations.Persistence item.Genres = reader.GetString(40).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).ToList(); } + if (!reader.IsDBNull(41)) + { + item.ParentId = reader.GetGuid(41); + } + + if (!reader.IsDBNull(42)) + { + item.Audio = (ProgramAudio)Enum.Parse(typeof(ProgramAudio), reader.GetString(42), true); + } + + if (!reader.IsDBNull(43)) + { + var tvItem = item as ILiveTvItem; + if (tvItem != null) + { + item.ForcedSortName = reader.GetString(43); + } + } + return item; } @@ -1668,6 +1714,12 @@ namespace MediaBrowser.Server.Implementations.Persistence cmd.Parameters.Add(cmd, "@MinStartDate", DbType.Date).Value = query.MinStartDate.Value; } + if (query.MinPremiereDate.HasValue) + { + whereClauses.Add("PremiereDate>=@MinPremiereDate"); + cmd.Parameters.Add(cmd, "@MinPremiereDate", DbType.Date).Value = query.MinPremiereDate.Value; + } + if (query.MaxStartDate.HasValue) { whereClauses.Add("StartDate<=@MaxStartDate"); diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs index e7853b458..a63b93dc7 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteProviderInfoRepository.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.Persistence string[] queries = { - "create table if not exists MetadataStatus (ItemId GUID PRIMARY KEY, ItemName TEXT, ItemType TEXT, SeriesName TEXT, DateLastMetadataRefresh datetime, DateLastImagesRefresh datetime, LastErrorMessage TEXT, ItemDateModified DateTimeNull)", + "create table if not exists MetadataStatus (ItemId GUID PRIMARY KEY, ItemName TEXT, ItemType TEXT, SeriesName TEXT, DateLastMetadataRefresh datetime, DateLastImagesRefresh datetime, ItemDateModified DateTimeNull)", "create index if not exists idx_MetadataStatus on MetadataStatus(ItemId)", //pragmas @@ -71,7 +71,6 @@ namespace MediaBrowser.Server.Implementations.Persistence "SeriesName", "DateLastMetadataRefresh", "DateLastImagesRefresh", - "LastErrorMessage", "ItemDateModified" }; @@ -185,12 +184,7 @@ namespace MediaBrowser.Server.Implementations.Persistence if (!reader.IsDBNull(6)) { - result.LastErrorMessage = reader.GetString(6); - } - - if (!reader.IsDBNull(7)) - { - result.ItemDateModified = reader.GetDateTime(7).ToUniversalTime(); + result.ItemDateModified = reader.GetDateTime(6).ToUniversalTime(); } return result; @@ -219,8 +213,7 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveStatusCommand.GetParameter(3).Value = status.SeriesName; _saveStatusCommand.GetParameter(4).Value = status.DateLastMetadataRefresh; _saveStatusCommand.GetParameter(5).Value = status.DateLastImagesRefresh; - _saveStatusCommand.GetParameter(6).Value = status.LastErrorMessage; - _saveStatusCommand.GetParameter(7).Value = status.ItemDateModified; + _saveStatusCommand.GetParameter(6).Value = status.ItemDateModified; _saveStatusCommand.Transaction = transaction; diff --git a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs index f34b43e43..93ebd0a1c 100644 --- a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs +++ b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs @@ -36,8 +36,22 @@ namespace MediaBrowser.Server.Implementations.TV ? new string[] { } : new[] { request.ParentId }; - var items = GetAllLibraryItems(user, parentIds, i => i is Series) - .Cast(); + IEnumerable items; + + if (parentIds.Length == 0) + { + items = _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Series).Name }, + SortOrder = SortOrder.Ascending + + }, user).Cast(); + } + else + { + items = GetAllLibraryItems(user, parentIds, i => i is Series) + .Cast(); + } // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items); @@ -64,7 +78,7 @@ namespace MediaBrowser.Server.Implementations.TV return GetResult(episodes, null, request); } - private IEnumerable GetAllLibraryItems(User user, string[] parentIds, Func filter) + private IEnumerable GetAllLibraryItems(User user, string[] parentIds, Func filter) { if (parentIds.Length > 0) { -- cgit v1.2.3 From 0bd1f36ececc04c86bbf49b1ffd07dd30a5878b1 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 29 Oct 2015 09:28:05 -0400 Subject: update db queries --- MediaBrowser.Api/PluginService.cs | 6 +- MediaBrowser.Api/TvShowsService.cs | 34 ++--- .../Security/PluginSecurityManager.cs | 17 ++- .../Entities/AggregateFolder.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 21 ++- MediaBrowser.Controller/Entities/Folder.cs | 45 ++++-- .../Entities/InternalItemsQuery.cs | 6 +- MediaBrowser.Controller/Entities/Person.cs | 9 ++ MediaBrowser.Controller/Entities/TV/Episode.cs | 14 ++ MediaBrowser.Controller/Entities/UserView.cs | 15 ++ MediaBrowser.Controller/Library/ILibraryManager.cs | 12 +- MediaBrowser.Controller/LiveTv/LiveTvProgram.cs | 9 ++ .../Persistence/IItemRepository.cs | 7 + .../ContentDirectory/ControlHandler.cs | 24 ++-- .../Configuration/ServerConfiguration.cs | 9 +- .../Collections/CollectionManager.cs | 1 + .../Dto/DtoService.cs | 14 +- .../Intros/DefaultIntroProvider.cs | 8 +- .../Library/LibraryManager.cs | 58 +++++--- .../Library/MusicManager.cs | 8 +- .../Library/SearchEngine.cs | 27 +--- .../LiveTv/LiveTvManager.cs | 34 ++--- .../Persistence/CleanDatabaseScheduledTask.cs | 8 ++ .../Persistence/SqliteItemRepository.cs | 152 +++++++++++++++++++-- .../Playlists/PlaylistManager.cs | 1 + .../TV/TVSeriesManager.cs | 48 ++----- .../ApplicationHost.cs | 2 +- .../MediaBrowser.Server.Startup.Common.csproj | 2 +- .../Migrations/DbMigration.cs | 34 +++++ .../Migrations/Release5767.cs | 48 ------- 30 files changed, 431 insertions(+), 244 deletions(-) create mode 100644 MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs delete mode 100644 MediaBrowser.Server.Startup.Common/Migrations/Release5767.cs (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs index a7fd14bf0..74b37df92 100644 --- a/MediaBrowser.Api/PluginService.cs +++ b/MediaBrowser.Api/PluginService.cs @@ -278,9 +278,11 @@ namespace MediaBrowser.Api /// /// /// - public async Task Post(RegisterAppstoreSale request) + public void Post(RegisterAppstoreSale request) { - await _securityManager.RegisterAppStoreSale(request.Parameters); + var task = _securityManager.RegisterAppStoreSale(request.Parameters); + + Task.WaitAll(task); } /// diff --git a/MediaBrowser.Api/TvShowsService.cs b/MediaBrowser.Api/TvShowsService.cs index 19d12fe65..ead232888 100644 --- a/MediaBrowser.Api/TvShowsService.cs +++ b/MediaBrowser.Api/TvShowsService.cs @@ -275,38 +275,26 @@ namespace MediaBrowser.Api var minPremiereDate = DateTime.Now.Date.AddDays(-1).ToUniversalTime(); - IEnumerable items; + var parentIds = string.IsNullOrWhiteSpace(request.ParentId) ? new string[] { } : new[] { request.ParentId }; - if (string.IsNullOrWhiteSpace(request.ParentId)) + var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user) { - items = _libraryManager.GetItems(new InternalItemsQuery(user) - { - IncludeItemTypes = new[] { typeof(Episode).Name }, - SortBy = new[] { "PremiereDate", "SortName" }, - SortOrder = SortOrder.Ascending, - MinPremiereDate = minPremiereDate - - }, user); - } - else - { - items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager, request.ParentId, i => i is Episode && (i.PremiereDate ?? DateTime.MinValue) >= minPremiereDate); - } - - var itemsList = _libraryManager - .Sort(items, user, new[] { "PremiereDate", "AirTime", "SortName" }, SortOrder.Ascending) - .Cast() - .ToList(); + IncludeItemTypes = new[] { typeof(Episode).Name }, + SortBy = new[] { "PremiereDate", "AirTime", "SortName" }, + SortOrder = SortOrder.Ascending, + MinPremiereDate = minPremiereDate, + StartIndex = request.StartIndex, + Limit = request.Limit - var pagedItems = ApplyPaging(itemsList, request.StartIndex, request.Limit); + }, user, parentIds); var options = GetDtoOptions(request); - var returnItems = _dtoService.GetBaseItemDtos(pagedItems, options, user).ToArray(); + var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, options, user).ToArray(); var result = new ItemsResult { - TotalRecordCount = itemsList.Count, + TotalRecordCount = itemsResult.TotalRecordCount, Items = returnItems }; diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index 7cc31ad7a..1176407ce 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -8,8 +8,10 @@ using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.Net; namespace MediaBrowser.Common.Implementations.Security { @@ -219,10 +221,6 @@ namespace MediaBrowser.Common.Implementations.Security { SupporterKey = reg.key; } - else - { - throw new PaymentRequiredException(); - } } } @@ -231,10 +229,15 @@ namespace MediaBrowser.Common.Implementations.Security SaveAppStoreInfo(parameters); throw; } - catch (PaymentRequiredException) + catch (HttpException e) { - SaveAppStoreInfo(parameters); - throw; + _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + + if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired) + { + throw new PaymentRequiredException(); + } + throw new ApplicationException("Error registering store sale"); } catch (Exception e) { diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 14f8c1617..10372eb49 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -128,7 +128,7 @@ namespace MediaBrowser.Controller.Entities /// IEnumerable{BaseItem}. protected override IEnumerable GetNonCachedChildren(IDirectoryService directoryService) { - return base.GetNonCachedChildren(directoryService).Concat(_virtualChildren); + return base.GetNonCachedChildren(directoryService); } /// diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index fdf035e8d..f14e09616 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -639,7 +639,7 @@ namespace MediaBrowser.Controller.Entities /// /// The tags. public List Tags { get; set; } - + /// /// Gets or sets the home page URL. /// @@ -1898,5 +1898,24 @@ namespace MediaBrowser.Controller.Entities DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture) }; } + + public virtual IEnumerable GetAncestorIds() + { + return Parents.Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id)); + } + + [IgnoreDataMember] + public virtual bool SupportsAncestors + { + get + { + return true; + } + } + + public virtual IEnumerable GetIdsForAncestorQuery() + { + return new[] { Id }; + } } } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index fcbe54d05..e08eda1ac 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -149,7 +149,15 @@ namespace MediaBrowser.Controller.Entities await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false); - await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false); + if (!EnableNewFolderQuerying()) + { + await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false); + } + } + + private static bool EnableNewFolderQuerying() + { + return ConfigurationManager.Configuration.MigrationVersion >= 1; } protected void AddChildrenInternal(IEnumerable children) @@ -222,7 +230,12 @@ namespace MediaBrowser.Controller.Entities item.SetParent(null); - return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken); + if (!EnableNewFolderQuerying()) + { + return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken); + } + + return Task.FromResult(true); } /// @@ -471,6 +484,7 @@ namespace MediaBrowser.Controller.Entities } else { + child.SetParent(this); newItems.Add(child); validChildren.Add(child); } @@ -478,6 +492,7 @@ namespace MediaBrowser.Controller.Entities else { // Brand new item - needs to be added + child.SetParent(this); newItems.Add(child); validChildren.Add(child); } @@ -506,7 +521,6 @@ namespace MediaBrowser.Controller.Entities } else { - await UpdateIsOffline(item, false).ConfigureAwait(false); actualRemovals.Add(item); } } @@ -517,6 +531,9 @@ namespace MediaBrowser.Controller.Entities foreach (var item in actualRemovals) { + item.SetParent(null); + item.IsOffline = false; + await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false); LibraryManager.ReportItemRemoved(item); } } @@ -525,7 +542,10 @@ namespace MediaBrowser.Controller.Entities AddChildrenInternal(newItems); - await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false); + if (!EnableNewFolderQuerying()) + { + await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false); + } } } @@ -755,19 +775,16 @@ namespace MediaBrowser.Controller.Entities /// IEnumerable{BaseItem}. protected IEnumerable GetCachedChildren() { - if (ConfigurationManager.Configuration.DisableStartupScan) + if (EnableNewFolderQuerying()) { - return ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null); - //return ItemRepository.GetItems(new InternalItemsQuery - //{ - // ParentId = Id + return ItemRepository.GetItemList(new InternalItemsQuery + { + ParentId = Id - //}).Items.Select(RetrieveChild).Where(i => i != null); - } - else - { - return ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null); + }).Select(RetrieveChild).Where(i => i != null); } + + return ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null); } private BaseItem RetrieveChild(BaseItem child) diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 786c96d36..038a46316 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -102,7 +102,8 @@ namespace MediaBrowser.Controller.Entities public LocationType? LocationType { get; set; } public Guid? ParentId { get; set; } - + public string[] AncestorIds { get; set; } + public InternalItemsQuery() { Tags = new string[] { }; @@ -121,6 +122,7 @@ namespace MediaBrowser.Controller.Entities PersonIds = new string[] { }; ChannelIds = new string[] { }; ItemIds = new string[] { }; + AncestorIds = new string[] { }; } public InternalItemsQuery(User user) @@ -130,6 +132,8 @@ namespace MediaBrowser.Controller.Entities { var policy = user.Policy; MaxParentalRating = policy.MaxParentalRating; + + User = user; } } } diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index 6c277da56..120a376d4 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -101,6 +101,15 @@ namespace MediaBrowser.Controller.Entities return false; } } + + [IgnoreDataMember] + public override bool SupportsAncestors + { + get + { + return false; + } + } } /// diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 92ca9e970..3d18b86df 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -265,6 +265,20 @@ namespace MediaBrowser.Controller.Entities.TV } } + public override IEnumerable GetAncestorIds() + { + var list = base.GetAncestorIds().ToList(); + + var seasonId = SeasonId; + + if (seasonId.HasValue && !list.Contains(seasonId.Value)) + { + list.Add(seasonId.Value); + } + + return list; + } + public override IEnumerable GetDeletePaths() { return new[] { Path }; diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 5ee49ae5a..76188ce58 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -24,6 +24,21 @@ namespace MediaBrowser.Controller.Entities { return true; } + + public override IEnumerable GetIdsForAncestorQuery() + { + var list = new List(); + + if (DisplayParentId != Guid.Empty) + { + list.Add(DisplayParentId); + } + else if (ParentId != Guid.Empty) + { + list.Add(ParentId); + } + return list; + } public override Task> GetItems(InternalItemsQuery query) { diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 96bb6e2b6..c24cf9bce 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -549,7 +549,17 @@ namespace MediaBrowser.Controller.Library /// /// The query. /// The user. + /// The parent ids. /// List<BaseItem>. - IEnumerable GetItems(InternalItemsQuery query, User user); + IEnumerable GetItems(InternalItemsQuery query, User user, IEnumerable parentIds); + + /// + /// Gets the items result. + /// + /// The query. + /// The user. + /// The parent ids. + /// QueryResult<BaseItem>. + QueryResult GetItemsResult(InternalItemsQuery query, User user, IEnumerable parentIds); } } \ No newline at end of file diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index aa1a3b9c2..55bc2269e 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -217,5 +217,14 @@ namespace MediaBrowser.Controller.LiveTv return base.SupportsPeople; } } + + [IgnoreDataMember] + public override bool SupportsAncestors + { + get + { + return false; + } + } } } diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs index 8fc0aedd3..0b1c9c3e0 100644 --- a/MediaBrowser.Controller/Persistence/IItemRepository.cs +++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs @@ -176,6 +176,13 @@ namespace MediaBrowser.Controller.Persistence /// The query. /// QueryResult<Tuple<Guid, System.String>>. QueryResult> GetItemIdsWithPath(InternalItemsQuery query); + + /// + /// Gets the item list. + /// + /// The query. + /// List<BaseItem>. + IEnumerable GetItemList(InternalItemsQuery query); } } diff --git a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs index a9ce5587d..ba50f2f32 100644 --- a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs +++ b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs @@ -481,23 +481,17 @@ namespace MediaBrowser.Dlna.ContentDirectory private QueryResult GetItemsFromPerson(Person person, User user, int? startIndex, int? limit) { - var itemsWithPerson = _libraryManager.GetItems(new InternalItemsQuery + var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user) { - Person = person.Name - - }).Items; - - var items = itemsWithPerson - .Where(i => i is Movie || i is Series || i is IChannelItem) - .Where(i => i.IsVisibleStandalone(user)) - .ToList(); + Person = person.Name, + IncludeItemTypes = new[] { typeof(Movie).Name, typeof(Series).Name, typeof(ChannelVideoItem).Name }, + SortBy = new[] { ItemSortBy.SortName }, + Limit = limit, + StartIndex = startIndex - items = _libraryManager.Sort(items, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending) - .Skip(startIndex ?? 0) - .Take(limit ?? int.MaxValue) - .ToList(); + }, user, new string[] { }); - var serverItems = items.Select(i => new ServerItem + var serverItems = itemsResult.Items.Select(i => new ServerItem { Item = i, StubType = null @@ -506,7 +500,7 @@ namespace MediaBrowser.Dlna.ContentDirectory return new QueryResult { - TotalRecordCount = serverItems.Length, + TotalRecordCount = itemsResult.TotalRecordCount, Items = serverItems }; } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index e4c4e4762..ec024e87c 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -67,7 +67,7 @@ namespace MediaBrowser.Model.Configuration /// /// true if [enable high quality image scaling]; otherwise, false. public bool EnableHighQualityImageScaling { get; set; } - + /// /// Gets or sets the item by name path. /// @@ -234,12 +234,14 @@ namespace MediaBrowser.Model.Configuration public string[] Migrations { get; set; } + public int MigrationVersion { get; set; } + /// /// Initializes a new instance of the class. /// public ServerConfiguration() { - Migrations = new string[] {}; + Migrations = new string[] { }; ImageSavingConvention = ImageSavingConvention.Compatible; PublicPort = 8096; @@ -583,7 +585,8 @@ namespace MediaBrowser.Model.Configuration Limit = 0, Type = ImageType.Thumb } - } + }, + DisabledMetadataFetchers = new []{ "TheMovieDb" } } }; } diff --git a/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs b/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs index 5c98e401f..4e742ca7a 100644 --- a/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs +++ b/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs @@ -40,6 +40,7 @@ namespace MediaBrowser.Server.Implementations.Collections public Folder GetCollectionsFolder(string userId) { return _libraryManager.RootFolder.Children.OfType() + .FirstOrDefault() ?? _libraryManager.GetUserRootFolder().Children.OfType() .FirstOrDefault(); } diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index fcda802f4..8439f28f7 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -163,16 +163,11 @@ namespace MediaBrowser.Server.Implementations.Dto if (person != null) { - var items = _libraryManager.GetItems(new InternalItemsQuery + var items = _libraryManager.GetItems(new InternalItemsQuery(user) { Person = byName.Name - }).Items; - - if (user != null) - { - return items.Where(i => i.IsVisibleStandalone(user)).ToList(); - } + }, user, new string[] { }); return items.ToList(); } @@ -471,8 +466,7 @@ namespace MediaBrowser.Server.Implementations.Dto dto.ChildCount = GetChildCount(folder, user); // These are just far too slow. - // TODO: Disable for CollectionFolder - if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is IChannelItem)) + if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is IChannelItem) && !(folder is ICollectionFolder)) { SetSpecialCounts(folder, user, dto, fields, syncProgress); } @@ -1524,7 +1518,7 @@ namespace MediaBrowser.Server.Implementations.Dto } dto.ChannelId = item.ChannelId; - + var channelItem = item as IChannelItem; if (channelItem != null) { diff --git a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs index ec94e16db..6310b61d1 100644 --- a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs +++ b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs @@ -83,13 +83,11 @@ namespace MediaBrowser.Server.Implementations.Intros if (config.EnableIntrosFromMoviesInLibrary) { - var inputItems = _libraryManager.GetItems(new InternalItemsQuery + var inputItems = _libraryManager.GetItems(new InternalItemsQuery(user) { - IncludeItemTypes = new[] { typeof(Movie).Name }, + IncludeItemTypes = new[] { typeof(Movie).Name } - User = user - - }).Items; + }, user, new string[]{}); var itemsWithTrailers = inputItems .Where(i => diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index daa3d8ad4..522038b46 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -401,12 +401,12 @@ namespace MediaBrowser.Server.Implementations.Library { foreach (var path in item.GetDeletePaths().ToList()) { - if (_fileSystem.DirectoryExists(path)) + if (_fileSystem.DirectoryExists(path)) { _logger.Debug("Deleting path {0}", path); _fileSystem.DeleteDirectory(path, true); } - else if (_fileSystem.FileExists(path)) + else if (_fileSystem.FileExists(path)) { _logger.Debug("Deleting path {0}", path); _fileSystem.DeleteFile(path); @@ -697,7 +697,7 @@ namespace MediaBrowser.Server.Implementations.Library { var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath; - _fileSystem.CreateDirectory(rootFolderPath); + _fileSystem.CreateDirectory(rootFolderPath); var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)); @@ -727,6 +727,13 @@ namespace MediaBrowser.Server.Implementations.Library folder = dbItem; } + //if (folder.ParentId != rootFolder.Id) + //{ + // folder.ParentId = rootFolder.Id; + // var task = folder.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None); + // Task.WaitAll(task); + //} + rootFolder.AddVirtualChild(folder); RegisterItem(folder); @@ -748,7 +755,7 @@ namespace MediaBrowser.Server.Implementations.Library { var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; - _fileSystem.CreateDirectory(userRootPath); + _fileSystem.CreateDirectory(userRootPath); var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder; @@ -1000,9 +1007,9 @@ namespace MediaBrowser.Server.Implementations.Library private void SetPropertiesFromSongs(MusicArtist artist, IEnumerable items) { - + } - + /// /// Validate and refresh the People sub-set of the IBN. /// The items are stored in the db but not loaded into memory until actually requested by an operation. @@ -1013,7 +1020,7 @@ namespace MediaBrowser.Server.Implementations.Library public Task ValidatePeople(CancellationToken cancellationToken, IProgress progress) { // Ensure the location is available. - _fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath); + _fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath); return new PeopleValidator(this, _logger, ConfigurationManager, _fileSystem).ValidatePeople(cancellationToken, progress); } @@ -1280,9 +1287,29 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.GetItemIdsList(query); } - public IEnumerable GetItems(InternalItemsQuery query, User user) + public IEnumerable GetItems(InternalItemsQuery query, User user, IEnumerable parentIds) { - return GetItemIds(query).Select(GetItemById).Where(i => i.IsVisibleStandalone(user)); + var parents = parentIds.Select(i => GetItemById(new Guid(i))).ToList(); + + query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).Select(i => i.ToString("N")).ToArray(); + + var items = GetItemIds(query).Select(GetItemById); + + if (user != null) + { + items = items.Where(i => i.IsVisibleStandalone(user)); + } + + return items; + } + + public QueryResult GetItemsResult(InternalItemsQuery query, User user, IEnumerable parentIds) + { + var parents = parentIds.Select(i => GetItemById(new Guid(i))).ToList(); + + query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).Select(i => i.ToString("N")).ToArray(); + + return GetItems(query); } /// @@ -1700,7 +1727,7 @@ namespace MediaBrowser.Server.Implementations.Library if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -1719,8 +1746,7 @@ namespace MediaBrowser.Server.Implementations.Library if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) { - item.ViewType = viewType; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); + refresh = true; } if (!refresh) @@ -1793,7 +1819,7 @@ namespace MediaBrowser.Server.Implementations.Library if (item == null) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -1917,7 +1943,7 @@ namespace MediaBrowser.Server.Implementations.Library return item; } - + public async Task GetNamedView(string name, string parentId, string viewType, @@ -1946,7 +1972,7 @@ namespace MediaBrowser.Server.Implementations.Library if (item == null) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -2379,7 +2405,7 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.UpdatePeople(item.Id, people); } - private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1,1); + private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1, 1); public async Task ConvertImageToLocal(IHasImages item, ItemImageInfo image, int imageIndex) { _logger.Debug("ConvertImageToLocal item {0}", item.Id); diff --git a/MediaBrowser.Server.Implementations/Library/MusicManager.cs b/MediaBrowser.Server.Implementations/Library/MusicManager.cs index aee101ef4..3d2286e1f 100644 --- a/MediaBrowser.Server.Implementations/Library/MusicManager.cs +++ b/MediaBrowser.Server.Implementations/Library/MusicManager.cs @@ -80,15 +80,13 @@ namespace MediaBrowser.Server.Implementations.Library { var genreList = genres.ToList(); - var inputItems = _libraryManager.GetItems(new InternalItemsQuery + var inputItems = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(Audio).Name }, - Genres = genreList.ToArray(), + Genres = genreList.ToArray() - User = user - - }).Items; + }, user, new string[] { }); var genresDictionary = genreList.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); diff --git a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs index 108a891e0..82e0f92e6 100644 --- a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs +++ b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs @@ -156,18 +156,18 @@ namespace MediaBrowser.Server.Implementations.Library } AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name); - + var mediaItems = _libraryManager.GetItems(new InternalItemsQuery(user) { NameContains = searchTerm, ExcludeItemTypes = excludeItemTypes.ToArray(), IncludeItemTypes = includeItemTypes.ToArray(), - Limit = (query.Limit.HasValue ? (int?)(query.Limit.Value * 3) : null), + Limit = (query.Limit.HasValue ? (int?)(query.Limit.Value * 2) : null), - }).Items; + }, user, new string[] { }); // Add search hints based on item name - hints.AddRange(mediaItems.Where(i => IncludeInSearch(i) && IsVisible(i, user)).Select(item => + hints.AddRange(mediaItems.Where(IncludeInSearch).Select(item => { var index = GetIndex(item.Name, searchTerm, terms); @@ -183,25 +183,6 @@ namespace MediaBrowser.Server.Implementations.Library return Task.FromResult(returnValue); } - private bool IsVisible(BaseItem item, User user) - { - if (user == null) - { - return true; - } - - if (item is IItemByName) - { - var dual = item as IHasDualAccess; - if (dual == null || dual.IsAccessedByName) - { - return true; - } - } - - return item.IsVisibleStandalone(user); - } - private bool IncludeInSearch(BaseItem item) { var episode = item as Episode; diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index d7c9edae3..1b8966aa0 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1357,7 +1357,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv await RefreshRecordings(cancellationToken).ConfigureAwait(false); - var internalQuery = new InternalItemsQuery + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name } }; @@ -1367,8 +1367,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv internalQuery.ChannelIds = new[] { query.ChannelId }; } - var queryResult = _libraryManager.GetItems(internalQuery); - IEnumerable recordings = queryResult.Items.Cast(); + var queryResult = _libraryManager.GetItems(internalQuery, user, new string[]{}); + IEnumerable recordings = queryResult.Cast(); if (!string.IsNullOrEmpty(query.Id)) { @@ -1405,12 +1405,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid); } - if (user != null) - { - var currentUser = user; - recordings = recordings.Where(i => i.IsParentalAllowed(currentUser)); - } - recordings = recordings.OrderByDescending(i => i.StartDate); var entityList = recordings.ToList(); @@ -1771,19 +1765,18 @@ namespace MediaBrowser.Server.Implementations.LiveTv var now = DateTime.UtcNow; - var programs = _libraryManager.GetItems(new InternalItemsQuery + var programs = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, ChannelIds = new[] { id }, MaxStartDate = now, MinEndDate = now, - Limit = 1 + Limit = 1, + SortBy = new[] { "StartDate"} - }).Items.Cast(); + }, user, new string[]{}).Cast(); - var currentProgram = programs - .OrderBy(i => i.StartDate) - .FirstOrDefault(); + var currentProgram = programs.FirstOrDefault(); var dto = _tvDtoService.GetChannelInfoDto(channel, new DtoOptions(), currentProgram, user); @@ -1796,19 +1789,18 @@ namespace MediaBrowser.Server.Implementations.LiveTv var now = DateTime.UtcNow; - var programs = _libraryManager.GetItems(new InternalItemsQuery + var programs = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, ChannelIds = new[] { channel.Id.ToString("N") }, MaxStartDate = now, MinEndDate = now, - Limit = 1 + Limit = 1, + SortBy = new[] { "StartDate" } - }).Items.Cast(); + }, user, new string []{}).Cast(); - var currentProgram = programs - .OrderBy(i => i.StartDate) - .FirstOrDefault(); + var currentProgram = programs.FirstOrDefault(); if (currentProgram != null) { diff --git a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs index 60b8c00bd..74688d9b1 100644 --- a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs +++ b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs @@ -24,6 +24,8 @@ namespace MediaBrowser.Server.Implementations.Persistence private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; + public const int MigrationVersion = 1; + public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem) { _libraryManager = libraryManager; @@ -121,6 +123,12 @@ namespace MediaBrowser.Server.Implementations.Persistence _config.SaveConfiguration(); } + if (_config.Configuration.MigrationVersion < MigrationVersion) + { + _config.Configuration.MigrationVersion = MigrationVersion; + _config.SaveConfiguration(); + } + progress.Report(100); } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index 167c96185..20d890d02 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -77,7 +77,10 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _deleteStreamsCommand; private IDbCommand _saveStreamCommand; - private const int LatestSchemaVersion = 17; + private IDbCommand _deleteAncestorsCommand; + private IDbCommand _saveAncestorCommand; + + private const int LatestSchemaVersion = 18; /// /// Initializes a new instance of the class. @@ -126,9 +129,13 @@ namespace MediaBrowser.Server.Implementations.Persistence string[] queries = { - "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)", + "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB, ParentId GUID)", "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)", + "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)", + "create table if not exists AncestorIds (ItemId GUID, AncestorId GUID, PRIMARY KEY (ItemId, AncestorId))", + "create index if not exists idx_AncestorIds on AncestorIds(ItemId,AncestorId)", + "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))", "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)", @@ -205,6 +212,7 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.AddColumn(_logger, "TypedBaseItems", "Studios", "Text"); _connection.AddColumn(_logger, "TypedBaseItems", "Audio", "Text"); _connection.AddColumn(_logger, "TypedBaseItems", "ExternalServiceId", "Text"); + _connection.AddColumn(_logger, "TypedBaseItems", "Tags", "Text"); PrepareStatements(); @@ -429,7 +437,8 @@ namespace MediaBrowser.Server.Implementations.Persistence "LockedFields", "Studios", "Audio", - "ExternalServiceId" + "ExternalServiceId", + "Tags" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -472,6 +481,16 @@ namespace MediaBrowser.Server.Implementations.Persistence _savePersonCommand.Parameters.Add(_savePersonCommand, "@PersonType"); _savePersonCommand.Parameters.Add(_savePersonCommand, "@SortOrder"); _savePersonCommand.Parameters.Add(_savePersonCommand, "@ListOrder"); + + // Ancestors + _deleteAncestorsCommand = _connection.CreateCommand(); + _deleteAncestorsCommand.CommandText = "delete from AncestorIds where ItemId=@Id"; + _deleteAncestorsCommand.Parameters.Add(_deleteAncestorsCommand, "@Id"); + + _saveAncestorCommand = _connection.CreateCommand(); + _saveAncestorCommand.CommandText = "insert into AncestorIds (ItemId, AncestorId) values (@ItemId, @AncestorId)"; + _saveAncestorCommand.Parameters.Add(_saveAncestorCommand, "@ItemId"); + _saveAncestorCommand.Parameters.Add(_saveAncestorCommand, "@AncestorId"); // Chapters _deleteChaptersCommand = _connection.CreateCommand(); @@ -682,9 +701,16 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemCommand.GetParameter(index++).Value = null; } + _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Tags.ToArray()); + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); + + if (item.SupportsAncestors) + { + UpdateAncestors(item.Id, item.GetAncestorIds().Distinct().ToList(), transaction); + } } transaction.Commit(); @@ -765,22 +791,32 @@ namespace MediaBrowser.Server.Implementations.Persistence return null; } - BaseItem item; + BaseItem item = null; using (var stream = reader.GetMemoryStream(1)) { try { item = _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem; + } + catch (SerializationException ex) + { + _logger.ErrorException("Error deserializing item", ex); + } - if (item == null) + if (item == null) + { + try + { + item = Activator.CreateInstance(type) as BaseItem; + } + catch { - return null; } } - catch (SerializationException ex) + + if (item == null) { - _logger.ErrorException("Error deserializing item", ex); return null; } } @@ -1328,6 +1364,8 @@ namespace MediaBrowser.Server.Implementations.Persistence cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId; + //_logger.Debug(cmd.CommandText); + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) { while (reader.Read()) @@ -1373,6 +1411,50 @@ namespace MediaBrowser.Server.Implementations.Persistence } } + public IEnumerable GetItemList(InternalItemsQuery query) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + CheckDisposed(); + + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems"; + + var whereClauses = GetWhereClauses(query, cmd, true); + + var whereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + cmd.CommandText += whereText; + + cmd.CommandText += GetOrderByText(query); + + if (query.Limit.HasValue) + { + cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture); + } + + //_logger.Debug(cmd.CommandText); + + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) + { + while (reader.Read()) + { + var item = GetItem(reader); + if (item != null) + { + yield return item; + } + } + } + } + } + public QueryResult GetItems(InternalItemsQuery query) { if (query == null) @@ -1453,6 +1535,12 @@ namespace MediaBrowser.Server.Implementations.Persistence private string MapOrderByField(string name) { + if (string.Equals(name, "airtime", StringComparison.OrdinalIgnoreCase)) + { + // TODO + return "SortName"; + } + return name; } @@ -1813,6 +1901,17 @@ namespace MediaBrowser.Server.Implementations.Persistence } } + if (query.AncestorIds.Length == 1) + { + whereClauses.Add("Guid in (select itemId from AncestorIds where AncestorId=@AncestorId)"); + cmd.Parameters.Add(cmd, "@AncestorId", DbType.Guid).Value = new Guid(query.AncestorIds[0]); + } + if (query.AncestorIds.Length > 1) + { + var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + i + "'").ToArray()); + whereClauses.Add(string.Format("Guid in (select itemId from AncestorIds where AncestorId in ({0}))", inClause)); + } + if (addPaging) { if (query.StartIndex.HasValue && query.StartIndex.Value > 0) @@ -1847,6 +1946,7 @@ namespace MediaBrowser.Server.Implementations.Persistence typeof(Movie), typeof(BoxSet), typeof(Episode), + typeof(ChannelVideoItem), typeof(Season), typeof(Series), typeof(Book), @@ -1933,6 +2033,11 @@ namespace MediaBrowser.Server.Implementations.Persistence _deleteStreamsCommand.GetParameter(0).Value = id; _deleteStreamsCommand.Transaction = transaction; _deleteStreamsCommand.ExecuteNonQuery(); + + // Delete ancestors + _deleteAncestorsCommand.GetParameter(0).Value = id; + _deleteAncestorsCommand.Transaction = transaction; + _deleteAncestorsCommand.ExecuteNonQuery(); // Delete the item _deleteItemCommand.GetParameter(0).Value = id; @@ -2167,6 +2272,37 @@ namespace MediaBrowser.Server.Implementations.Persistence return whereClauses; } + private void UpdateAncestors(Guid itemId, List ancestorIds, IDbTransaction transaction) + { + if (itemId == Guid.Empty) + { + throw new ArgumentNullException("itemId"); + } + + if (ancestorIds == null) + { + throw new ArgumentNullException("ancestorIds"); + } + + CheckDisposed(); + + // First delete + _deleteAncestorsCommand.GetParameter(0).Value = itemId; + _deleteAncestorsCommand.Transaction = transaction; + + _deleteAncestorsCommand.ExecuteNonQuery(); + + foreach (var ancestorId in ancestorIds) + { + _saveAncestorCommand.GetParameter(0).Value = itemId; + _saveAncestorCommand.GetParameter(1).Value = ancestorId; + + _saveAncestorCommand.Transaction = transaction; + + _saveAncestorCommand.ExecuteNonQuery(); + } + } + public async Task UpdatePeople(Guid itemId, List people) { if (itemId == Guid.Empty) diff --git a/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs b/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs index d9b3ed755..048e2bf8d 100644 --- a/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs +++ b/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs @@ -264,6 +264,7 @@ namespace MediaBrowser.Server.Implementations.Playlists public Folder GetPlaylistsFolder(string userId) { return _libraryManager.RootFolder.Children.OfType() + .FirstOrDefault() ?? _libraryManager.GetUserRootFolder().Children.OfType() .FirstOrDefault(); } } diff --git a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs index 93ebd0a1c..d913360f0 100644 --- a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs +++ b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs @@ -36,22 +36,12 @@ namespace MediaBrowser.Server.Implementations.TV ? new string[] { } : new[] { request.ParentId }; - IEnumerable items; - - if (parentIds.Length == 0) + var items = _libraryManager.GetItems(new InternalItemsQuery(user) { - items = _libraryManager.GetItems(new InternalItemsQuery(user) - { - IncludeItemTypes = new[] { typeof(Series).Name }, - SortOrder = SortOrder.Ascending + IncludeItemTypes = new[] { typeof(Series).Name }, + SortOrder = SortOrder.Ascending - }, user).Cast(); - } - else - { - items = GetAllLibraryItems(user, parentIds, i => i is Series) - .Cast(); - } + }, user, parentIds).Cast(); // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items); @@ -68,9 +58,12 @@ namespace MediaBrowser.Server.Implementations.TV throw new ArgumentException("User not found"); } - var items = parentsFolders - .SelectMany(i => i.GetRecursiveChildren(user, s => s is Series)) - .Cast(); + var items = _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Series).Name }, + SortOrder = SortOrder.Ascending + + }, user, parentsFolders.Select(i => i.Id.ToString("N"))).Cast(); // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items); @@ -78,27 +71,6 @@ namespace MediaBrowser.Server.Implementations.TV return GetResult(episodes, null, request); } - private IEnumerable GetAllLibraryItems(User user, string[] parentIds, Func filter) - { - if (parentIds.Length > 0) - { - return parentIds.SelectMany(i => - { - var folder = (Folder)_libraryManager.GetItemById(new Guid(i)); - - return folder.GetRecursiveChildren(user, filter); - - }); - } - - if (user == null) - { - throw new ArgumentException("User not found"); - } - - return user.RootFolder.GetRecursiveChildren(user, filter); - } - public IEnumerable GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable series) { // Avoid implicitly captured closure diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 97a457a1b..694bd1b79 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -363,7 +363,7 @@ namespace MediaBrowser.Server.Startup.Common { var migrations = new List { - new Release5767(ServerConfigurationManager, TaskManager) + new DbMigration(ServerConfigurationManager, TaskManager) }; foreach (var task in migrations) diff --git a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj index 13b782e40..b58646a2e 100644 --- a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj +++ b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj @@ -72,7 +72,7 @@ - + diff --git a/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs new file mode 100644 index 000000000..de7cba68d --- /dev/null +++ b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs @@ -0,0 +1,34 @@ +using System.Threading.Tasks; +using MediaBrowser.Common.ScheduledTasks; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Server.Implementations.Persistence; + +namespace MediaBrowser.Server.Startup.Common.Migrations +{ + public class DbMigration : IVersionMigration + { + private readonly IServerConfigurationManager _config; + private readonly ITaskManager _taskManager; + + public DbMigration(IServerConfigurationManager config, ITaskManager taskManager) + { + _config = config; + _taskManager = taskManager; + } + + public void Run() + { + if (_config.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion) + { + return; + } + + Task.Run(async () => + { + await Task.Delay(2000).ConfigureAwait(false); + + _taskManager.QueueScheduledTask(); + }); + } + } +} diff --git a/MediaBrowser.Server.Startup.Common/Migrations/Release5767.cs b/MediaBrowser.Server.Startup.Common/Migrations/Release5767.cs deleted file mode 100644 index 168230b87..000000000 --- a/MediaBrowser.Server.Startup.Common/Migrations/Release5767.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using MediaBrowser.Common.ScheduledTasks; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Server.Implementations.LiveTv; -using MediaBrowser.Server.Implementations.Persistence; -using MediaBrowser.Server.Implementations.ScheduledTasks; - -namespace MediaBrowser.Server.Startup.Common.Migrations -{ - public class Release5767 : IVersionMigration - { - private readonly IServerConfigurationManager _config; - private readonly ITaskManager _taskManager; - - public Release5767(IServerConfigurationManager config, ITaskManager taskManager) - { - _config = config; - _taskManager = taskManager; - } - - public async void Run() - { - var name = "5767.1"; - - if (_config.Configuration.Migrations.Contains(name, StringComparer.OrdinalIgnoreCase)) - { - return; - } - - Task.Run(async () => - { - await Task.Delay(3000).ConfigureAwait(false); - - _taskManager.QueueScheduledTask(); - }); - - // Wait a few minutes before marking this as done. Make sure the server doesn't get restarted. - await Task.Delay(300000).ConfigureAwait(false); - - var list = _config.Configuration.Migrations.ToList(); - list.Add(name); - _config.Configuration.Migrations = list.ToArray(); - _config.SaveConfiguration(); - } - } -} -- cgit v1.2.3 From f6c8e5b4d6a8b3d1643482d2c89bae9176e45025 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 2 Nov 2015 14:29:40 -0500 Subject: update httplistener --- .../HttpClientManager/HttpClientManager.cs | 13 ------ MediaBrowser.Controller/Entities/UserView.cs | 2 +- .../Folders/DefaultImageProvider.cs | 2 +- .../Manager/ItemImageProvider.cs | 5 +++ .../LiveTv/LiveTvManager.cs | 50 ++++++++++++---------- .../MediaBrowser.Server.Implementations.csproj | 4 +- .../packages.config | 2 +- 7 files changed, 38 insertions(+), 40 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs index f4d4826eb..5908cd800 100644 --- a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs +++ b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs @@ -164,22 +164,9 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager } } - //request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback; - return request; } - private static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) - { - // Prefer local ipv4 - if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6) - { - return new IPEndPoint(IPAddress.IPv6Any, 0); - } - - return new IPEndPoint(IPAddress.Any, 0); - } - private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options) { foreach (var header in options.RequestHeaders.ToList()) diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 4e3b58778..c5b65f5a8 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -141,7 +141,7 @@ namespace MediaBrowser.Controller.Entities public static bool IsEligibleForEnhancedView(string viewType) { - var types = new[] { CollectionType.Movies, CollectionType.TvShows, CollectionType.Music }; + var types = new[] { CollectionType.Movies, CollectionType.TvShows }; return types.Contains(viewType ?? string.Empty, StringComparer.OrdinalIgnoreCase); } diff --git a/MediaBrowser.Providers/Folders/DefaultImageProvider.cs b/MediaBrowser.Providers/Folders/DefaultImageProvider.cs index 270867f90..74db70652 100644 --- a/MediaBrowser.Providers/Folders/DefaultImageProvider.cs +++ b/MediaBrowser.Providers/Folders/DefaultImageProvider.cs @@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.Folders } if (string.Equals(viewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase)) { - return urlPrefix + "generic.png"; + //return urlPrefix + "generic.png"; } if (string.Equals(viewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index 838306e13..f13fb2613 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -505,6 +505,11 @@ namespace MediaBrowser.Providers.Manager return true; } + if (!item.IsSaveLocalMetadataEnabled()) + { + return true; + } + return false; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index f872817cf..db8ccd9af 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -564,8 +564,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv item.ServiceName = serviceName; item.Number = channelInfo.Number; - var replaceImages = new List(); - //if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase)) //{ // isNew = true; @@ -577,13 +575,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv // replaceImages.Add(ImageType.Primary); //} - if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath)) - { - item.SetImagePath(ImageType.Primary, channelInfo.ImagePath); - } - else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl)) + if (!item.HasImage(ImageType.Primary)) { - item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl); + if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath)) + { + item.SetImagePath(ImageType.Primary, channelInfo.ImagePath); + } + else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl)) + { + item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl); + } } if (string.IsNullOrEmpty(item.Name)) @@ -593,8 +594,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) { - ForceSave = isNew, - ReplaceImages = replaceImages.Distinct().ToList() + ForceSave = isNew }, cancellationToken); @@ -658,13 +658,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv item.IndexNumber = info.EpisodeNumber; item.ParentIndexNumber = info.SeasonNumber; - if (!string.IsNullOrWhiteSpace(info.ImagePath)) + if (!item.HasImage(ImageType.Primary)) { - item.SetImagePath(ImageType.Primary, info.ImagePath); - } - else if (!string.IsNullOrWhiteSpace(info.ImageUrl)) - { - item.SetImagePath(ImageType.Primary, info.ImageUrl); + if (!string.IsNullOrWhiteSpace(info.ImagePath)) + { + item.SetImagePath(ImageType.Primary, info.ImagePath); + } + else if (!string.IsNullOrWhiteSpace(info.ImageUrl)) + { + item.SetImagePath(ImageType.Primary, info.ImageUrl); + } } if (isNew) @@ -761,13 +764,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv } recording.IsSeries = info.IsSeries; - if (!string.IsNullOrWhiteSpace(info.ImagePath)) - { - item.SetImagePath(ImageType.Primary, info.ImagePath); - } - else if (!string.IsNullOrWhiteSpace(info.ImageUrl)) + if (!item.HasImage(ImageType.Primary)) { - item.SetImagePath(ImageType.Primary, info.ImageUrl); + if (!string.IsNullOrWhiteSpace(info.ImagePath)) + { + item.SetImagePath(ImageType.Primary, info.ImagePath); + } + else if (!string.IsNullOrWhiteSpace(info.ImageUrl)) + { + item.SetImagePath(ImageType.Primary, info.ImageUrl); + } } var statusChanged = info.Status != recording.Status; diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 99ef3f1f2..24bc42024 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -58,9 +58,9 @@ ..\ThirdParty\ServiceStack\ServiceStack.Api.Swagger.dll - + False - ..\packages\SocketHttpListener.1.0.0.10\lib\net45\SocketHttpListener.dll + ..\packages\SocketHttpListener.1.0.0.13\lib\net45\SocketHttpListener.dll diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index 22206997f..603c86333 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -6,5 +6,5 @@ - + \ No newline at end of file -- cgit v1.2.3 From 8e41918ac5880b2b72c676ac550011fd854ff0a1 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 12 Nov 2015 14:19:30 -0500 Subject: update local network detection --- .../Networking/BaseNetworkManager.cs | 54 +++++++++++++++------- 1 file changed, 37 insertions(+), 17 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index c27dfd68d..9b5fa726c 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -84,7 +84,15 @@ namespace MediaBrowser.Common.Implementations.Networking return true; } - private bool IsInPrivateAddressSpace(string endpoint) + private bool IsInPrivateAddressSpaceIpv6(string endpoint) + { + return + + // If url was requested with computer name, we may see this + string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase); + } + + private bool IsInPrivateAddressSpaceIpv4(string endpoint) { // Private address space: // http://en.wikipedia.org/wiki/Private_network @@ -96,9 +104,6 @@ namespace MediaBrowser.Common.Implementations.Networking return - // If url was requested with computer name, we may see this - endpoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 || - endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) || endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) || endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) || @@ -131,25 +136,40 @@ namespace MediaBrowser.Common.Implementations.Networking throw new ArgumentNullException("endpoint"); } - if (IsInPrivateAddressSpace(endpoint)) - { - return true; - } - - const int lengthMatch = 4; - - if (endpoint.Length >= lengthMatch) + IPAddress address; + if (IPAddress.TryParse(endpoint, out address)) { - var prefix = endpoint.Substring(0, lengthMatch); + int lengthMatch = 100; + if (address.AddressFamily == AddressFamily.InterNetwork) + { + lengthMatch = 4; + if (IsInPrivateAddressSpaceIpv4(endpoint)) + { + return true; + } + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + lengthMatch = 10; + if (IsInPrivateAddressSpaceIpv6(endpoint)) + { + return true; + } + } - if (GetLocalIpAddresses() - .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + // Should be even be doing this with ipv6? + if (endpoint.Length >= lengthMatch) { - return true; + var prefix = endpoint.Substring(0, lengthMatch); + + if (GetLocalIpAddresses() + .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + { + return true; + } } } - IPAddress address; if (resolveHost && !IPAddress.TryParse(endpoint, out address)) { Uri uri; -- cgit v1.2.3 From 578fc7be143528dc53f79fd941551b00e3214b00 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 13 Nov 2015 15:48:21 -0500 Subject: use DateTime.TryParse --- .../Security/PluginSecurityManager.cs | 28 ++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index 1176407ce..d4fa74a86 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -178,11 +178,35 @@ namespace MediaBrowser.Common.Implementations.Security Email = response.email, PlanType = response.planType, SupporterKey = response.supporterKey, - ExpirationDate = string.IsNullOrWhiteSpace(response.expDate) ? (DateTime?)null : DateTime.Parse(response.expDate), - RegistrationDate = DateTime.Parse(response.regDate), IsActiveSupporter = IsMBSupporter }; + if (!string.IsNullOrWhiteSpace(response.expDate)) + { + DateTime parsedDate; + if (DateTime.TryParse(response.expDate, out parsedDate)) + { + info.ExpirationDate = parsedDate; + } + else + { + _logger.Error("Failed to parse expDate: {0}", response.expDate); + } + } + + if (!string.IsNullOrWhiteSpace(response.regDate)) + { + DateTime parsedDate; + if (DateTime.TryParse(response.regDate, out parsedDate)) + { + info.RegistrationDate = parsedDate; + } + else + { + _logger.Error("Failed to parse regDate: {0}", response.regDate); + } + } + info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey); return info; -- cgit v1.2.3 From b992659f24f8b86c5d3b28fab09f213fc6a7c19f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 13 Nov 2015 23:19:05 -0500 Subject: fix recording icons --- .../Networking/BaseNetworkManager.cs | 13 ++++--- .../LiveTv/LiveTvManager.cs | 44 ++++++++++++---------- .../Persistence/SqliteItemRepository.cs | 2 +- 3 files changed, 33 insertions(+), 26 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 9b5fa726c..834bac67d 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -139,11 +139,13 @@ namespace MediaBrowser.Common.Implementations.Networking IPAddress address; if (IPAddress.TryParse(endpoint, out address)) { + var addressString = address.ToString(); + int lengthMatch = 100; if (address.AddressFamily == AddressFamily.InterNetwork) { lengthMatch = 4; - if (IsInPrivateAddressSpaceIpv4(endpoint)) + if (IsInPrivateAddressSpaceIpv4(addressString)) { return true; } @@ -158,9 +160,9 @@ namespace MediaBrowser.Common.Implementations.Networking } // Should be even be doing this with ipv6? - if (endpoint.Length >= lengthMatch) + if (addressString.Length >= lengthMatch) { - var prefix = endpoint.Substring(0, lengthMatch); + var prefix = addressString.Substring(0, lengthMatch); if (GetLocalIpAddresses() .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) @@ -168,9 +170,8 @@ namespace MediaBrowser.Common.Implementations.Networking return true; } } - } - - if (resolveHost && !IPAddress.TryParse(endpoint, out address)) + } + else if (resolveHost) { Uri uri; if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri)) diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 8bf066887..af349ae12 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -565,7 +565,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv isNew = true; } item.ParentId = parentFolderId; - + item.ChannelType = channelInfo.ChannelType; item.ServiceName = serviceName; item.Number = channelInfo.Number; @@ -633,7 +633,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv forceUpdate = true; } item.ParentId = channel.Id; - + //item.ChannelType = channelType; if (!string.Equals(item.ServiceName, serviceName, StringComparison.Ordinal)) { @@ -781,7 +781,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv dataChanged = true; } item.ParentId = parentFolderId; - + if (!item.HasImage(ImageType.Primary)) { if (!string.IsNullOrWhiteSpace(info.ImagePath)) @@ -847,7 +847,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user); - await AddRecordingInfo(new[] { dto }, cancellationToken).ConfigureAwait(false); + var list = new List>(); + list.Add(new Tuple(dto, program.ServiceName, program.ExternalId)); + + await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false); return dto; } @@ -889,14 +892,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv var queryResult = _libraryManager.QueryItems(internalQuery); var returnArray = queryResult.Items - .Select(i => _dtoService.GetBaseItemDto(i, options, user)) + .Cast() + .Select(i => new Tuple(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId)) .ToArray(); await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false); var result = new QueryResult { - Items = returnArray, + Items = returnArray.Select(i => i.Item1).ToArray(), TotalRecordCount = queryResult.TotalRecordCount }; @@ -968,14 +972,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv var user = _userManager.GetUserById(query.UserId); var returnArray = internalResult.Items - .Select(i => _dtoService.GetBaseItemDto(i, options, user)) + .Select(i => new Tuple(_dtoService.GetBaseItemDto(i, options, user), i.ServiceName, i.ExternalId)) .ToArray(); await AddRecordingInfo(returnArray, cancellationToken).ConfigureAwait(false); var result = new QueryResult { - Items = returnArray, + Items = returnArray.Select(i => i.Item1).ToArray(), TotalRecordCount = internalResult.TotalRecordCount }; @@ -1051,44 +1055,46 @@ namespace MediaBrowser.Server.Implementations.LiveTv }).Sum(); } - private async Task AddRecordingInfo(IEnumerable programs, CancellationToken cancellationToken) + private async Task AddRecordingInfo(IEnumerable> programs, CancellationToken cancellationToken) { var timers = new Dictionary>(); - foreach (var program in programs) + foreach (var programTuple in programs) { - var internalProgram = GetInternalProgram(program.Id); + var program = programTuple.Item1; + var serviceName = programTuple.Item2; + var externalProgramId = programTuple.Item3; - if (string.IsNullOrWhiteSpace(internalProgram.ServiceName)) + if (string.IsNullOrWhiteSpace(serviceName)) { continue; } List timerList; - if (!timers.TryGetValue(internalProgram.ServiceName, out timerList)) + if (!timers.TryGetValue(serviceName, out timerList)) { try { - var tempTimers = await GetService(internalProgram.ServiceName).GetTimersAsync(cancellationToken).ConfigureAwait(false); - timers[internalProgram.ServiceName] = timerList = tempTimers.ToList(); + var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false); + timers[serviceName] = timerList = tempTimers.ToList(); } catch (Exception ex) { _logger.ErrorException("Error getting timer infos", ex); - timers[internalProgram.ServiceName] = timerList = new List(); + timers[serviceName] = timerList = new List(); } } - var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, internalProgram.ExternalId, StringComparison.OrdinalIgnoreCase)); + var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase)); if (timer != null) { - program.TimerId = _tvDtoService.GetInternalTimerId(internalProgram.ServiceName, timer.Id) + program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id) .ToString("N"); if (!string.IsNullOrEmpty(timer.SeriesTimerId)) { - program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(internalProgram.ServiceName, timer.SeriesTimerId) + program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId) .ToString("N"); } } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index cea45daa5..bf95fa612 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -1059,7 +1059,7 @@ namespace MediaBrowser.Server.Implementations.Persistence var tvItem = item as ILiveTvItem; if (tvItem != null) { - item.ForcedSortName = reader.GetString(43); + tvItem.ServiceName = reader.GetString(43); } } -- cgit v1.2.3 From 252dde1722dd66c23272d44f9940182e2cda7720 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 18 Nov 2015 21:35:08 -0500 Subject: update components --- .../Networking/BaseNetworkManager.cs | 18 +++++++++--------- MediaBrowser.ServerApplication/MainStartup.cs | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 834bac67d..703fec68d 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -84,16 +84,16 @@ namespace MediaBrowser.Common.Implementations.Networking return true; } - private bool IsInPrivateAddressSpaceIpv6(string endpoint) + private bool IsInPrivateAddressSpace(string endpoint) { - return + if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase)) + { + return true; + } - // If url was requested with computer name, we may see this - string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase); - } + // Handle ipv4 mapped to ipv6 + endpoint = endpoint.Replace("::ffff:", string.Empty); - private bool IsInPrivateAddressSpaceIpv4(string endpoint) - { // Private address space: // http://en.wikipedia.org/wiki/Private_network @@ -145,7 +145,7 @@ namespace MediaBrowser.Common.Implementations.Networking if (address.AddressFamily == AddressFamily.InterNetwork) { lengthMatch = 4; - if (IsInPrivateAddressSpaceIpv4(addressString)) + if (IsInPrivateAddressSpace(addressString)) { return true; } @@ -153,7 +153,7 @@ namespace MediaBrowser.Common.Implementations.Networking else if (address.AddressFamily == AddressFamily.InterNetworkV6) { lengthMatch = 10; - if (IsInPrivateAddressSpaceIpv6(endpoint)) + if (IsInPrivateAddressSpace(endpoint)) { return true; } diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index e6cb875a8..1032b1716 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -140,7 +140,7 @@ namespace MediaBrowser.ServerApplication if (!duplicate.WaitForExit(10000)) { _logger.Info("The duplicate process did not exit."); - //return true; + return true; } } -- cgit v1.2.3 From 625a089737af2aecc4025777242bfda8ee47c5bb Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 20 Nov 2015 12:55:38 -0500 Subject: update image provider --- .../ScheduledTasks/Tasks/DeleteCacheFileTask.cs | 9 ++++++++- .../Configuration/ServerConfiguration.cs | 1 - MediaBrowser.Providers/Manager/ItemImageProvider.cs | 18 ++++++++++++++++-- 3 files changed, 24 insertions(+), 4 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index 0e50f9315..a3636ac2e 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -128,7 +128,14 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks DeleteEmptyFolders(directory); if (!_fileSystem.GetFileSystemEntryPaths(directory).Any()) { - _fileSystem.DeleteDirectory(directory, false); + try + { + _fileSystem.DeleteDirectory(directory, false); + } + catch (IOException ex) + { + _logger.ErrorException("Error deleting directory {0}", ex, directory); + } } } } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index faee0785b..e7a111620 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -222,7 +222,6 @@ namespace MediaBrowser.Model.Configuration public string[] Migrations { get; set; } public int MigrationVersion { get; set; } - public bool EnableImagePreDownloading { get; set; } /// /// Initializes a new instance of the class. diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index fcb208a05..a4710bec4 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -516,11 +516,25 @@ namespace MediaBrowser.Providers.Manager var hasDualAccess = item as IHasDualAccess; if (hasDualAccess == null || hasDualAccess.IsAccessedByName) { - return !_config.Configuration.EnableImagePreDownloading; + return true; } } - return false; + switch (type) + { + case ImageType.Primary: + return false; + case ImageType.Thumb: + return false; + case ImageType.Logo: + return false; + case ImageType.Backdrop: + return false; + case ImageType.Screenshot: + return false; + default: + return true; + } } private void SaveImageStub(IHasImages item, ImageType imageType, string url) -- cgit v1.2.3 From c4fa6a28dbc67c26b8b387ac7675c619a6600859 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 20 Nov 2015 19:12:44 -0500 Subject: update components --- MediaBrowser.Api/StartupWizardService.cs | 1 - .../Configuration/BaseConfigurationManager.cs | 6 +----- MediaBrowser.Controller/Entities/BaseItem.cs | 5 +---- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 6 ------ MediaBrowser.Providers/Manager/MetadataService.cs | 2 +- MediaBrowser.WebDashboard/Api/DashboardService.cs | 1 - .../MediaBrowser.WebDashboard.csproj | 15 --------------- 7 files changed, 3 insertions(+), 33 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs index 3c907a996..365a9bfa8 100644 --- a/MediaBrowser.Api/StartupWizardService.cs +++ b/MediaBrowser.Api/StartupWizardService.cs @@ -68,7 +68,6 @@ namespace MediaBrowser.Api _config.Configuration.EnableLocalizedGuids = true; _config.Configuration.MergeMetadataAndImagesByName = true; _config.Configuration.EnableStandaloneMetadata = true; - _config.Configuration.EnableLibraryMetadataSubFolder = true; _config.Configuration.EnableCustomPathSubFolders = true; _config.Configuration.EnableDateLastRefresh = true; _config.SaveConfiguration(); diff --git a/MediaBrowser.Common.Implementations/Configuration/BaseConfigurationManager.cs b/MediaBrowser.Common.Implementations/Configuration/BaseConfigurationManager.cs index 7bbc1abd7..7f9299ff2 100644 --- a/MediaBrowser.Common.Implementations/Configuration/BaseConfigurationManager.cs +++ b/MediaBrowser.Common.Implementations/Configuration/BaseConfigurationManager.cs @@ -174,13 +174,9 @@ namespace MediaBrowser.Common.Implementations.Configuration { cachePath = null; } - else if (CommonConfiguration.EnableCustomPathSubFolders) - { - cachePath = Path.Combine(CommonConfiguration.CachePath, "cache"); - } else { - cachePath = CommonConfiguration.CachePath; + cachePath = Path.Combine(CommonConfiguration.CachePath, "cache"); } ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath; diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 8713fb347..a29d9395c 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -458,10 +458,7 @@ namespace MediaBrowser.Controller.Entities { var idString = Id.ToString("N"); - if (ConfigurationManager.Configuration.EnableLibraryMetadataSubFolder) - { - basePath = System.IO.Path.Combine(basePath, "library"); - } + basePath = System.IO.Path.Combine(basePath, "library"); return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString); } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index e7a111620..5666a32be 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -98,12 +98,6 @@ namespace MediaBrowser.Model.Configuration /// true if [enable localized guids]; otherwise, false. public bool EnableLocalizedGuids { get; set; } - /// - /// Gets or sets a value indicating whether [enable library metadata sub folder]. - /// - /// true if [enable library metadata sub folder]; otherwise, false. - public bool EnableLibraryMetadataSubFolder { get; set; } - /// /// Gets or sets the preferred metadata language. /// diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 414cadf82..2d1aeb5a1 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -143,7 +143,7 @@ namespace MediaBrowser.Providers.Manager { var id = itemOfType.GetLookupInfo(); - await FindIdentities(id, cancellationToken).ConfigureAwait(false); + //await FindIdentities(id, cancellationToken).ConfigureAwait(false); var result = await RefreshWithProviders(metadataResult, id, refreshOptions, providers, itemImageProvider, cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index 030dc7f33..c7ba9cbf0 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -317,7 +317,6 @@ namespace MediaBrowser.WebDashboard.Api _fileSystem.DeleteFile(Path.Combine(path, "thirdparty", "jquerymobile-1.4.5", "jquery.mobile-1.4.5.min.map")); _fileSystem.DeleteDirectory(Path.Combine(path, "bower_components"), true); - _fileSystem.DeleteDirectory(Path.Combine(path, "thirdparty", "viblast"), true); // But we do need this CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "webcomponentsjs", "webcomponents-lite.js"), Path.Combine(path, "bower_components", "webcomponentsjs", "webcomponents-lite.js")); diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index a95e6900c..228a4fafa 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -539,21 +539,6 @@ PreserveNewest - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - PreserveNewest -- cgit v1.2.3 From 7db806da0af3868870d5f01705ac051d8ae83ef9 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 22 Nov 2015 13:17:58 -0500 Subject: start replacing jquery ajax with fetch --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 2 +- MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs | 2 +- MediaBrowser.WebDashboard/Api/DashboardService.cs | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 1de42268a..377c34c31 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -566,7 +566,7 @@ namespace MediaBrowser.Api.Playback if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) { - if (filters.Count > 0) + if (filters.Count > 1) { filters[filters.Count - 1] += ":flags=fast_bilinear"; } diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index d4fa74a86..e796dba76 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -21,7 +21,7 @@ namespace MediaBrowser.Common.Implementations.Security public class PluginSecurityManager : ISecurityManager { private const string MBValidateUrl = MbAdmin.HttpsUrl + "service/registration/validate"; - private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/admin/" + "service/appstore/register"; + private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/admin/service/appstore/register"; /// /// The _is MB supporter diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index 5c36399e7..6d46be0ec 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -335,6 +335,7 @@ namespace MediaBrowser.WebDashboard.Api CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "hammerjs", "hammer.min.js"), Path.Combine(path, "bower_components", "hammerjs", "hammer.min.js")); CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "Sortable", "Sortable.min.js"), Path.Combine(path, "bower_components", "Sortable", "Sortable.min.js")); + CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "fetch", "fetch.js"), Path.Combine(path, "bower_components", "fetch", "fetch.js")); CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "native-promise-only", "lib", "npo.src.js"), Path.Combine(path, "bower_components", "native-promise-only", "lib", "npo.src.js")); } -- cgit v1.2.3 From 90ad1786df98d6f930170898d365d39976f56c1d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 24 Nov 2015 13:46:23 -0500 Subject: remove unneeded param --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 18 +++++++----------- .../ScheduledTasks/Tasks/DeleteCacheFileTask.cs | 8 ++++++++ MediaBrowser.Model/Dlna/StreamInfo.cs | 11 ----------- SharedVersion.cs | 4 ++-- 4 files changed, 17 insertions(+), 24 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index f30e4008d..d98e2f3a1 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -1426,50 +1426,46 @@ namespace MediaBrowser.Api.Playback } } else if (i == 16) - { - request.ClientTime = val; - } - else if (i == 17) { if (videoRequest != null) { videoRequest.MaxRefFrames = int.Parse(val, UsCulture); } } - else if (i == 18) + else if (i == 17) { if (videoRequest != null) { videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture); } } - else if (i == 19) + else if (i == 18) { if (videoRequest != null) { videoRequest.Profile = val; } } - else if (i == 20) + else if (i == 19) { if (videoRequest != null) { videoRequest.Cabac = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } } - else if (i == 21) + else if (i == 20) { request.PlaySessionId = val; } - else if (i == 22) + else if (i == 21) { // api_key } - else if (i == 23) + else if (i == 22) { request.LiveStreamId = val; } - else if (i == 24) + else if (i == 23) { // Duplicating ItemId because of MediaMonkey } diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index a3636ac2e..c7423a775 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -132,6 +132,10 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks { _fileSystem.DeleteDirectory(directory, false); } + catch (UnauthorizedAccessException ex) + { + _logger.ErrorException("Error deleting directory {0}", ex, directory); + } catch (IOException ex) { _logger.ErrorException("Error deleting directory {0}", ex, directory); @@ -146,6 +150,10 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks { _fileSystem.DeleteFile(path); } + catch (UnauthorizedAccessException ex) + { + _logger.ErrorException("Error deleting file {0}", ex, path); + } catch (IOException ex) { _logger.ErrorException("Error deleting file {0}", ex, path); diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 50d1cdfc8..979472948 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -216,17 +216,6 @@ namespace MediaBrowser.Model.Dlna list.Add(new NameValuePair("Level", item.VideoLevel.HasValue ? StringHelper.ToStringCultureInvariant(item.VideoLevel.Value) : string.Empty)); - if (isDlna) - { - // The player may see it as separate resources due to url differences - // And then try to request more than one at playback - list.Add(new NameValuePair("ClientTime", string.Empty)); - } - else - { - list.Add(new NameValuePair("ClientTime", item.IsDirectStream ? string.Empty : DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture))); - } - list.Add(new NameValuePair("MaxRefFrames", item.MaxRefFrames.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxRefFrames.Value) : string.Empty)); list.Add(new NameValuePair("MaxVideoBitDepth", item.MaxVideoBitDepth.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxVideoBitDepth.Value) : string.Empty)); list.Add(new NameValuePair("Profile", item.VideoProfile ?? string.Empty)); diff --git a/SharedVersion.cs b/SharedVersion.cs index 01e44e2ca..f39b5a5d1 100644 --- a/SharedVersion.cs +++ b/SharedVersion.cs @@ -1,4 +1,4 @@ using System.Reflection; -//[assembly: AssemblyVersion("3.0.*")] -[assembly: AssemblyVersion("3.0.5781.3")] +[assembly: AssemblyVersion("3.0.*")] +//[assembly: AssemblyVersion("3.0.5781.3")] -- cgit v1.2.3 From 19076d054637074a0ae7a61b994c67577c9b6f4d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 6 Dec 2015 13:11:03 -0500 Subject: update naming project --- .../MediaBrowser.Common.Implementations.csproj | 6 +++--- MediaBrowser.Common.Implementations/packages.config | 4 ++-- .../MediaBrowser.Server.Implementations.csproj | 4 ++-- MediaBrowser.Server.Implementations/packages.config | 2 +- MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj | 11 ++++++----- MediaBrowser.WebDashboard/packages.config | 2 +- Nuget/MediaBrowser.Common.Internal.nuspec | 4 ++-- 7 files changed, 17 insertions(+), 16 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index 8615d4f8b..3967abe58 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -53,7 +53,7 @@ False - ..\packages\NLog.4.2.0\lib\net45\NLog.dll + ..\packages\NLog.4.2.2\lib\net45\NLog.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll @@ -62,9 +62,9 @@ False ..\ThirdParty\SharpCompress\SharpCompress.dll - + False - ..\packages\SimpleInjector.3.1.0\lib\net45\SimpleInjector.dll + ..\packages\SimpleInjector.3.1.1\lib\net45\SimpleInjector.dll diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index 769a7c4f6..c6c2e1105 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -1,7 +1,7 @@  - + - + diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index aae59013a..5afa4e1ec 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -48,9 +48,9 @@ ..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll - + False - ..\packages\MediaBrowser.Naming.1.0.0.38\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll + ..\packages\MediaBrowser.Naming.1.0.0.41\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll False diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index 1a02e5837..4ea2069af 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -2,7 +2,7 @@ - + diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index acaca99dc..0ea768037 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -63,8 +63,9 @@ ..\ThirdParty\ServiceStack\ServiceStack.Interfaces.dll - - ..\packages\WebMarkupMin.Core.1.0.0\lib\net40\WebMarkupMin.Core.dll + + False + ..\packages\WebMarkupMin.Core.1.0.1\lib\net40\WebMarkupMin.Core.dll @@ -91,11 +92,11 @@ MediaBrowser.Model - + - PreserveNewest + PreserveNewest - + PreserveNewest diff --git a/MediaBrowser.WebDashboard/packages.config b/MediaBrowser.WebDashboard/packages.config index 906f1f4e6..24a8a5316 100644 --- a/MediaBrowser.WebDashboard/packages.config +++ b/MediaBrowser.WebDashboard/packages.config @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/Nuget/MediaBrowser.Common.Internal.nuspec b/Nuget/MediaBrowser.Common.Internal.nuspec index 8fa5b665d..f8c88fbad 100644 --- a/Nuget/MediaBrowser.Common.Internal.nuspec +++ b/Nuget/MediaBrowser.Common.Internal.nuspec @@ -13,8 +13,8 @@ Copyright © Emby 2013 - - + + -- cgit v1.2.3 From d27cd521b54d0d9c0d2256218e927bb88fd2aac0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 14 Dec 2015 09:45:42 -0500 Subject: rework dialog --- .../Networking/BaseNetworkManager.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 7 +++++++ .../HttpServer/HttpListenerHost.cs | 13 ++++++------- .../HttpServer/ServerFactory.cs | 5 ++++- MediaBrowser.Server.Startup.Common/ApplicationHost.cs | 2 +- MediaBrowser.WebDashboard/Api/DashboardService.cs | 19 +++++++++++++++++++ .../MediaBrowser.WebDashboard.csproj | 5 +---- 7 files changed, 39 insertions(+), 14 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 703fec68d..1708206dc 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -84,7 +84,7 @@ namespace MediaBrowser.Common.Implementations.Networking return true; } - private bool IsInPrivateAddressSpace(string endpoint) + public bool IsInPrivateAddressSpace(string endpoint) { if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 8fc947e8f..a3bf1aac8 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -25,6 +25,13 @@ namespace MediaBrowser.Common.Net /// [string] MAC Address string GetMacAddress(); + /// + /// Determines whether [is in private address space] [the specified endpoint]. + /// + /// The endpoint. + /// true if [is in private address space] [the specified endpoint]; otherwise, false. + bool IsInPrivateAddressSpace(string endpoint); + /// /// Gets the network shares. /// diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 6ade9a8f6..847982976 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -19,6 +19,7 @@ using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Security; namespace MediaBrowser.Server.Implementations.HttpServer @@ -46,6 +47,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer public string CertificatePath { get; private set; } private readonly IServerConfigurationManager _config; + private readonly INetworkManager _networkManager; /// /// Gets the local end points. @@ -69,10 +71,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer ILogManager logManager, IServerConfigurationManager config, string serviceName, - string defaultRedirectPath, params Assembly[] assembliesWithServices) + string defaultRedirectPath, INetworkManager networkManager, params Assembly[] assembliesWithServices) : base(serviceName, assembliesWithServices) { DefaultRedirectPath = defaultRedirectPath; + _networkManager = networkManager; _config = config; _logger = logManager.GetLogger("HttpServer"); @@ -175,11 +178,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer private void OnRequestReceived(string localEndPoint) { - var ignore = localEndPoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 || - - localEndPoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) || - localEndPoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) || - localEndPoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase); + var ignore = _networkManager.IsInPrivateAddressSpace(localEndPoint); if (ignore) { @@ -188,7 +187,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer if (_localEndpointLock.TryEnterWriteLock(100)) { - var list = _localEndpoints.ToList(); + var list = _localEndpoints; list.Remove(localEndPoint); list.Insert(0, localEndPoint); diff --git a/MediaBrowser.Server.Implementations/HttpServer/ServerFactory.cs b/MediaBrowser.Server.Implementations/HttpServer/ServerFactory.cs index 4d81ec157..cc351f6b3 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/ServerFactory.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/ServerFactory.cs @@ -1,4 +1,5 @@ using MediaBrowser.Common; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Logging; @@ -17,18 +18,20 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The application host. /// The log manager. /// The configuration. + /// The _networkmanager. /// Name of the server. /// The default redirectpath. /// IHttpServer. public static IHttpServer CreateServer(IApplicationHost applicationHost, ILogManager logManager, IServerConfigurationManager config, + INetworkManager _networkmanager, string serverName, string defaultRedirectpath) { LogManager.LogFactory = new ServerLogFactory(logManager); - return new HttpListenerHost(applicationHost, logManager, config, serverName, defaultRedirectpath); + return new HttpListenerHost(applicationHost, logManager, config, serverName, defaultRedirectpath, _networkmanager); } } } diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index f0fe68dd8..f4da52f2e 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -436,7 +436,7 @@ namespace MediaBrowser.Server.Startup.Common RegisterSingleInstance(() => new SearchEngine(LogManager, LibraryManager, UserManager)); - HttpServer = ServerFactory.CreateServer(this, LogManager, ServerConfigurationManager, "Emby", "web/index.html"); + HttpServer = ServerFactory.CreateServer(this, LogManager, ServerConfigurationManager, NetworkManager, "Emby", "web/index.html"); HttpServer.GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading"); RegisterSingleInstance(HttpServer, false); progress.Report(10); diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index 0ee62cb96..2fc77dff4 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -310,6 +310,7 @@ namespace MediaBrowser.WebDashboard.Api DeleteFilesByExtension(bowerPath, ".md"); DeleteFilesByExtension(bowerPath, ".json"); DeleteFilesByExtension(bowerPath, ".gz"); + DeleteFilesByExtension(bowerPath, ".bat"); DeleteFilesByName(bowerPath, "copying", true); DeleteFilesByName(bowerPath, "license", true); DeleteFilesByName(bowerPath, "license-mit", true); @@ -330,6 +331,8 @@ namespace MediaBrowser.WebDashboard.Api DeleteFoldersByName(bowerPath, "grunt"); DeleteFoldersByName(bowerPath, "rollups"); + DeleteCryptoFiles(Path.Combine(bowerPath, "cryptojslib", "components")); + DeleteFoldersByName(Path.Combine(bowerPath, "jquery"), "src"); DeleteFoldersByName(Path.Combine(bowerPath, "jstree"), "src"); DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "meteor"); @@ -357,6 +360,22 @@ namespace MediaBrowser.WebDashboard.Api return ""; } + private void DeleteCryptoFiles(string path) + { + var files = _fileSystem.GetFiles(path) + .ToList(); + + var keepFiles = new[] { "core-min.js", "md5-min.js", "sha1-min.js" }; + + foreach (var file in files) + { + if (!keepFiles.Contains(file.Name, StringComparer.OrdinalIgnoreCase)) + { + _fileSystem.DeleteFile(file.FullName); + } + } + } + private void DeleteFilesByExtension(string path, string extension) { var files = _fileSystem.GetFiles(path, true) diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index 4ce05415b..975c60a0b 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -116,15 +116,12 @@ PreserveNewest - + PreserveNewest PreserveNewest - - PreserveNewest - PreserveNewest -- cgit v1.2.3 From 0ffc5ebace929a6b243219ab025e16d4bb0d2d67 Mon Sep 17 00:00:00 2001 From: Luke Date: Fri, 25 Dec 2015 22:23:02 -0500 Subject: update ulna interface binding --- .../Networking/BaseNetworkManager.cs | 94 +++++++++++--------- MediaBrowser.Common/Net/INetworkManager.cs | 2 +- MediaBrowser.Dlna/Main/DlnaEntryPoint.cs | 7 +- MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs | 99 ++++++++++++---------- .../ApplicationHost.cs | 1 + 5 files changed, 114 insertions(+), 89 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 1708206dc..7cf2b3838 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -7,6 +7,7 @@ using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; +using MoreLinq; namespace MediaBrowser.Common.Implementations.Networking { @@ -31,14 +32,14 @@ namespace MediaBrowser.Common.Implementations.Networking } } - private volatile List _localIpAddresses; + private volatile List _localIpAddresses; private readonly object _localIpAddressSyncLock = new object(); /// /// Gets the machine's local ip address /// /// IPAddress. - public IEnumerable GetLocalIpAddresses() + public IEnumerable GetLocalIpAddresses() { if (_localIpAddresses == null) { @@ -58,25 +59,24 @@ namespace MediaBrowser.Common.Implementations.Networking return _localIpAddresses; } - private IEnumerable GetLocalIpAddressesInternal() + private IEnumerable GetLocalIpAddressesInternal() { var list = GetIPsDefault() - .Where(i => !IPAddress.IsLoopback(i)) - .Select(i => i.ToString()) - .Where(FilterIpAddress) .ToList(); - if (list.Count > 0) + if (list.Count == 0) { - return list; + list.AddRange(GetLocalIpAddressesFallback()); } - return GetLocalIpAddressesFallback().Where(FilterIpAddress); + return list.Where(i => !IPAddress.IsLoopback(i)).Where(FilterIpAddress).DistinctBy(i => i.ToString()); } - private bool FilterIpAddress(string address) + private bool FilterIpAddress(IPAddress address) { - if (address.StartsWith("169.", StringComparison.OrdinalIgnoreCase)) + var addressString = address.ToString (); + + if (addressString.StartsWith("169.", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -164,8 +164,7 @@ namespace MediaBrowser.Common.Implementations.Networking { var prefix = addressString.Substring(0, lengthMatch); - if (GetLocalIpAddresses() - .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) { return true; } @@ -209,33 +208,47 @@ namespace MediaBrowser.Common.Implementations.Networking return Dns.GetHostAddresses(hostName); } - private IEnumerable GetIPsDefault() - { - foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces()) - { - var props = adapter.GetIPProperties(); - var gateways = from ga in props.GatewayAddresses - where !ga.Address.Equals(IPAddress.Any) - select true; - - if (!gateways.Any()) - { - continue; - } - - foreach (var uni in props.UnicastAddresses) - { - var address = uni.Address; - if (address.AddressFamily != AddressFamily.InterNetwork) - { - continue; - } - yield return address; - } - } - } - - private IEnumerable GetLocalIpAddressesFallback() + private List GetIPsDefault() + { + NetworkInterface[] interfaces; + + try + { + interfaces = NetworkInterface.GetAllNetworkInterfaces(); + } + catch (Exception ex) + { + Logger.ErrorException("Error in GetAllNetworkInterfaces", ex); + return new List(); + } + + return interfaces.SelectMany(network => { + + try + { + Logger.Debug("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + + var properties = network.GetIPProperties(); + var ipV4 = properties.GetIPv4Properties(); + if (null == ipV4) + return new List(); + + return properties.UnicastAddresses + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i.Address)) + .Select(i => i.Address) + .ToList(); + } + catch (Exception ex) + { + Logger.ErrorException("Error querying network interface", ex); + return new List(); + } + + }).DistinctBy(i => i.ToString()) + .ToList(); + } + + private IEnumerable GetLocalIpAddressesFallback() { var host = Dns.GetHostEntry(Dns.GetHostName()); @@ -243,7 +256,6 @@ namespace MediaBrowser.Common.Implementations.Networking // It's not fool-proof so ultimately the consumer will have to examine them and decide return host.AddressList .Where(i => i.AddressFamily == AddressFamily.InterNetwork) - .Select(i => i.ToString()) .Reverse(); } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index a3bf1aac8..de63ddd51 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -11,7 +11,7 @@ namespace MediaBrowser.Common.Net /// Gets the machine's local ip address /// /// IPAddress. - IEnumerable GetLocalIpAddresses(); + IEnumerable GetLocalIpAddresses(); /// /// Gets a random port number that is currently available diff --git a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs index 8c45757e7..37cca43eb 100644 --- a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs +++ b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs @@ -150,11 +150,12 @@ namespace MediaBrowser.Dlna.Main { foreach (var address in _network.GetLocalIpAddresses()) { - var guid = address.GetMD5(); + var addressString = address.ToString (); + var guid = addressString.GetMD5(); var descriptorURI = "/dlna/" + guid.ToString("N") + "/description.xml"; - var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorURI); + var uri = new Uri(_appHost.GetLocalApiUrl(addressString) + descriptorURI); var services = new List { @@ -166,7 +167,7 @@ namespace MediaBrowser.Dlna.Main "uuid:" + guid.ToString("N") }; - _ssdpHandler.RegisterNotification(guid, uri, IPAddress.Parse(address), services); + _ssdpHandler.RegisterNotification(guid, uri, address, services); _registeredServerIds.Add(guid.ToString("N")); } diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs index c9b983bae..02c26e8c1 100644 --- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs +++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs @@ -36,40 +36,63 @@ namespace MediaBrowser.Dlna.Ssdp _appHost = appHost; } + private List GetLocalIpAddresses() + { + NetworkInterface[] interfaces; + + try + { + interfaces = NetworkInterface.GetAllNetworkInterfaces(); + } + catch (Exception ex) + { + _logger.ErrorException("Error in GetAllNetworkInterfaces", ex); + return new List(); + } + + return interfaces.SelectMany(network => { + + try + { + _logger.Debug("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + + var properties = network.GetIPProperties(); + var ipV4 = properties.GetIPv4Properties(); + if (null == ipV4) + return new List(); + + return properties.UnicastAddresses + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i.Address)) + .Select(i => i.Address) + .ToList(); + } + catch (Exception ex) + { + _logger.ErrorException("Error querying network interface", ex); + return new List(); + } + + }) + .Distinct() + .ToList(); + } + public void Start(SsdpHandler ssdpHandler) { _ssdpHandler = ssdpHandler; _ssdpHandler.MessageReceived += _ssdpHandler_MessageReceived; - foreach (var network in GetNetworkInterfaces()) - { - _logger.Debug("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); - - if (!network.SupportsMulticast || OperationalStatus.Up != network.OperationalStatus || !network.GetIPProperties().MulticastAddresses.Any()) - continue; - - var properties = network.GetIPProperties(); - var ipV4 = properties.GetIPv4Properties(); - if (null == ipV4) - continue; - - var localIps = properties.UnicastAddresses - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork) - .Select(i => i.Address) - .ToList(); - - foreach (var localIp in localIps) - { - try - { - CreateListener(localIp); - } - catch (Exception e) - { - _logger.ErrorException("Failed to Initilize Socket", e); - } - } - } + foreach (var localIp in GetLocalIpAddresses()) + { + try + { + CreateListener(localIp); + } + catch (Exception e) + { + _logger.ErrorException("Failed to Initilize Socket", e); + } + } } void _ssdpHandler_MessageReceived(object sender, SsdpMessageEventArgs e) @@ -107,29 +130,17 @@ namespace MediaBrowser.Dlna.Ssdp } } - private IEnumerable GetNetworkInterfaces() - { - try - { - return NetworkInterface.GetAllNetworkInterfaces(); - } - catch (Exception ex) - { - _logger.ErrorException("Error in GetAllNetworkInterfaces", ex); - return new List(); - } - } private void CreateListener(IPAddress localIp) { Task.Factory.StartNew(async (o) => { try { - var endPoint = new IPEndPoint(localIp, 1900); + _logger.Info("Creating SSDP listener on {0}", localIp); - var socket = GetMulticastSocket(localIp, endPoint); + var endPoint = new IPEndPoint(localIp, 1900); - _logger.Info("Creating SSDP listener on {0}", localIp); + var socket = GetMulticastSocket(localIp, endPoint); var receiveBuffer = new byte[64000]; diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index f4da52f2e..2bdb138d7 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -1154,6 +1154,7 @@ namespace MediaBrowser.Server.Startup.Common get { var localAddresses = NetworkManager.GetLocalIpAddresses() + .Select(i => i.ToString()) .ToList(); var httpServerAddresses = HttpServer.LocalEndPoints -- cgit v1.2.3 From 40c46ca64995668a4becab4021613c56903649c4 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 25 Dec 2015 22:36:38 -0500 Subject: update dlna interface binding --- .../MediaBrowser.Common.Implementations.csproj | 4 ++++ .../Networking/BaseNetworkManager.cs | 9 +++------ MediaBrowser.Common.Implementations/packages.config | 1 + MediaBrowser.Dlna/MediaBrowser.Dlna.csproj | 4 ++++ MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs | 12 +++++------- MediaBrowser.Dlna/packages.config | 1 + 6 files changed, 18 insertions(+), 13 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index 3967abe58..a86dd45ac 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -51,6 +51,9 @@ False ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll + False ..\packages\NLog.4.2.2\lib\net45\NLog.dll @@ -69,6 +72,7 @@ + diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 7cf2b3838..789cde5fc 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -226,16 +226,13 @@ namespace MediaBrowser.Common.Implementations.Networking try { - Logger.Debug("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); var properties = network.GetIPProperties(); - var ipV4 = properties.GetIPv4Properties(); - if (null == ipV4) - return new List(); return properties.UnicastAddresses - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i.Address)) - .Select(i => i.Address) + .Select(i => i.Address) + .Where(i => i.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i)) .ToList(); } catch (Exception ex) diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index c6c2e1105..7d594dfdb 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -1,6 +1,7 @@  + diff --git a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj index b8ac60ef6..8169e7f8b 100644 --- a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj +++ b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj @@ -44,6 +44,10 @@ False ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + + False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll + ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs index 02c26e8c1..457134913 100644 --- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs +++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs @@ -11,6 +11,7 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using MoreLinq; namespace MediaBrowser.Dlna.Ssdp { @@ -54,16 +55,13 @@ namespace MediaBrowser.Dlna.Ssdp try { - _logger.Debug("Found interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + _logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); var properties = network.GetIPProperties(); - var ipV4 = properties.GetIPv4Properties(); - if (null == ipV4) - return new List(); return properties.UnicastAddresses - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i.Address)) - .Select(i => i.Address) + .Select(i => i.Address) + .Where(i => i.AddressFamily == AddressFamily.InterNetwork) .ToList(); } catch (Exception ex) @@ -73,7 +71,7 @@ namespace MediaBrowser.Dlna.Ssdp } }) - .Distinct() + .DistinctBy(i => i.ToString()) .ToList(); } diff --git a/MediaBrowser.Dlna/packages.config b/MediaBrowser.Dlna/packages.config index fad6af08e..258a097cd 100644 --- a/MediaBrowser.Dlna/packages.config +++ b/MediaBrowser.Dlna/packages.config @@ -1,5 +1,6 @@  + \ No newline at end of file -- cgit v1.2.3 From bb4aabc070672cdbaa946c49959261581ac32cee Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 26 Dec 2015 14:57:29 -0500 Subject: update components --- .../MediaBrowser.Common.Implementations.csproj | 4 ++-- MediaBrowser.Common.Implementations/packages.config | 2 +- .../MediaBrowser.Server.Implementations.csproj | 4 ++-- MediaBrowser.Server.Implementations/packages.config | 2 +- Nuget/MediaBrowser.Common.Internal.nuspec | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index a86dd45ac..e084a4501 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -65,9 +65,9 @@ False ..\ThirdParty\SharpCompress\SharpCompress.dll - + False - ..\packages\SimpleInjector.3.1.1\lib\net45\SimpleInjector.dll + ..\packages\SimpleInjector.3.1.2\lib\net45\SimpleInjector.dll diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index 7d594dfdb..e68e7df53 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -4,5 +4,5 @@ - + diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index c93875811..3e8ba7ff1 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -62,9 +62,9 @@ ..\ThirdParty\ServiceStack\ServiceStack.Api.Swagger.dll - + False - ..\packages\SocketHttpListener.1.0.0.19\lib\net45\SocketHttpListener.dll + ..\packages\SocketHttpListener.1.0.0.20\lib\net45\SocketHttpListener.dll diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index a1e97ddc8..55cd993b0 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -6,5 +6,5 @@ - + \ No newline at end of file diff --git a/Nuget/MediaBrowser.Common.Internal.nuspec b/Nuget/MediaBrowser.Common.Internal.nuspec index efd226238..7c59cde06 100644 --- a/Nuget/MediaBrowser.Common.Internal.nuspec +++ b/Nuget/MediaBrowser.Common.Internal.nuspec @@ -14,7 +14,7 @@ - + -- cgit v1.2.3 From 6a9d71db10cc117076706e8d0c996fb831164d24 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 27 Dec 2015 14:06:38 -0500 Subject: update nlog --- .../MediaBrowser.Common.Implementations.csproj | 2 +- MediaBrowser.Common.Implementations/packages.config | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index e084a4501..cea5b8f3f 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -56,7 +56,7 @@ False - ..\packages\NLog.4.2.2\lib\net45\NLog.dll + ..\packages\NLog.4.2.3\lib\net45\NLog.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index e68e7df53..84f663268 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -2,7 +2,7 @@ - + -- cgit v1.2.3 From 4b11e3e0d8aca93da7132d10a37a4139f75d713f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 27 Dec 2015 14:22:55 -0500 Subject: fix merge conflicts --- MediaBrowser.Api/MediaBrowser.Api.csproj | 3 +-- .../MediaBrowser.Common.Implementations.csproj | 6 ++---- MediaBrowser.Controller/MediaBrowser.Controller.csproj | 3 +-- MediaBrowser.Dlna/MediaBrowser.Dlna.csproj | 3 +-- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 3 +-- .../MediaBrowser.Server.Implementations.csproj | 5 ++--- 6 files changed, 8 insertions(+), 15 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index 2f6926239..08b99d5a4 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -49,8 +49,7 @@ False ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll - - False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index cea5b8f3f..59e20ec6e 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -54,8 +54,7 @@ ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll - - False + ..\packages\NLog.4.2.3\lib\net45\NLog.dll @@ -65,8 +64,7 @@ False ..\ThirdParty\SharpCompress\SharpCompress.dll - - False + ..\packages\SimpleInjector.3.1.2\lib\net45\SimpleInjector.dll diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 9243f5b9c..a32ffdb3b 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -51,8 +51,7 @@ ..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll - - False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj index 8169e7f8b..db69a45c8 100644 --- a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj +++ b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj @@ -44,8 +44,7 @@ False ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll - - False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index e04021835..7478b2738 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -56,8 +56,7 @@ False ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\DvdLib.dll - - False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index c842e28b6..24670aedf 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -52,8 +52,7 @@ False ..\packages\MediaBrowser.Naming.1.0.0.41\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll - - False + ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll @@ -122,9 +121,9 @@ - + -- cgit v1.2.3 From b46ef16ba838dafbd79f6e9ffbea37afa2104b0b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 28 Dec 2015 22:39:38 -0500 Subject: update local address detection --- MediaBrowser.Api/System/SystemService.cs | 11 ++++ .../Networking/BaseNetworkManager.cs | 4 +- MediaBrowser.Controller/IServerApplicationHost.cs | 4 +- MediaBrowser.Controller/Net/IHttpServer.cs | 6 -- MediaBrowser.Dlna/Main/DlnaEntryPoint.cs | 44 +++++++------ MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs | 7 ++- .../HttpServer/HttpListenerHost.cs | 38 ------------ .../ApplicationHost.cs | 72 +++++++++++++++------- 8 files changed, 95 insertions(+), 91 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index a95fcb542..4faff8780 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -32,6 +32,12 @@ namespace MediaBrowser.Api.System } + [Route("/System/Ping", "POST")] + public class PingSystem : IReturnVoid + { + + } + /// /// Class RestartApplication /// @@ -117,6 +123,11 @@ namespace MediaBrowser.Api.System return ToOptimizedResult(result); } + public void Post(PingSystem request) + { + + } + public object Get(GetServerLogs request) { List files; diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 789cde5fc..9b278b889 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Common.Implementations.Networking list.AddRange(GetLocalIpAddressesFallback()); } - return list.Where(i => !IPAddress.IsLoopback(i)).Where(FilterIpAddress).DistinctBy(i => i.ToString()); + return list.Where(FilterIpAddress).DistinctBy(i => i.ToString()); } private bool FilterIpAddress(IPAddress address) @@ -232,7 +232,7 @@ namespace MediaBrowser.Common.Implementations.Networking return properties.UnicastAddresses .Select(i => i.Address) - .Where(i => i.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(i)) + .Where(i => i.AddressFamily == AddressFamily.InterNetwork) .ToList(); } catch (Exception ex) diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 1b842a5f6..fb843d191 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -1,6 +1,8 @@ using MediaBrowser.Common; using MediaBrowser.Model.System; using System; +using System.Collections.Generic; +using System.Net; namespace MediaBrowser.Controller { @@ -63,7 +65,7 @@ namespace MediaBrowser.Controller /// Gets the local ip address. /// /// The local ip address. - string LocalIpAddress { get; } + List LocalIpAddresses { get; } /// /// Gets the local API URL. diff --git a/MediaBrowser.Controller/Net/IHttpServer.cs b/MediaBrowser.Controller/Net/IHttpServer.cs index 91da5fab2..97c5dd31b 100644 --- a/MediaBrowser.Controller/Net/IHttpServer.cs +++ b/MediaBrowser.Controller/Net/IHttpServer.cs @@ -28,12 +28,6 @@ namespace MediaBrowser.Controller.Net /// the ssl certificate localtion on the file system. void StartServer(IEnumerable urlPrefixes, string certificatePath); - /// - /// Gets the local end points. - /// - /// The local end points. - IEnumerable LocalEndPoints { get; } - /// /// Stops this instance. /// diff --git a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs index 37cca43eb..d79ef9eaf 100644 --- a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs +++ b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs @@ -43,19 +43,19 @@ namespace MediaBrowser.Dlna.Main private readonly List _registeredServerIds = new List(); private bool _dlnaServerStarted; - public DlnaEntryPoint(IServerConfigurationManager config, - ILogManager logManager, - IServerApplicationHost appHost, - INetworkManager network, - ISessionManager sessionManager, - IHttpClient httpClient, - ILibraryManager libraryManager, - IUserManager userManager, - IDlnaManager dlnaManager, - IImageProcessor imageProcessor, - IUserDataManager userDataManager, - ILocalizationManager localization, - IMediaSourceManager mediaSourceManager, + public DlnaEntryPoint(IServerConfigurationManager config, + ILogManager logManager, + IServerApplicationHost appHost, + INetworkManager network, + ISessionManager sessionManager, + IHttpClient httpClient, + ILibraryManager libraryManager, + IUserManager userManager, + IDlnaManager dlnaManager, + IImageProcessor imageProcessor, + IUserDataManager userDataManager, + ILocalizationManager localization, + IMediaSourceManager mediaSourceManager, ISsdpHandler ssdpHandler, IDeviceDiscovery deviceDiscovery) { _config = config; @@ -148,14 +148,20 @@ namespace MediaBrowser.Dlna.Main private void RegisterServerEndpoints() { - foreach (var address in _network.GetLocalIpAddresses()) + foreach (var address in _appHost.LocalIpAddresses) { - var addressString = address.ToString (); - var guid = addressString.GetMD5(); + //if (IPAddress.IsLoopback(address)) + //{ + // // Should we allow this? + // continue; + //} + + var addressString = address.ToString(); + var guid = addressString.GetMD5(); var descriptorURI = "/dlna/" + guid.ToString("N") + "/description.xml"; - var uri = new Uri(_appHost.GetLocalApiUrl(addressString) + descriptorURI); + var uri = new Uri(_appHost.GetLocalApiUrl(addressString) + descriptorURI); var services = new List { @@ -166,8 +172,8 @@ namespace MediaBrowser.Dlna.Main "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1", "uuid:" + guid.ToString("N") }; - - _ssdpHandler.RegisterNotification(guid, uri, address, services); + + _ssdpHandler.RegisterNotification(guid, uri, address, services); _registeredServerIds.Add(guid.ToString("N")); } diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs index 457134913..279979550 100644 --- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs +++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs @@ -110,8 +110,11 @@ namespace MediaBrowser.Dlna.Ssdp { if (e.LocalEndPoint == null) { - var ip = _appHost.LocalIpAddress; - e.LocalEndPoint = new IPEndPoint(IPAddress.Parse(ip), 0); + var ip = _appHost.LocalIpAddresses.FirstOrDefault(i => !IPAddress.IsLoopback(i)); + if (ip != null) + { + e.LocalEndPoint = new IPEndPoint(ip, 0); + } } if (e.LocalEndPoint != null) diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 847982976..0283c1f7a 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -40,33 +40,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer public event EventHandler WebSocketConnected; public event EventHandler WebSocketConnecting; - private readonly List _localEndpoints = new List(); - - private readonly ReaderWriterLockSlim _localEndpointLock = new ReaderWriterLockSlim(); - public string CertificatePath { get; private set; } private readonly IServerConfigurationManager _config; private readonly INetworkManager _networkManager; - /// - /// Gets the local end points. - /// - /// The local end points. - public IEnumerable LocalEndPoints - { - get - { - _localEndpointLock.EnterReadLock(); - - var list = _localEndpoints.ToList(); - - _localEndpointLock.ExitReadLock(); - - return list; - } - } - public HttpListenerHost(IApplicationHost applicationHost, ILogManager logManager, IServerConfigurationManager config, @@ -178,22 +156,6 @@ namespace MediaBrowser.Server.Implementations.HttpServer private void OnRequestReceived(string localEndPoint) { - var ignore = _networkManager.IsInPrivateAddressSpace(localEndPoint); - - if (ignore) - { - return; - } - - if (_localEndpointLock.TryEnterWriteLock(100)) - { - var list = _localEndpoints; - - list.Remove(localEndPoint); - list.Insert(0, localEndPoint); - - _localEndpointLock.ExitWriteLock(); - } } /// diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 2bdb138d7..a4760f3af 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -91,10 +91,12 @@ using MediaBrowser.Server.Startup.Common.Migrations; using MediaBrowser.WebDashboard.Api; using MediaBrowser.XbmcMetadata.Providers; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -207,6 +209,7 @@ namespace MediaBrowser.Server.Startup.Common private readonly string _remotePackageName; internal INativeApp NativeApp { get; set; } + private Timer _ipAddressCacheTimer; /// /// Initializes a new instance of the class. @@ -230,6 +233,8 @@ namespace MediaBrowser.Server.Startup.Common NativeApp = nativeApp; SetBaseExceptionMessage(); + + _ipAddressCacheTimer = new Timer(OnCacheClearTimerFired, null, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3)); } private Version _version; @@ -1116,14 +1121,14 @@ namespace MediaBrowser.Server.Startup.Common try { // Return the first matched address, if found, or the first known local address - var address = LocalIpAddress; + var address = LocalIpAddresses.FirstOrDefault(i => !IPAddress.IsLoopback(i)); - if (!string.IsNullOrWhiteSpace(address)) + if (address != null) { - address = GetLocalApiUrl(address); + return GetLocalApiUrl(address.ToString()); } - return address; + return null; } catch (Exception ex) { @@ -1141,39 +1146,60 @@ namespace MediaBrowser.Server.Startup.Common HttpPort.ToString(CultureInfo.InvariantCulture)); } - public string LocalIpAddress + public List LocalIpAddresses { get { - return HttpServerIpAddresses.FirstOrDefault(); + var localAddresses = NetworkManager.GetLocalIpAddresses() + .Where(IsIpAddressValid) + .ToList(); + + return localAddresses; } } - private IEnumerable HttpServerIpAddresses + private readonly ConcurrentDictionary _validAddressResults = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private bool IsIpAddressValid(IPAddress address) { - get + if (IPAddress.IsLoopback(address)) { - var localAddresses = NetworkManager.GetLocalIpAddresses() - .Select(i => i.ToString()) - .ToList(); + return true; + } - var httpServerAddresses = HttpServer.LocalEndPoints - .Select(i => i.Split(':').FirstOrDefault()) - .Where(i => !string.IsNullOrEmpty(i)) - .ToList(); + var apiUrl = GetLocalApiUrl(address.ToString()); + apiUrl += "/system/ping"; - // Cross-check the local ip addresses with addresses that have been received on with the http server - var matchedAddresses = httpServerAddresses - .Where(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase)) - .ToList(); + bool cachedResult; + if (_validAddressResults.TryGetValue(apiUrl, out cachedResult)) + { + return cachedResult; + } - if (matchedAddresses.Count == 0) + try + { + using (var response = HttpClient.SendAsync(new HttpRequestOptions { - return localAddresses; - } + Url = apiUrl, + BufferContent = false, + LogErrorResponseBody = false, + LogErrors = false - return matchedAddresses; + }, "POST").Result) + { + _validAddressResults.AddOrUpdate(apiUrl, true, (k, v) => true); + return true; + } } + catch + { + _validAddressResults.AddOrUpdate(apiUrl, true, (k, v) => false); + return false; + } + } + + private void OnCacheClearTimerFired(object state) + { + _validAddressResults.Clear(); } public string FriendlyName -- cgit v1.2.3 From 821e8246872cfa380249bca2f79ea810f27c87d5 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 Jan 2016 16:54:37 -0500 Subject: better caching of remote data --- MediaBrowser.Api/System/SystemService.cs | 13 -- .../Security/PluginSecurityManager.cs | 60 --------- .../Updates/InstallationManager.cs | 103 ++++++++++---- MediaBrowser.Common/Security/ISecurityManager.cs | 6 - .../MediaBrowser.Model.Portable.csproj | 3 - .../MediaBrowser.Model.net35.csproj | 3 - MediaBrowser.Model/Entities/SupporterInfo.cs | 15 --- MediaBrowser.Model/MediaBrowser.Model.csproj | 1 - .../Connect/ConnectEntryPoint.cs | 3 +- .../Connect/ConnectManager.cs | 15 --- .../EntryPoints/LoadRegistrations.cs | 2 +- .../Notifications/RemoteNotifications.cs | 148 --------------------- .../MediaBrowser.Server.Implementations.csproj | 1 - 13 files changed, 79 insertions(+), 294 deletions(-) delete mode 100644 MediaBrowser.Model/Entities/SupporterInfo.cs delete mode 100644 MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index 539b920a7..9b6b6a7d6 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -78,12 +78,6 @@ namespace MediaBrowser.Api.System public string Name { get; set; } } - [Route("/System/SupporterInfo", "GET")] - [Authenticated] - public class GetSupporterInfo : IReturn - { - } - /// /// Class SystemInfoService /// @@ -116,13 +110,6 @@ namespace MediaBrowser.Api.System _security = security; } - public async Task Get(GetSupporterInfo request) - { - var result = await _security.GetSupporterInfo().ConfigureAwait(false); - - return ToOptimizedResult(result); - } - public object Post(PingSystem request) { return _appHost.Name; diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index e796dba76..d8f350207 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -153,66 +153,6 @@ namespace MediaBrowser.Common.Implementations.Security } } - public async Task GetSupporterInfo() - { - var key = SupporterKey; - - if (string.IsNullOrWhiteSpace(key)) - { - return new SupporterInfo(); - } - - var data = new Dictionary - { - { "key", key }, - }; - - var url = MbAdmin.HttpsUrl + "/service/supporter/retrieve"; - - using (var stream = await _httpClient.Post(url, data, CancellationToken.None).ConfigureAwait(false)) - { - var response = _jsonSerializer.DeserializeFromStream(stream); - - var info = new SupporterInfo - { - Email = response.email, - PlanType = response.planType, - SupporterKey = response.supporterKey, - IsActiveSupporter = IsMBSupporter - }; - - if (!string.IsNullOrWhiteSpace(response.expDate)) - { - DateTime parsedDate; - if (DateTime.TryParse(response.expDate, out parsedDate)) - { - info.ExpirationDate = parsedDate; - } - else - { - _logger.Error("Failed to parse expDate: {0}", response.expDate); - } - } - - if (!string.IsNullOrWhiteSpace(response.regDate)) - { - DateTime parsedDate; - if (DateTime.TryParse(response.regDate, out parsedDate)) - { - info.RegistrationDate = parsedDate; - } - else - { - _logger.Error("Failed to parse regDate: {0}", response.regDate); - } - } - - info.IsExpiredSupporter = info.ExpirationDate.HasValue && info.ExpirationDate < DateTime.UtcNow && !string.IsNullOrWhiteSpace(info.SupporterKey); - - return info; - } - } - /// /// Register an app store sale with our back-end. It will validate the transaction with the store /// and then register the proper feature and then fill in the supporter key on success. diff --git a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs index dc642a0a8..014275331 100644 --- a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs +++ b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs @@ -185,7 +185,7 @@ namespace MediaBrowser.Common.Implementations.Updates } } - private Tuple, DateTime> _lastPackageListResult; + private DateTime _lastPackageUpdateTime; /// /// Gets all available packages. @@ -194,40 +194,89 @@ namespace MediaBrowser.Common.Implementations.Updates /// Task{List{PackageInfo}}. public async Task> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken) { - if (_lastPackageListResult != null) + using (var stream = await GetCachedPackages(cancellationToken).ConfigureAwait(false)) { - TimeSpan cacheLength; + var packages = _jsonSerializer.DeserializeFromStream>(stream).ToList(); - switch (_config.CommonConfiguration.SystemUpdateLevel) + if ((DateTime.UtcNow - _lastPackageUpdateTime) > GetCacheLength()) { - case PackageVersionClass.Beta: - cacheLength = TimeSpan.FromMinutes(30); - break; - case PackageVersionClass.Dev: - cacheLength = TimeSpan.FromMinutes(3); - break; - default: - cacheLength = TimeSpan.FromHours(24); - break; + UpdateCachedPackages(CancellationToken.None, false); } - if ((DateTime.UtcNow - _lastPackageListResult.Item2) < cacheLength) - { - return _lastPackageListResult.Item1; - } + return packages; } + } - using (var json = await _httpClient.Get(MbAdmin.HttpUrl + "service/MB3Packages.json", cancellationToken).ConfigureAwait(false)) + private string PackageCachePath + { + get { return Path.Combine(_appPaths.CachePath, "serverpackages.json"); } + } + + private async Task GetCachedPackages(CancellationToken cancellationToken) + { + try + { + return _fileSystem.OpenRead(PackageCachePath); + } + catch (Exception) { - cancellationToken.ThrowIfCancellationRequested(); - var packages = _jsonSerializer.DeserializeFromStream>(json).ToList(); + } - packages = FilterPackages(packages).ToList(); + await UpdateCachedPackages(cancellationToken, true).ConfigureAwait(false); + return _fileSystem.OpenRead(PackageCachePath); + } + + private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1); + private async Task UpdateCachedPackages(CancellationToken cancellationToken, bool throwErrors) + { + await _updateSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - _lastPackageListResult = new Tuple, DateTime>(packages, DateTime.UtcNow); + try + { + if ((DateTime.UtcNow - _lastPackageUpdateTime) < GetCacheLength()) + { + return; + } - return _lastPackageListResult.Item1; + var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions + { + Url = MbAdmin.HttpUrl + "service/MB3Packages.json", + CancellationToken = cancellationToken, + Progress = new Progress() + + }).ConfigureAwait(false); + + _fileSystem.CreateDirectory(Path.GetDirectoryName(PackageCachePath)); + + _fileSystem.CopyFile(tempFile, PackageCachePath, true); + _lastPackageUpdateTime = DateTime.UtcNow; + } + catch (Exception ex) + { + _logger.ErrorException("Error updating package cache", ex); + + if (throwErrors) + { + throw; + } + } + finally + { + _updateSemaphore.Release(); + } + } + + private TimeSpan GetCacheLength() + { + switch (_config.CommonConfiguration.SystemUpdateLevel) + { + case PackageVersionClass.Beta: + return TimeSpan.FromMinutes(30); + case PackageVersionClass.Dev: + return TimeSpan.FromMinutes(3); + default: + return TimeSpan.FromHours(24); } } @@ -554,7 +603,7 @@ namespace MediaBrowser.Common.Implementations.Updates if (packageChecksum != Guid.Empty) // support for legacy uploads for now { using (var crypto = new MD5CryptoServiceProvider()) - using (var stream = new BufferedStream(_fileSystem.OpenRead(tempFile), 100000)) + using (var stream = new BufferedStream(_fileSystem.OpenRead(tempFile), 100000)) { var check = Guid.Parse(BitConverter.ToString(crypto.ComputeHash(stream)).Replace("-", String.Empty)); if (check != packageChecksum) @@ -569,12 +618,12 @@ namespace MediaBrowser.Common.Implementations.Updates // Success - move it to the real target try { - _fileSystem.CreateDirectory(Path.GetDirectoryName(target)); - _fileSystem.CopyFile(tempFile, target, true); + _fileSystem.CreateDirectory(Path.GetDirectoryName(target)); + _fileSystem.CopyFile(tempFile, target, true); //If it is an archive - write out a version file so we know what it is if (isArchive) { - File.WriteAllText(target + ".ver", package.versionStr); + File.WriteAllText(target + ".ver", package.versionStr); } } catch (IOException e) diff --git a/MediaBrowser.Common/Security/ISecurityManager.cs b/MediaBrowser.Common/Security/ISecurityManager.cs index 729de911b..0d8934a62 100644 --- a/MediaBrowser.Common/Security/ISecurityManager.cs +++ b/MediaBrowser.Common/Security/ISecurityManager.cs @@ -41,12 +41,6 @@ namespace MediaBrowser.Common.Security /// Task LoadAllRegistrationInfo(); - /// - /// Gets the supporter information. - /// - /// Task<SupporterInfo>. - Task GetSupporterInfo(); - /// /// Register and app store sale with our back-end /// diff --git a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj index 40e532b79..6145983e2 100644 --- a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj +++ b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj @@ -608,9 +608,6 @@ Entities\SortOrder.cs - - Entities\SupporterInfo.cs - Entities\TrailerType.cs diff --git a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj index 09a7cde9d..435c4f50b 100644 --- a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj +++ b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj @@ -573,9 +573,6 @@ Entities\SortOrder.cs - - Entities\SupporterInfo.cs - Entities\TrailerType.cs diff --git a/MediaBrowser.Model/Entities/SupporterInfo.cs b/MediaBrowser.Model/Entities/SupporterInfo.cs deleted file mode 100644 index 233d5615f..000000000 --- a/MediaBrowser.Model/Entities/SupporterInfo.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace MediaBrowser.Model.Entities -{ - public class SupporterInfo - { - public string Email { get; set; } - public string SupporterKey { get; set; } - public DateTime? ExpirationDate { get; set; } - public DateTime RegistrationDate { get; set; } - public string PlanType { get; set; } - public bool IsActiveSupporter { get; set; } - public bool IsExpiredSupporter { get; set; } - } -} \ No newline at end of file diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 1386854bb..3664175d8 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -144,7 +144,6 @@ - diff --git a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs index 9ad04ebbd..af81b4eea 100644 --- a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs +++ b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs @@ -10,6 +10,7 @@ using System.IO; using System.Net; using System.Text; using System.Threading; +using System.Threading.Tasks; using CommonIO; using MediaBrowser.Common.IO; @@ -40,7 +41,7 @@ namespace MediaBrowser.Server.Implementations.Connect public void Run() { - LoadCachedAddress(); + Task.Run(() => LoadCachedAddress()); _timer = new Timer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3)); } diff --git a/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs b/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs index f1de09d56..fdc7e9ee2 100644 --- a/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs +++ b/MediaBrowser.Server.Implementations/Connect/ConnectManager.cs @@ -1073,11 +1073,6 @@ namespace MediaBrowser.Server.Implementations.Connect public async Task GetConnectSupporterSummary() { - if (!_securityManager.IsMBSupporter) - { - return new ConnectSupporterSummary(); - } - var url = GetConnectUrl("keyAssociation"); var options = new HttpRequestOptions @@ -1106,11 +1101,6 @@ namespace MediaBrowser.Server.Implementations.Connect public async Task AddConnectSupporter(string id) { - if (!_securityManager.IsMBSupporter) - { - throw new InvalidOperationException(); - } - var url = GetConnectUrl("keyAssociation"); var options = new HttpRequestOptions @@ -1139,11 +1129,6 @@ namespace MediaBrowser.Server.Implementations.Connect public async Task RemoveConnectSupporter(string id) { - if (!_securityManager.IsMBSupporter) - { - throw new InvalidOperationException(); - } - var url = GetConnectUrl("keyAssociation"); var options = new HttpRequestOptions diff --git a/MediaBrowser.Server.Implementations/EntryPoints/LoadRegistrations.cs b/MediaBrowser.Server.Implementations/EntryPoints/LoadRegistrations.cs index 27170ced9..701cf21fb 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/LoadRegistrations.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/LoadRegistrations.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints /// public void Run() { - _timer = new Timer(s => LoadAllRegistrations(), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromHours(24)); + _timer = new Timer(s => LoadAllRegistrations(), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromHours(12)); } private async Task LoadAllRegistrations() diff --git a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs b/MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs deleted file mode 100644 index 9a20505a5..000000000 --- a/MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs +++ /dev/null @@ -1,148 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.IO; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Notifications; -using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using CommonIO; - -namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications -{ - public class RemoteNotifications : IServerEntryPoint - { - private const string Url = "http://www.mb3admin.com/admin/service/MB3ServerNotifications.json"; - - private Timer _timer; - private readonly IHttpClient _httpClient; - private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; - private readonly IJsonSerializer _json; - private readonly IUserManager _userManager; - private readonly IFileSystem _fileSystem; - - private readonly TimeSpan _frequency = TimeSpan.FromHours(6); - private readonly TimeSpan _maxAge = TimeSpan.FromDays(31); - - private readonly INotificationManager _notificationManager; - - public RemoteNotifications(IApplicationPaths appPaths, ILogger logger, IHttpClient httpClient, IJsonSerializer json, IUserManager userManager, IFileSystem fileSystem, INotificationManager notificationManager) - { - _appPaths = appPaths; - _logger = logger; - _httpClient = httpClient; - _json = json; - _userManager = userManager; - _fileSystem = fileSystem; - _notificationManager = notificationManager; - } - - /// - /// Runs this instance. - /// - public void Run() - { - _timer = new Timer(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency); - } - - /// - /// Called when [timer fired]. - /// - /// The state. - private async void OnTimerFired(object state) - { - var dataPath = Path.Combine(_appPaths.DataPath, "remotenotifications.json"); - - var lastRunTime = _fileSystem.FileExists(dataPath) ? _fileSystem.GetLastWriteTimeUtc(dataPath) : DateTime.MinValue; - - try - { - await DownloadNotifications(dataPath, lastRunTime).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.ErrorException("Error downloading remote notifications", ex); - } - } - - /// - /// Downloads the notifications. - /// - /// The data path. - /// The last run time. - /// Task. - private async Task DownloadNotifications(string dataPath, DateTime lastRunTime) - { - using (var stream = await _httpClient.Get(new HttpRequestOptions - { - Url = Url - - }).ConfigureAwait(false)) - { - var notifications = _json.DeserializeFromStream(stream); - - _fileSystem.WriteAllText(dataPath, string.Empty); - - await CreateNotifications(notifications, lastRunTime).ConfigureAwait(false); - } - } - - /// - /// Creates the notifications. - /// - /// The notifications. - /// The last run time. - /// Task. - private async Task CreateNotifications(IEnumerable notifications, DateTime lastRunTime) - { - // Only show notifications that are active, new since last download, and not older than max age - var notificationList = notifications - .Where(i => string.Equals(i.active, "1") && i.date.ToUniversalTime() > lastRunTime && (DateTime.UtcNow - i.date.ToUniversalTime()) <= _maxAge) - .ToList(); - - var userIds = _userManager.Users.Select(i => i.Id.ToString("N")).ToList(); - - foreach (var notification in notificationList) - { - await _notificationManager.SendNotification(new NotificationRequest - { - Date = notification.date, - Name = notification.name, - Description = notification.description, - Url = notification.url, - UserIds = userIds - - }, CancellationToken.None).ConfigureAwait(false); - } - } - - public void Dispose() - { - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } - } - - private class RemoteNotification - { - public string id { get; set; } - public DateTime date { get; set; } - public string name { get; set; } - public string description { get; set; } - public string category { get; set; } - public string url { get; set; } - public object imageUrl { get; set; } - public string active { get; set; } - } - } -} diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index bec2abdc4..52adae14c 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -131,7 +131,6 @@ - -- cgit v1.2.3 From 82b8d60720e3bb88ccab80099c209c49e0d1502b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 Jan 2016 20:23:09 -0500 Subject: get stable and beta server packages from github --- MediaBrowser.Api/PackageService.cs | 2 +- .../HttpClientManager/HttpClientManager.cs | 2 +- .../MediaBrowser.Common.Implementations.csproj | 2 + .../Updates/GithubUpdater.cs | 195 +++++++++++++++++++++ .../Updates/InstallationManager.cs | 12 +- .../Updates/IInstallationManager.cs | 3 +- .../ScheduledTasks/PluginUpdateTask.cs | 2 +- .../ApplicationHost.cs | 13 +- 8 files changed, 220 insertions(+), 11 deletions(-) create mode 100644 MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/PackageService.cs b/MediaBrowser.Api/PackageService.cs index 4f9efad50..6d8378aae 100644 --- a/MediaBrowser.Api/PackageService.cs +++ b/MediaBrowser.Api/PackageService.cs @@ -233,7 +233,7 @@ namespace MediaBrowser.Api throw new ResourceNotFoundException(string.Format("Package not found: {0}", request.Name)); } - Task.Run(() => _installationManager.InstallPackage(package, new Progress(), CancellationToken.None)); + Task.Run(() => _installationManager.InstallPackage(package, true, new Progress(), CancellationToken.None)); } /// diff --git a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs index 054c5aaaf..c30cdf1a7 100644 --- a/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs +++ b/MediaBrowser.Common.Implementations/HttpClientManager/HttpClientManager.cs @@ -150,7 +150,7 @@ namespace MediaBrowser.Common.Implementations.HttpClientManager request.Method = method; request.Timeout = options.TimeoutMs; - + if (httpWebRequest != null) { if (!string.IsNullOrEmpty(options.Host)) diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index 59e20ec6e..e87a6ad16 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -68,6 +68,7 @@ ..\packages\SimpleInjector.3.1.2\lib\net45\SimpleInjector.dll + @@ -107,6 +108,7 @@ + diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs new file mode 100644 index 000000000..aff3dcf8d --- /dev/null +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Updates; + +namespace MediaBrowser.Common.Implementations.Updates +{ + public class GithubUpdater + { + private readonly IHttpClient _httpClient; + private readonly IJsonSerializer _jsonSerializer; + private TimeSpan _cacheLength; + + public GithubUpdater(IHttpClient httpClient, IJsonSerializer jsonSerializer, TimeSpan cacheLength) + { + _httpClient = httpClient; + _jsonSerializer = jsonSerializer; + _cacheLength = cacheLength; + } + + public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, bool includePrerelease, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) + { + var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository); + + var options = new HttpRequestOptions + { + Url = url, + EnableKeepAlive = false, + CancellationToken = cancellationToken, + UserAgent = "Emby/3.0" + + }; + + if (_cacheLength.Ticks > 0) + { + options.CacheMode = CacheMode.Unconditional; + options.CacheLength = _cacheLength; + } + + using (var stream = await _httpClient.Get(new HttpRequestOptions + { + Url = url, + EnableKeepAlive = false, + CancellationToken = cancellationToken, + UserAgent = "Emby/3.0" + + }).ConfigureAwait(false)) + { + var obj = _jsonSerializer.DeserializeFromStream(stream); + + var availableUpdate = CheckForUpdateResult(obj, minVersion, includePrerelease, assetFilename, packageName, targetFilename); + + return availableUpdate ?? new CheckForUpdateResult + { + IsUpdateAvailable = false + }; + } + } + + private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, bool includePrerelease, string assetFilename, string packageName, string targetFilename) + { + if (!includePrerelease) + { + obj = obj.Where(i => !i.prerelease).ToArray(); + } + + // TODO: + // Filter using name and check for suffixes such as -beta, -dev? + + return obj.Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)).FirstOrDefault(i => i != null); + } + + private CheckForUpdateResult CheckForUpdateResult(RootObject obj, Version minVersion, string assetFilename, string packageName, string targetFilename) + { + Version version; + if (!Version.TryParse(obj.tag_name, out version)) + { + return null; + } + + if (version < minVersion) + { + return null; + } + + var asset = (obj.assets ?? new List()).FirstOrDefault(i => string.Equals(assetFilename, Path.GetFileName(i.browser_download_url), StringComparison.OrdinalIgnoreCase)); + + if (asset == null) + { + return null; + } + + return new CheckForUpdateResult + { + AvailableVersion = version.ToString(), + IsUpdateAvailable = version > minVersion, + Package = new PackageVersionInfo + { + classification = obj.prerelease ? PackageVersionClass.Beta : PackageVersionClass.Release, + name = packageName, + sourceUrl = asset.browser_download_url, + targetFilename = targetFilename, + versionStr = version.ToString(), + requiredVersionStr = "1.0.0" + } + }; + } + + public class Uploader + { + public string login { get; set; } + public int id { get; set; } + public string avatar_url { get; set; } + public string gravatar_id { get; set; } + public string url { get; set; } + public string html_url { get; set; } + public string followers_url { get; set; } + public string following_url { get; set; } + public string gists_url { get; set; } + public string starred_url { get; set; } + public string subscriptions_url { get; set; } + public string organizations_url { get; set; } + public string repos_url { get; set; } + public string events_url { get; set; } + public string received_events_url { get; set; } + public string type { get; set; } + public bool site_admin { get; set; } + } + + public class Asset + { + public string url { get; set; } + public int id { get; set; } + public string name { get; set; } + public object label { get; set; } + public Uploader uploader { get; set; } + public string content_type { get; set; } + public string state { get; set; } + public int size { get; set; } + public int download_count { get; set; } + public string created_at { get; set; } + public string updated_at { get; set; } + public string browser_download_url { get; set; } + } + + public class Author + { + public string login { get; set; } + public int id { get; set; } + public string avatar_url { get; set; } + public string gravatar_id { get; set; } + public string url { get; set; } + public string html_url { get; set; } + public string followers_url { get; set; } + public string following_url { get; set; } + public string gists_url { get; set; } + public string starred_url { get; set; } + public string subscriptions_url { get; set; } + public string organizations_url { get; set; } + public string repos_url { get; set; } + public string events_url { get; set; } + public string received_events_url { get; set; } + public string type { get; set; } + public bool site_admin { get; set; } + } + + public class RootObject + { + public string url { get; set; } + public string assets_url { get; set; } + public string upload_url { get; set; } + public string html_url { get; set; } + public int id { get; set; } + public string tag_name { get; set; } + public string target_commitish { get; set; } + public string name { get; set; } + public bool draft { get; set; } + public Author author { get; set; } + public bool prerelease { get; set; } + public string created_at { get; set; } + public string published_at { get; set; } + public List assets { get; set; } + public string tarball_url { get; set; } + public string zipball_url { get; set; } + public string body { get; set; } + } + } +} diff --git a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs index 014275331..d155f11c7 100644 --- a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs +++ b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs @@ -438,11 +438,12 @@ namespace MediaBrowser.Common.Implementations.Updates /// Installs the package. /// /// The package. + /// if set to true [is plugin]. /// The progress. /// The cancellation token. /// Task. /// package - public async Task InstallPackage(PackageVersionInfo package, IProgress progress, CancellationToken cancellationToken) + public async Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress progress, CancellationToken cancellationToken) { if (package == null) { @@ -495,7 +496,7 @@ namespace MediaBrowser.Common.Implementations.Updates try { - await InstallPackageInternal(package, innerProgress, linkedToken).ConfigureAwait(false); + await InstallPackageInternal(package, isPlugin, innerProgress, linkedToken).ConfigureAwait(false); lock (CurrentInstallations) { @@ -551,18 +552,17 @@ namespace MediaBrowser.Common.Implementations.Updates /// Installs the package internal. /// /// The package. + /// if set to true [is plugin]. /// The progress. /// The cancellation token. /// Task. - private async Task InstallPackageInternal(PackageVersionInfo package, IProgress progress, CancellationToken cancellationToken) + private async Task InstallPackageInternal(PackageVersionInfo package, bool isPlugin, IProgress progress, CancellationToken cancellationToken) { // Do the install await PerformPackageInstallation(progress, package, cancellationToken).ConfigureAwait(false); - var extension = Path.GetExtension(package.targetFilename) ?? ""; - // Do plugin-specific processing - if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".rar", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".7z", StringComparison.OrdinalIgnoreCase)) + if (isPlugin) { // Set last update time if we were installed before var plugin = _applicationHost.Plugins.FirstOrDefault(p => string.Equals(p.Id.ToString(), package.guid, StringComparison.OrdinalIgnoreCase)) diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 7d721da6f..68853f05e 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -105,11 +105,12 @@ namespace MediaBrowser.Common.Updates /// Installs the package. /// /// The package. + /// if set to true [is plugin]. /// The progress. /// The cancellation token. /// Task. /// package - Task InstallPackage(PackageVersionInfo package, IProgress progress, CancellationToken cancellationToken); + Task InstallPackage(PackageVersionInfo package, bool isPlugin, IProgress progress, CancellationToken cancellationToken); /// /// Uninstalls a plugin diff --git a/MediaBrowser.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/MediaBrowser.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs index 96f469f69..457f5a33d 100644 --- a/MediaBrowser.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ b/MediaBrowser.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -72,7 +72,7 @@ namespace MediaBrowser.Server.Implementations.ScheduledTasks try { - await _installationManager.InstallPackage(i, new Progress(), cancellationToken).ConfigureAwait(false); + await _installationManager.InstallPackage(i, true, new Progress(), cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 2bc01ebe1..3690c8f67 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -101,6 +101,7 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Common.Implementations.Updates; namespace MediaBrowser.Server.Startup.Common { @@ -1308,6 +1309,16 @@ namespace MediaBrowser.Server.Startup.Common /// Task{CheckForUpdateResult}. public override async Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) { + if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel != PackageVersionClass.Dev) + { + var includePreRelease = ConfigurationManager.CommonConfiguration.SystemUpdateLevel != PackageVersionClass.Release; + + var cacheLength = TimeSpan.FromHours(1); + + return await new GithubUpdater(HttpClient, JsonSerializer, cacheLength) + .CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, includePreRelease, "emby.windows.zip", "MBServer", "Mbserver.zip", cancellationToken).ConfigureAwait(false); + } + var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false); var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel); @@ -1339,7 +1350,7 @@ namespace MediaBrowser.Server.Startup.Common /// Task. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress progress) { - await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false); + await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false); HasUpdateAvailable = false; -- cgit v1.2.3 From 3560e61596fcb415c7b8f123e33b96a84214c62d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 2 Jan 2016 20:33:44 -0500 Subject: add release description --- MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index aff3dcf8d..b5ccebd2a 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -108,7 +108,8 @@ namespace MediaBrowser.Common.Implementations.Updates sourceUrl = asset.browser_download_url, targetFilename = targetFilename, versionStr = version.ToString(), - requiredVersionStr = "1.0.0" + requiredVersionStr = "1.0.0", + description = obj.body } }; } -- cgit v1.2.3 From 316b7da1a357604d4d935734b91c918d821eb3f2 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 3 Jan 2016 14:01:05 -0500 Subject: update github updater --- .../Updates/GithubUpdater.cs | 11 +++-- MediaBrowser.Server.Mono/Program.cs | 2 +- .../ApplicationHost.cs | 53 ++++++++++------------ MediaBrowser.ServerApplication/MainStartup.cs | 2 +- 4 files changed, 34 insertions(+), 34 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index b5ccebd2a..a6dcc53d0 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Implementations.Updates _cacheLength = cacheLength; } - public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, bool includePrerelease, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) + public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, bool includePrerelease, string[] excludeSuffixes, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) { var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository); @@ -55,7 +55,7 @@ namespace MediaBrowser.Common.Implementations.Updates { var obj = _jsonSerializer.DeserializeFromStream(stream); - var availableUpdate = CheckForUpdateResult(obj, minVersion, includePrerelease, assetFilename, packageName, targetFilename); + var availableUpdate = CheckForUpdateResult(obj, minVersion, includePrerelease, excludeSuffixes, assetFilename, packageName, targetFilename); return availableUpdate ?? new CheckForUpdateResult { @@ -64,13 +64,18 @@ namespace MediaBrowser.Common.Implementations.Updates } } - private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, bool includePrerelease, string assetFilename, string packageName, string targetFilename) + private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, bool includePrerelease, string[] excludeSuffixes, string assetFilename, string packageName, string targetFilename) { if (!includePrerelease) { obj = obj.Where(i => !i.prerelease).ToArray(); } + if (excludeSuffixes.Length > 0) + { + obj = obj.Where(i => !excludeSuffixes.Any(e => i.name.EndsWith(e, StringComparison.OrdinalIgnoreCase))).ToArray(); + } + // TODO: // Filter using name and check for suffixes such as -beta, -dev? diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 69c8201af..bccf6487a 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -82,7 +82,7 @@ namespace MediaBrowser.Server.Mono var nativeApp = new NativeApp(options); - _appHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "MBServer.Mono", nativeApp); + _appHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "emby.mono.zip", nativeApp); if (options.ContainsOption("-v")) { diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 3690c8f67..ea40ffc18 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -207,7 +207,7 @@ namespace MediaBrowser.Server.Startup.Common private IPlaylistManager PlaylistManager { get; set; } private readonly StartupOptions _startupOptions; - private readonly string _remotePackageName; + private readonly string _releaseAssetFilename; internal INativeApp NativeApp { get; set; } private Timer _ipAddressCacheTimer; @@ -219,18 +219,18 @@ namespace MediaBrowser.Server.Startup.Common /// The log manager. /// The options. /// The file system. - /// Name of the remote package. + /// The release asset filename. /// The native application. public ApplicationHost(ServerApplicationPaths applicationPaths, ILogManager logManager, StartupOptions options, IFileSystem fileSystem, - string remotePackageName, + string releaseAssetFilename, INativeApp nativeApp) : base(applicationPaths, logManager, fileSystem) { _startupOptions = options; - _remotePackageName = remotePackageName; + _releaseAssetFilename = releaseAssetFilename; NativeApp = nativeApp; SetBaseExceptionMessage(); @@ -1309,36 +1309,31 @@ namespace MediaBrowser.Server.Startup.Common /// Task{CheckForUpdateResult}. public override async Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) { - if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel != PackageVersionClass.Dev) - { - var includePreRelease = ConfigurationManager.CommonConfiguration.SystemUpdateLevel != PackageVersionClass.Release; - - var cacheLength = TimeSpan.FromHours(1); + var includePreRelease = false; + var cacheLength = TimeSpan.FromHours(12); + var excludeSuffixes = new List(); - return await new GithubUpdater(HttpClient, JsonSerializer, cacheLength) - .CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, includePreRelease, "emby.windows.zip", "MBServer", "Mbserver.zip", cancellationToken).ConfigureAwait(false); + if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Release) + { + // Shouldn't actually be needed due to the prerelease filter + excludeSuffixes.Add("-beta"); + excludeSuffixes.Add("-dev"); } - - var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false); - - var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel); - - var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr); - - var isUpdateAvailable = versionObject != null && versionObject > ApplicationVersion; - - var result = versionObject != null ? - new CheckForUpdateResult { AvailableVersion = versionObject.ToString(), IsUpdateAvailable = isUpdateAvailable, Package = version } : - new CheckForUpdateResult { AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false }; - - HasUpdateAvailable = result.IsUpdateAvailable; - - if (result.IsUpdateAvailable) + else if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Beta) + { + excludeSuffixes.Add("-dev"); + cacheLength = TimeSpan.FromHours(1); + includePreRelease = true; + } + else if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Dev) { - Logger.Info("New application version is available: {0}", result.AvailableVersion); + excludeSuffixes.Add("-dev"); + cacheLength = TimeSpan.FromMinutes(5); + includePreRelease = true; } - return result; + return await new GithubUpdater(HttpClient, JsonSerializer, cacheLength) + .CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, includePreRelease, excludeSuffixes.ToArray(), _releaseAssetFilename, "MBServer", "Mbserver.zip", cancellationToken).ConfigureAwait(false); } /// diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 3fec815f5..69b78e02b 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -225,7 +225,7 @@ namespace MediaBrowser.ServerApplication logManager, options, fileSystem, - "MBServer", + "emby.windows.zip", nativeApp); var initProgress = new Progress(); -- cgit v1.2.3 From 598f79fafe342782c7e0528559a7f8878cbd061c Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 3 Jan 2016 21:31:22 -0500 Subject: update the updater --- .../Updates/GithubUpdater.cs | 41 +++++++++------------- .../ApplicationHost.cs | 20 +++-------- 2 files changed, 21 insertions(+), 40 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index a6dcc53d0..ac7002668 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Implementations.Updates _cacheLength = cacheLength; } - public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, bool includePrerelease, string[] excludeSuffixes, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) + public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, CancellationToken cancellationToken) { var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository); @@ -44,42 +44,31 @@ namespace MediaBrowser.Common.Implementations.Updates options.CacheLength = _cacheLength; } - using (var stream = await _httpClient.Get(new HttpRequestOptions - { - Url = url, - EnableKeepAlive = false, - CancellationToken = cancellationToken, - UserAgent = "Emby/3.0" - - }).ConfigureAwait(false)) + using (var stream = await _httpClient.Get(options).ConfigureAwait(false)) { var obj = _jsonSerializer.DeserializeFromStream(stream); - var availableUpdate = CheckForUpdateResult(obj, minVersion, includePrerelease, excludeSuffixes, assetFilename, packageName, targetFilename); - - return availableUpdate ?? new CheckForUpdateResult - { - IsUpdateAvailable = false - }; + return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); } } - private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, bool includePrerelease, string[] excludeSuffixes, string assetFilename, string packageName, string targetFilename) + private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename) { - if (!includePrerelease) + if (updateLevel == PackageVersionClass.Release) { obj = obj.Where(i => !i.prerelease).ToArray(); } - - if (excludeSuffixes.Length > 0) + else if (updateLevel == PackageVersionClass.Beta) { - obj = obj.Where(i => !excludeSuffixes.Any(e => i.name.EndsWith(e, StringComparison.OrdinalIgnoreCase))).ToArray(); + obj = obj.Where(i => !i.prerelease || !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } - // TODO: - // Filter using name and check for suffixes such as -beta, -dev? - - return obj.Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)).FirstOrDefault(i => i != null); + var availableUpdate = obj.Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)).FirstOrDefault(i => i != null); + + return availableUpdate ?? new CheckForUpdateResult + { + IsUpdateAvailable = false + }; } private CheckForUpdateResult CheckForUpdateResult(RootObject obj, Version minVersion, string assetFilename, string packageName, string targetFilename) @@ -108,7 +97,9 @@ namespace MediaBrowser.Common.Implementations.Updates IsUpdateAvailable = version > minVersion, Package = new PackageVersionInfo { - classification = obj.prerelease ? PackageVersionClass.Beta : PackageVersionClass.Release, + classification = obj.prerelease ? + (obj.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase) ? PackageVersionClass.Dev : PackageVersionClass.Beta) : + PackageVersionClass.Release, name = packageName, sourceUrl = asset.browser_download_url, targetFilename = targetFilename, diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 114b9047a..4fee83d31 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -1309,30 +1309,20 @@ namespace MediaBrowser.Server.Startup.Common /// Task{CheckForUpdateResult}. public override Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) { - var includePreRelease = false; var cacheLength = TimeSpan.FromHours(12); - var excludeSuffixes = new List(); + var updateLevel = ConfigurationManager.CommonConfiguration.SystemUpdateLevel; - if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Release) + if (updateLevel == PackageVersionClass.Beta) { - // Shouldn't actually be needed due to the prerelease filter - excludeSuffixes.Add("-beta"); - excludeSuffixes.Add("-dev"); - } - else if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Beta) - { - excludeSuffixes.Add("-dev"); cacheLength = TimeSpan.FromHours(1); - includePreRelease = true; } - else if (ConfigurationManager.CommonConfiguration.SystemUpdateLevel == PackageVersionClass.Dev) + else if (updateLevel == PackageVersionClass.Dev) { cacheLength = TimeSpan.FromMinutes(5); - includePreRelease = true; } - return new GithubUpdater(HttpClient, JsonSerializer, cacheLength) - .CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, includePreRelease, excludeSuffixes.ToArray(), _releaseAssetFilename, "MBServer", "Mbserver.zip", cancellationToken); + return new GithubUpdater(HttpClient, JsonSerializer, cacheLength).CheckForUpdateResult("MediaBrowser", "Emby", ApplicationVersion, updateLevel, _releaseAssetFilename, + "MBServer", "Mbserver.zip", cancellationToken); } /// -- cgit v1.2.3 From 3788383181c88de3c2c0f72636c9025f76b722b4 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 3 Jan 2016 21:56:43 -0500 Subject: update the updater --- MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index ac7002668..3239d7b95 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -60,7 +60,11 @@ namespace MediaBrowser.Common.Implementations.Updates } else if (updateLevel == PackageVersionClass.Beta) { - obj = obj.Where(i => !i.prerelease || !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); + obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase)).ToArray(); + } + else if (updateLevel == PackageVersionClass.Dev) + { + obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } var availableUpdate = obj.Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)).FirstOrDefault(i => i != null); -- cgit v1.2.3 From 30229982bab747bfa695123038f9c5d90dd5ac9a Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 4 Jan 2016 14:40:59 -0500 Subject: auto install vcredist --- Emby.Drawing/ImageMagick/ImageMagickEncoder.cs | 7 ++- .../BaseApplicationHost.cs | 2 +- MediaBrowser.ServerApplication/MainStartup.cs | 69 ++++++++++++++++++++++ .../MediaBrowser.ServerApplication.csproj | 4 ++ 4 files changed, 80 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs index 5ca674888..12a98edff 100644 --- a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs @@ -72,11 +72,16 @@ namespace Emby.Drawing.ImageMagick private void LogVersion() { - _logger.Info("ImageMagick version: " + Wand.VersionString); + _logger.Info("ImageMagick version: " + GetVersion()); TestWebp(); Wand.SetMagickThreadCount(1); } + public static string GetVersion() + { + return Wand.VersionString; + } + private bool _webpAvailable = true; private void TestWebp() { diff --git a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs index 6dc97100d..2a93efcde 100644 --- a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs +++ b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs @@ -133,7 +133,7 @@ namespace MediaBrowser.Common.Implementations /// Gets the HTTP client. /// /// The HTTP client. - protected IHttpClient HttpClient { get; private set; } + public IHttpClient HttpClient { get; private set; } /// /// Gets the network manager. /// diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 69b78e02b..ac6fd1bbe 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -18,7 +18,9 @@ using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using CommonIO.Windows; +using Emby.Drawing.ImageMagick; using ImageMagickSharp; +using MediaBrowser.Common.Net; using MediaBrowser.Server.Implementations.Logging; namespace MediaBrowser.ServerApplication @@ -251,6 +253,9 @@ namespace MediaBrowser.ServerApplication { Task.WaitAll(task); + task = InstallVcredistIfNeeded(_appHost, _logger); + Task.WaitAll(task); + SystemEvents.SessionEnding += SystemEvents_SessionEnding; SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; @@ -568,6 +573,70 @@ namespace MediaBrowser.ServerApplication } } + private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger) + { + try + { + var version = ImageMagickEncoder.GetVersion(); + return; + } + catch (Exception ex) + { + logger.ErrorException("Error loading ImageMagick", ex); + } + + try + { + await InstallVcredist().ConfigureAwait(false); + } + catch (Exception ex) + { + logger.ErrorException("Error installing ImageMagick", ex); + } + } + + private async static Task InstallVcredist() + { + var httpClient = _appHost.HttpClient; + + var tmp = await httpClient.GetTempFile(new HttpRequestOptions + { + Url = GetVcredistUrl(), + Progress = new Progress() + + }).ConfigureAwait(false); + + var exePath = Path.ChangeExtension(tmp, ".exe"); + File.Copy(tmp, exePath); + + var startInfo = new ProcessStartInfo + { + FileName = exePath, + + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + Verb = "runas", + ErrorDialog = false + }; + + using (var process = Process.Start(startInfo)) + { + process.WaitForExit(); + } + } + + private static string GetVcredistUrl() + { + if (Environment.Is64BitProcess) + { + return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe"; + } + + // TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe + + return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe"; + } + /// /// Sets the error mode. /// diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index ddae4ee5a..e8d5b6d27 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -1055,6 +1055,10 @@ + + {08fff49b-f175-4807-a2b5-73b0ebd9f716} + Emby.Drawing + {4fd51ac5-2c16-4308-a993-c3a84f3b4582} MediaBrowser.Api -- cgit v1.2.3 From 8b93bd6eab948cad24345d0819f53ae2ed2714ca Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 6 Jan 2016 13:16:01 -0500 Subject: update the updater --- .../Updates/GithubUpdater.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index 3239d7b95..599b483fe 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -88,7 +88,7 @@ namespace MediaBrowser.Common.Implementations.Updates return null; } - var asset = (obj.assets ?? new List()).FirstOrDefault(i => string.Equals(assetFilename, Path.GetFileName(i.browser_download_url), StringComparison.OrdinalIgnoreCase)); + var asset = (obj.assets ?? new List()).FirstOrDefault(i => IsAsset(i, assetFilename)); if (asset == null) { @@ -114,6 +114,18 @@ namespace MediaBrowser.Common.Implementations.Updates }; } + private bool IsAsset(Asset asset, string assetFilename) + { + var downloadFilename = Path.GetFileName(asset.browser_download_url) ?? string.Empty; + + if (downloadFilename.IndexOf(assetFilename, StringComparison.OrdinalIgnoreCase) != -1) + { + return true; + } + + return string.Equals(assetFilename, downloadFilename, StringComparison.OrdinalIgnoreCase); + } + public class Uploader { public string login { get; set; } -- cgit v1.2.3 From 0911bebf2289d3014d4798de9917ddbc9a297268 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 6 Jan 2016 22:54:26 -0500 Subject: filter ip addresses --- .../Networking/BaseNetworkManager.cs | 1 + MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs | 40 +++------------------- .../ApplicationHost.cs | 2 +- 3 files changed, 7 insertions(+), 36 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 9b278b889..bc3dc360f 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -231,6 +231,7 @@ namespace MediaBrowser.Common.Implementations.Networking var properties = network.GetIPProperties(); return properties.UnicastAddresses + .Where(i => i.IsDnsEligible) .Select(i => i.Address) .Where(i => i.AddressFamily == AddressFamily.InterNetwork) .ToList(); diff --git a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs index 279979550..ed3698e43 100644 --- a/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs +++ b/MediaBrowser.Dlna/Ssdp/DeviceDiscovery.cs @@ -11,6 +11,7 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Net; using MoreLinq; namespace MediaBrowser.Dlna.Ssdp @@ -27,52 +28,21 @@ namespace MediaBrowser.Dlna.Ssdp public event EventHandler DeviceDiscovered; public event EventHandler DeviceLeft; + private readonly INetworkManager _networkManager; - public DeviceDiscovery(ILogger logger, IServerConfigurationManager config, IServerApplicationHost appHost) + public DeviceDiscovery(ILogger logger, IServerConfigurationManager config, IServerApplicationHost appHost, INetworkManager networkManager) { _tokenSource = new CancellationTokenSource(); _logger = logger; _config = config; _appHost = appHost; + _networkManager = networkManager; } private List GetLocalIpAddresses() { - NetworkInterface[] interfaces; - - try - { - interfaces = NetworkInterface.GetAllNetworkInterfaces(); - } - catch (Exception ex) - { - _logger.ErrorException("Error in GetAllNetworkInterfaces", ex); - return new List(); - } - - return interfaces.SelectMany(network => { - - try - { - _logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); - - var properties = network.GetIPProperties(); - - return properties.UnicastAddresses - .Select(i => i.Address) - .Where(i => i.AddressFamily == AddressFamily.InterNetwork) - .ToList(); - } - catch (Exception ex) - { - _logger.ErrorException("Error querying network interface", ex); - return new List(); - } - - }) - .DistinctBy(i => i.ToString()) - .ToList(); + return _networkManager.GetLocalIpAddresses().ToList(); } public void Start(SsdpHandler ssdpHandler) diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 4fee83d31..29da81e9a 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -522,7 +522,7 @@ namespace MediaBrowser.Server.Startup.Common SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, MediaSourceManager); RegisterSingleInstance(SubtitleManager); - RegisterSingleInstance(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, this)); + RegisterSingleInstance(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, this, NetworkManager)); ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); -- cgit v1.2.3 From 2f56880a0600ec4524d52be05bb978d07c90fd20 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 8 Jan 2016 20:51:51 -0500 Subject: update github updater --- MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs index 599b483fe..360428072 100644 --- a/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common.Implementations/Updates/GithubUpdater.cs @@ -67,7 +67,11 @@ namespace MediaBrowser.Common.Implementations.Updates obj = obj.Where(i => !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); } - var availableUpdate = obj.Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)).FirstOrDefault(i => i != null); + var availableUpdate = obj + .Select(i => CheckForUpdateResult(i, minVersion, assetFilename, packageName, targetFilename)) + .Where(i => i != null) + .OrderByDescending(i => Version.Parse(i.AvailableVersion)) + .FirstOrDefault(); return availableUpdate ?? new CheckForUpdateResult { -- cgit v1.2.3 From b501d66fa8b57eefd1c61e8388d5f0b91b34fe92 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 12 Jan 2016 15:12:50 -0500 Subject: add error handling to package retrieval --- .../Updates/InstallationManager.cs | 39 +++++++++++----------- 1 file changed, 19 insertions(+), 20 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs index d155f11c7..8e0df9005 100644 --- a/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs +++ b/MediaBrowser.Common.Implementations/Updates/InstallationManager.cs @@ -194,37 +194,36 @@ namespace MediaBrowser.Common.Implementations.Updates /// Task{List{PackageInfo}}. public async Task> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken) { - using (var stream = await GetCachedPackages(cancellationToken).ConfigureAwait(false)) + try { - var packages = _jsonSerializer.DeserializeFromStream>(stream).ToList(); - - if ((DateTime.UtcNow - _lastPackageUpdateTime) > GetCacheLength()) + using (var stream = _fileSystem.OpenRead(PackageCachePath)) { - UpdateCachedPackages(CancellationToken.None, false); - } - - return packages; - } - } + var packages = _jsonSerializer.DeserializeFromStream>(stream).ToList(); - private string PackageCachePath - { - get { return Path.Combine(_appPaths.CachePath, "serverpackages.json"); } - } + if ((DateTime.UtcNow - _lastPackageUpdateTime) > GetCacheLength()) + { + UpdateCachedPackages(CancellationToken.None, false); + } - private async Task GetCachedPackages(CancellationToken cancellationToken) - { - try - { - return _fileSystem.OpenRead(PackageCachePath); + return packages; + } } catch (Exception) { } + _lastPackageUpdateTime = DateTime.MinValue; await UpdateCachedPackages(cancellationToken, true).ConfigureAwait(false); - return _fileSystem.OpenRead(PackageCachePath); + using (var stream = _fileSystem.OpenRead(PackageCachePath)) + { + return _jsonSerializer.DeserializeFromStream>(stream).ToList(); + } + } + + private string PackageCachePath + { + get { return Path.Combine(_appPaths.CachePath, "serverpackages.json"); } } private readonly SemaphoreSlim _updateSemaphore = new SemaphoreSlim(1, 1); -- cgit v1.2.3 From 0cd008bcb9e92e2dd74be58bf3566872ad8fb9ef Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 16 Jan 2016 22:24:24 -0500 Subject: update commonio --- Emby.Drawing/Emby.Drawing.csproj | 2 +- Emby.Drawing/packages.config | 2 +- MediaBrowser.Api/MediaBrowser.Api.csproj | 2 +- MediaBrowser.Api/packages.config | 2 +- .../MediaBrowser.Common.Implementations.csproj | 2 +- MediaBrowser.Common.Implementations/packages.config | 2 +- MediaBrowser.Controller/MediaBrowser.Controller.csproj | 2 +- MediaBrowser.Controller/packages.config | 2 +- MediaBrowser.Dlna/MediaBrowser.Dlna.csproj | 2 +- MediaBrowser.Dlna/packages.config | 2 +- MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj | 2 +- MediaBrowser.LocalMetadata/packages.config | 2 +- MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj | 2 +- MediaBrowser.MediaEncoding/packages.config | 2 +- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 2 +- MediaBrowser.Providers/packages.config | 2 +- .../MediaBrowser.Server.Implementations.csproj | 2 +- MediaBrowser.Server.Implementations/packages.config | 2 +- MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj | 2 +- MediaBrowser.Server.Mono/packages.config | 2 +- .../MediaBrowser.Server.Startup.Common.csproj | 2 +- MediaBrowser.Server.Startup.Common/packages.config | 2 +- MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj | 2 +- MediaBrowser.ServerApplication/packages.config | 2 +- MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj | 2 +- MediaBrowser.WebDashboard/packages.config | 2 +- MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj | 2 +- MediaBrowser.XbmcMetadata/packages.config | 2 +- 28 files changed, 28 insertions(+), 28 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 6cda8b5d0..45ac97ecc 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -33,7 +33,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll False diff --git a/Emby.Drawing/packages.config b/Emby.Drawing/packages.config index 3b8dbcab7..51731c474 100644 --- a/Emby.Drawing/packages.config +++ b/Emby.Drawing/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index 08b99d5a4..7e55446ae 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -47,7 +47,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Api/packages.config b/MediaBrowser.Api/packages.config index 258a097cd..83890e697 100644 --- a/MediaBrowser.Api/packages.config +++ b/MediaBrowser.Api/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj index e87a6ad16..cb3a284c1 100644 --- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj +++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj @@ -49,7 +49,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Common.Implementations/packages.config b/MediaBrowser.Common.Implementations/packages.config index 84f663268..14f0f4719 100644 --- a/MediaBrowser.Common.Implementations/packages.config +++ b/MediaBrowser.Common.Implementations/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index a32ffdb3b..774e51bd3 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -46,7 +46,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll diff --git a/MediaBrowser.Controller/packages.config b/MediaBrowser.Controller/packages.config index 90b347929..8439bee10 100644 --- a/MediaBrowser.Controller/packages.config +++ b/MediaBrowser.Controller/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj index db69a45c8..2d672ee87 100644 --- a/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj +++ b/MediaBrowser.Dlna/MediaBrowser.Dlna.csproj @@ -42,7 +42,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Dlna/packages.config b/MediaBrowser.Dlna/packages.config index 258a097cd..83890e697 100644 --- a/MediaBrowser.Dlna/packages.config +++ b/MediaBrowser.Dlna/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index 5ef8eaaa3..c673c01df 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -33,7 +33,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll diff --git a/MediaBrowser.LocalMetadata/packages.config b/MediaBrowser.LocalMetadata/packages.config index fad6af08e..28556744d 100644 --- a/MediaBrowser.LocalMetadata/packages.config +++ b/MediaBrowser.LocalMetadata/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index df5ab4651..69f6186c7 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -41,7 +41,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\DvdLib.dll diff --git a/MediaBrowser.MediaEncoding/packages.config b/MediaBrowser.MediaEncoding/packages.config index e8a1767e3..d6a4fc90f 100644 --- a/MediaBrowser.MediaEncoding/packages.config +++ b/MediaBrowser.MediaEncoding/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 89bed8849..24397dd5a 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -50,7 +50,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll False diff --git a/MediaBrowser.Providers/packages.config b/MediaBrowser.Providers/packages.config index 9002f1a40..08f8ef3b0 100644 --- a/MediaBrowser.Providers/packages.config +++ b/MediaBrowser.Providers/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index c5b6c1c42..e5c94a01b 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -43,7 +43,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index aac5951b5..5c04f2782 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj b/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj index e9f631bf3..9f36599fa 100644 --- a/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj +++ b/MediaBrowser.Server.Mono/MediaBrowser.Server.Mono.csproj @@ -54,7 +54,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll False diff --git a/MediaBrowser.Server.Mono/packages.config b/MediaBrowser.Server.Mono/packages.config index 6a2a6c1e5..2956d69c6 100644 --- a/MediaBrowser.Server.Mono/packages.config +++ b/MediaBrowser.Server.Mono/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj index b3865eadf..a4028d5b0 100644 --- a/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj +++ b/MediaBrowser.Server.Startup.Common/MediaBrowser.Server.Startup.Common.csproj @@ -33,7 +33,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll False diff --git a/MediaBrowser.Server.Startup.Common/packages.config b/MediaBrowser.Server.Startup.Common/packages.config index 6a2a6c1e5..2956d69c6 100644 --- a/MediaBrowser.Server.Startup.Common/packages.config +++ b/MediaBrowser.Server.Startup.Common/packages.config @@ -1,6 +1,6 @@  - + \ No newline at end of file diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index e8d5b6d27..3e62f4735 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -63,7 +63,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll False diff --git a/MediaBrowser.ServerApplication/packages.config b/MediaBrowser.ServerApplication/packages.config index 3ea97a30e..db2bb5476 100644 --- a/MediaBrowser.ServerApplication/packages.config +++ b/MediaBrowser.ServerApplication/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index 16f5ffeab..48a8bf253 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -49,7 +49,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll diff --git a/MediaBrowser.WebDashboard/packages.config b/MediaBrowser.WebDashboard/packages.config index 24a8a5316..128a2f162 100644 --- a/MediaBrowser.WebDashboard/packages.config +++ b/MediaBrowser.WebDashboard/packages.config @@ -1,6 +1,6 @@  - + diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 353fe31ca..16b6ca995 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -33,7 +33,7 @@ False - ..\packages\CommonIO.1.0.0.5\lib\net45\CommonIO.dll + ..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll ..\packages\Patterns.Logging.1.0.0.2\lib\portable-net45+sl4+wp71+win8+wpa81\Patterns.Logging.dll diff --git a/MediaBrowser.XbmcMetadata/packages.config b/MediaBrowser.XbmcMetadata/packages.config index fad6af08e..28556744d 100644 --- a/MediaBrowser.XbmcMetadata/packages.config +++ b/MediaBrowser.XbmcMetadata/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file -- cgit v1.2.3 From 53f2d7cd701196e1185cfabb3dcfae01b69a8554 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 21 Jan 2016 15:40:20 -0500 Subject: disable http compression --- .../Security/PluginSecurityManager.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index d8f350207..a6dbf77e9 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -258,7 +258,17 @@ namespace MediaBrowser.Common.Implementations.Security try { - using (var json = await _httpClient.Post(MBValidateUrl, data, CancellationToken.None).ConfigureAwait(false)) + var options = new HttpRequestOptions + { + Url = MBValidateUrl, + + // Seeing block length errors + EnableHttpCompression = false + }; + + options.SetPostData(data); + + using (var json = (await _httpClient.Post(options).ConfigureAwait(false)).Content) { reg = _jsonSerializer.DeserializeFromStream(json); success = true; -- cgit v1.2.3 From 3510ef3d2beb810c87f8f3d52f95b95110e574d0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 28 Jan 2016 22:40:21 -0500 Subject: reduce use of timers throughout the system --- .../Networking/BaseNetworkManager.cs | 15 ++--- MediaBrowser.Common/MediaBrowser.Common.csproj | 1 + MediaBrowser.Common/Threading/PeriodicTimer.cs | 67 ++++++++++++++++++++++ .../People/MovieDbPersonProvider.cs | 18 +++--- .../Channels/ChannelManager.cs | 61 +------------------- .../Connect/ConnectEntryPoint.cs | 5 +- .../EntryPoints/ExternalPortForwarding.cs | 5 +- .../EntryPoints/UsageEntryPoint.cs | 16 ++---- 8 files changed, 97 insertions(+), 91 deletions(-) create mode 100644 MediaBrowser.Common/Threading/PeriodicTimer.cs (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index bc3dc360f..527a5fb3e 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; -using System.Threading; using MoreLinq; namespace MediaBrowser.Common.Implementations.Networking @@ -14,14 +13,11 @@ namespace MediaBrowser.Common.Implementations.Networking public abstract class BaseNetworkManager { protected ILogger Logger { get; private set; } - private Timer _clearCacheTimer; + private DateTime _lastRefresh; protected BaseNetworkManager(ILogger logger) { Logger = logger; - - // Can't use network change events due to a crash in Linux - _clearCacheTimer = new Timer(ClearCacheTimerCallback, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); } private void ClearCacheTimerCallback(object state) @@ -41,15 +37,20 @@ namespace MediaBrowser.Common.Implementations.Networking /// IPAddress. public IEnumerable GetLocalIpAddresses() { - if (_localIpAddresses == null) + var forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= 1; + + if (_localIpAddresses == null || forceRefresh) { lock (_localIpAddressSyncLock) { - if (_localIpAddresses == null) + forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= 1; + + if (_localIpAddresses == null || forceRefresh) { var addresses = GetLocalIpAddressesInternal().ToList(); _localIpAddresses = addresses; + _lastRefresh = DateTime.UtcNow; return addresses; } diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index ccdb319fe..17f211d84 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -90,6 +90,7 @@ + diff --git a/MediaBrowser.Common/Threading/PeriodicTimer.cs b/MediaBrowser.Common/Threading/PeriodicTimer.cs new file mode 100644 index 000000000..cb562a80d --- /dev/null +++ b/MediaBrowser.Common/Threading/PeriodicTimer.cs @@ -0,0 +1,67 @@ +using System; +using System.Threading; +using Microsoft.Win32; + +namespace MediaBrowser.Common.Threading +{ + public class PeriodicTimer : IDisposable + { + public Action Callback { get; set; } + private Timer _timer; + private readonly object _state; + private readonly object _timerLock = new object(); + private readonly TimeSpan _period; + + public PeriodicTimer(Action callback, object state, TimeSpan dueTime, TimeSpan period) + { + Callback = callback; + _period = period; + _state = state; + + StartTimer(dueTime); + } + + void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) + { + if (e.Mode == PowerModes.Resume) + { + DisposeTimer(); + StartTimer(Timeout.InfiniteTimeSpan); + } + } + + private void TimerCallback(object state) + { + Callback(state); + } + + private void StartTimer(TimeSpan dueTime) + { + lock (_timerLock) + { + _timer = new Timer(TimerCallback, _state, dueTime, _period); + + SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; + } + } + + private void DisposeTimer() + { + SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged; + + lock (_timerLock) + { + if (_timer != null) + { + _timer.Dispose(); + _timer = null; + } + } + } + + public void Dispose() + { + DisposeTimer(); + } + } +} diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs index 5c5919709..14304c2eb 100644 --- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs +++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Providers.People private int _requestCount; private readonly object _requestCountLock = new object(); - private Timer _requestCountReset; + private DateTime _lastRequestCountReset; public MovieDbPersonProvider(IFileSystem fileSystem, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogger logger) { @@ -48,16 +48,6 @@ namespace MediaBrowser.Providers.People _httpClient = httpClient; _logger = logger; Current = this; - - _requestCountReset = new Timer(OnRequestThrottleTimerFired, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); - } - - private void OnRequestThrottleTimerFired(object state) - { - lock (_requestCountLock) - { - _requestCount = 0; - } } public string Name @@ -101,6 +91,12 @@ namespace MediaBrowser.Providers.People { lock (_requestCountLock) { + if ((DateTime.UtcNow - _lastRequestCountReset).TotalHours >= 1) + { + _requestCount = 0; + _lastRequestCountReset = DateTime.UtcNow; + } + var requestCount = _requestCount; if (requestCount >= 5) diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs index fe13d8cef..c7865b6aa 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs @@ -29,7 +29,7 @@ using CommonIO; namespace MediaBrowser.Server.Implementations.Channels { - public class ChannelManager : IChannelManager, IDisposable + public class ChannelManager : IChannelManager { private IChannel[] _channels; @@ -47,11 +47,6 @@ namespace MediaBrowser.Server.Implementations.Channels private readonly ILocalizationManager _localization; private readonly ConcurrentDictionary _refreshedItems = new ConcurrentDictionary(); - private readonly ConcurrentDictionary _downloadCounts = new ConcurrentDictionary(); - - private Timer _refreshTimer; - private Timer _clearDownloadCountsTimer; - public ChannelManager(IUserManager userManager, IDtoService dtoService, ILibraryManager libraryManager, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IUserDataManager userDataManager, IJsonSerializer jsonSerializer, ILocalizationManager localization, IHttpClient httpClient, IProviderManager providerManager) { _userManager = userManager; @@ -65,9 +60,6 @@ namespace MediaBrowser.Server.Implementations.Channels _localization = localization; _httpClient = httpClient; _providerManager = providerManager; - - _refreshTimer = new Timer(s => _refreshedItems.Clear(), null, TimeSpan.FromHours(3), TimeSpan.FromHours(3)); - _clearDownloadCountsTimer = new Timer(s => _downloadCounts.Clear(), null, TimeSpan.FromHours(24), TimeSpan.FromHours(24)); } private TimeSpan CacheLength @@ -211,6 +203,8 @@ namespace MediaBrowser.Server.Implementations.Channels public async Task RefreshChannels(IProgress progress, CancellationToken cancellationToken) { + _refreshedItems.Clear(); + var allChannelsList = GetAllChannels().ToList(); var numComplete = 0; @@ -1487,12 +1481,6 @@ namespace MediaBrowser.Server.Implementations.Channels var limit = features.DailyDownloadLimit; - if (!ValidateDownloadLimit(host, limit)) - { - _logger.Error(string.Format("Download limit has been reached for {0}", channel.Name)); - throw new ChannelDownloadException(string.Format("Download limit has been reached for {0}", channel.Name)); - } - foreach (var header in source.RequiredHttpHeaders) { options.RequestHeaders[header.Key] = header.Value; @@ -1511,8 +1499,6 @@ namespace MediaBrowser.Server.Implementations.Channels }; } - IncrementDownloadCount(host, limit); - if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase) && response.ContentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase)) { var extension = response.ContentType.Split('/') @@ -1547,46 +1533,5 @@ namespace MediaBrowser.Server.Implementations.Channels } } - - private void IncrementDownloadCount(string key, int? limit) - { - if (!limit.HasValue) - { - return; - } - - int current; - _downloadCounts.TryGetValue(key, out current); - - current++; - _downloadCounts.AddOrUpdate(key, current, (k, v) => current); - } - - private bool ValidateDownloadLimit(string key, int? limit) - { - if (!limit.HasValue) - { - return true; - } - - int current; - _downloadCounts.TryGetValue(key, out current); - - return current < limit.Value; - } - - public void Dispose() - { - if (_clearDownloadCountsTimer != null) - { - _clearDownloadCountsTimer.Dispose(); - _clearDownloadCountsTimer = null; - } - if (_refreshTimer != null) - { - _refreshTimer.Dispose(); - _refreshTimer = null; - } - } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs index 6dab136a5..0d6b8ac26 100644 --- a/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs +++ b/MediaBrowser.Server.Implementations/Connect/ConnectEntryPoint.cs @@ -13,12 +13,13 @@ using System.Threading; using System.Threading.Tasks; using CommonIO; using MediaBrowser.Common.IO; +using MediaBrowser.Common.Threading; namespace MediaBrowser.Server.Implementations.Connect { public class ConnectEntryPoint : IServerEntryPoint { - private Timer _timer; + private PeriodicTimer _timer; private readonly IHttpClient _httpClient; private readonly IApplicationPaths _appPaths; private readonly ILogger _logger; @@ -43,7 +44,7 @@ namespace MediaBrowser.Server.Implementations.Connect { Task.Run(() => LoadCachedAddress()); - _timer = new Timer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3)); + _timer = new PeriodicTimer(null, new TimerCallback(TimerCallback), TimeSpan.FromSeconds(5), TimeSpan.FromHours(3)); } private readonly string[] _ipLookups = { "http://bot.whatismyipaddress.com", "https://connect.emby.media/service/ip" }; diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index a2ffa9aff..2b2c338dd 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -11,6 +11,7 @@ using System.IO; using System.Net; using System.Text; using System.Threading; +using MediaBrowser.Common.Threading; namespace MediaBrowser.Server.Implementations.EntryPoints { @@ -21,7 +22,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints private readonly IServerConfigurationManager _config; private readonly ISsdpHandler _ssdp; - private Timer _timer; + private PeriodicTimer _timer; private bool _isStarted; public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, ISsdpHandler ssdp) @@ -95,7 +96,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints NatUtility.UnhandledException += NatUtility_UnhandledException; NatUtility.StartDiscovery(); - _timer = new Timer(s => _createdRules = new List(), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); + _timer = new PeriodicTimer(s => _createdRules = new List(), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); _ssdp.MessageReceived += _ssdp_MessageReceived; diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs index c3b9c0d4d..d8aef909b 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/UsageEntryPoint.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; +using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.EntryPoints { @@ -23,7 +24,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints private readonly ISessionManager _sessionManager; private readonly IUserManager _userManager; - private Timer _timer; private readonly TimeSpan _frequency = TimeSpan.FromHours(24); private readonly ConcurrentDictionary _apps = new ConcurrentDictionary(); @@ -95,16 +95,16 @@ namespace MediaBrowser.Server.Implementations.EntryPoints return info; } - public void Run() + public async void Run() { - _timer = new Timer(OnTimerFired, null, TimeSpan.FromMilliseconds(5000), _frequency); + await Task.Delay(5000).ConfigureAwait(false); + OnTimerFired(); } /// /// Called when [timer fired]. /// - /// The state. - private async void OnTimerFired(object state) + private async void OnTimerFired() { try { @@ -121,12 +121,6 @@ namespace MediaBrowser.Server.Implementations.EntryPoints public void Dispose() { _sessionManager.SessionStarted -= _sessionManager_SessionStarted; - - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } } } } -- cgit v1.2.3 From 4774a2cc4037b76af7784aa6470d63aa579457a3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 28 Jan 2016 22:45:29 -0500 Subject: update network cache --- .../Networking/BaseNetworkManager.cs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs index 527a5fb3e..ff11c889a 100644 --- a/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs +++ b/MediaBrowser.Common.Implementations/Networking/BaseNetworkManager.cs @@ -20,14 +20,6 @@ namespace MediaBrowser.Common.Implementations.Networking Logger = logger; } - private void ClearCacheTimerCallback(object state) - { - lock (_localIpAddressSyncLock) - { - _localIpAddresses = null; - } - } - private volatile List _localIpAddresses; private readonly object _localIpAddressSyncLock = new object(); @@ -37,13 +29,14 @@ namespace MediaBrowser.Common.Implementations.Networking /// IPAddress. public IEnumerable GetLocalIpAddresses() { - var forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= 1; + const int cacheMinutes = 3; + var forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= cacheMinutes; if (_localIpAddresses == null || forceRefresh) { lock (_localIpAddressSyncLock) { - forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= 1; + forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= cacheMinutes; if (_localIpAddresses == null || forceRefresh) { -- cgit v1.2.3 From fb91b7c808a6348529b4115d2e51c3db400e8d89 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 31 Jan 2016 19:57:40 -0500 Subject: update locking --- .../ScheduledTasks/ScheduledTaskWorker.cs | 8 ++++---- MediaBrowser.Controller/Entities/User.cs | 4 ++-- MediaBrowser.Server.Implementations/Library/LibraryManager.cs | 4 ++-- MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 6 +++++- .../LiveTv/EmbyTV/ItemDataProvider.cs | 2 +- 5 files changed, 14 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 95f29915d..a4ccbb6f8 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -233,7 +233,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// /// The _triggers /// - private IEnumerable _triggers; + private volatile List _triggers; /// /// The _triggers sync lock /// @@ -532,7 +532,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// Loads the triggers. /// /// IEnumerable{BaseTaskTrigger}. - private IEnumerable LoadTriggers() + private List LoadTriggers() { try { @@ -543,12 +543,12 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks catch (FileNotFoundException) { // File doesn't exist. No biggie. Return defaults. - return ScheduledTask.GetDefaultTriggers(); + return ScheduledTask.GetDefaultTriggers().ToList(); } catch (DirectoryNotFoundException) { // File doesn't exist. No biggie. Return defaults. - return ScheduledTask.GetDefaultTriggers(); + return ScheduledTask.GetDefaultTriggers().ToList(); } } diff --git a/MediaBrowser.Controller/Entities/User.cs b/MediaBrowser.Controller/Entities/User.cs index 976c6827f..6c9266d74 100644 --- a/MediaBrowser.Controller/Entities/User.cs +++ b/MediaBrowser.Controller/Entities/User.cs @@ -128,7 +128,7 @@ namespace MediaBrowser.Controller.Entities /// The last activity date. public DateTime? LastActivityDate { get; set; } - private UserConfiguration _config; + private volatile UserConfiguration _config; private readonly object _configSyncLock = new object(); [IgnoreDataMember] public UserConfiguration Configuration @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.Entities set { _config = value; } } - private UserPolicy _policy; + private volatile UserPolicy _policy; private readonly object _policySyncLock = new object(); [IgnoreDataMember] public UserPolicy Policy diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index e0e44f01f..14b608006 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -226,7 +226,7 @@ namespace MediaBrowser.Server.Implementations.Library /// /// The _root folder /// - private AggregateFolder _rootFolder; + private volatile AggregateFolder _rootFolder; /// /// The _root folder sync lock /// @@ -759,7 +759,7 @@ namespace MediaBrowser.Server.Implementations.Library return rootFolder; } - private UserRootFolder _userRootFolder; + private volatile UserRootFolder _userRootFolder; private readonly object _syncLock = new object(); public Folder GetUserRootFolder() { diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index ea64950ab..cd91684ce 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -239,7 +239,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken) { - var timers = _timerProvider.GetAll().Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase)); + var timers = _timerProvider + .GetAll() + .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase)) + .ToList(); + foreach (var timer in timers) { CancelTimerInternal(timer.Id); diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index f46daa6d5..b29a7562c 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -13,7 +13,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV where T : class { private readonly object _fileDataLock = new object(); - private List _items; + private volatile List _items; private readonly IJsonSerializer _jsonSerializer; protected readonly ILogger Logger; private readonly string _dataPath; -- cgit v1.2.3 From 6cb1f77789171f4be7a4c6cd9e075eb4e8b6eff0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 3 Feb 2016 15:52:45 -0500 Subject: update upgrade process --- .../BaseApplicationHost.cs | 6 +-- .../ScheduledTasks/TaskManager.cs | 53 +++++++++++++++++++++- MediaBrowser.Common/ScheduledTasks/ITaskManager.cs | 5 ++ .../Persistence/CleanDatabaseScheduledTask.cs | 16 ++++--- .../ApplicationHost.cs | 5 ++ .../Migrations/DbMigration.cs | 3 +- 6 files changed, 76 insertions(+), 12 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs index 2a93efcde..caf8f54a6 100644 --- a/MediaBrowser.Common.Implementations/BaseApplicationHost.cs +++ b/MediaBrowser.Common.Implementations/BaseApplicationHost.cs @@ -453,7 +453,7 @@ namespace MediaBrowser.Common.Implementations RegisterSingleInstance(ApplicationPaths); - TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, Logger, FileSystemManager); + TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager); RegisterSingleInstance(JsonSerializer); RegisterSingleInstance(XmlSerializer); @@ -465,7 +465,7 @@ namespace MediaBrowser.Common.Implementations RegisterSingleInstance(FileSystemManager); - HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, Logger, FileSystemManager); + HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager); RegisterSingleInstance(HttpClient); NetworkManager = CreateNetworkManager(LogManager.GetLogger("NetworkManager")); @@ -474,7 +474,7 @@ namespace MediaBrowser.Common.Implementations SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager); RegisterSingleInstance(SecurityManager); - InstallationManager = new InstallationManager(Logger, this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager); + InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ConfigurationManager, FileSystemManager); RegisterSingleInstance(InstallationManager); ZipClient = new ZipClient(FileSystemManager); diff --git a/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs b/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs index 845c984fb..b5566650c 100644 --- a/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs +++ b/MediaBrowser.Common.Implementations/ScheduledTasks/TaskManager.cs @@ -55,6 +55,25 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks private ILogger Logger { get; set; } private readonly IFileSystem _fileSystem; + private bool _suspendTriggers; + + public bool SuspendTriggers + { + get { return _suspendTriggers; } + set + { + Logger.Info("Setting SuspendTriggers to {0}", value); + var executeQueued = _suspendTriggers && !value; + + _suspendTriggers = value; + + if (executeQueued) + { + ExecuteQueuedTasks(); + } + } + } + /// /// Initializes a new instance of the class. /// @@ -151,6 +170,31 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks QueueScheduledTask(new TaskExecutionOptions()); } + public void Execute() + where T : IScheduledTask + { + var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == typeof(T)); + + if (scheduledTask == null) + { + Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); + } + else + { + var type = scheduledTask.ScheduledTask.GetType(); + + Logger.Info("Queueing task {0}", type.Name); + + lock (_taskQueue) + { + if (scheduledTask.State == TaskState.Idle) + { + Execute(scheduledTask, new TaskExecutionOptions()); + } + } + } + } + /// /// Queues the scheduled task. /// @@ -183,7 +227,7 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks lock (_taskQueue) { - if (task.State == TaskState.Idle) + if (task.State == TaskState.Idle && !SuspendTriggers) { Execute(task, options); return; @@ -273,6 +317,13 @@ namespace MediaBrowser.Common.Implementations.ScheduledTasks /// private void ExecuteQueuedTasks() { + if (SuspendTriggers) + { + return; + } + + Logger.Info("ExecuteQueuedTasks"); + // Execute queued tasks lock (_taskQueue) { diff --git a/MediaBrowser.Common/ScheduledTasks/ITaskManager.cs b/MediaBrowser.Common/ScheduledTasks/ITaskManager.cs index 8d271859e..c1dc304f6 100644 --- a/MediaBrowser.Common/ScheduledTasks/ITaskManager.cs +++ b/MediaBrowser.Common/ScheduledTasks/ITaskManager.cs @@ -66,7 +66,12 @@ namespace MediaBrowser.Common.ScheduledTasks void Cancel(IScheduledTaskWorker task); Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options = null); + void Execute() + where T : IScheduledTask; + event EventHandler> TaskExecuting; event EventHandler TaskCompleted; + + bool SuspendTriggers { get; set; } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs index 26de52560..76a6e6d40 100644 --- a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs +++ b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Server.Implementations.Persistence private readonly ILocalizationManager _localization; private readonly ITaskManager _taskManager; - public const int MigrationVersion = 12; + public const int MigrationVersion = 17; public static bool EnableUnavailableMessage = false; public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager) @@ -97,12 +97,20 @@ namespace MediaBrowser.Server.Implementations.Persistence await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false); + if (_config.Configuration.MigrationVersion < MigrationVersion) + { + _config.Configuration.MigrationVersion = MigrationVersion; + _config.SaveConfiguration(); + } + if (EnableUnavailableMessage) { EnableUnavailableMessage = false; _httpServer.GlobalResponse = null; _taskManager.QueueScheduledTask(); } + + _taskManager.SuspendTriggers = false; } private void OnProgress(double newPercentCommplete) @@ -164,12 +172,6 @@ namespace MediaBrowser.Server.Implementations.Persistence progress.Report(percent * 100); } - if (_config.Configuration.MigrationVersion < MigrationVersion) - { - _config.Configuration.MigrationVersion = MigrationVersion; - _config.SaveConfiguration(); - } - progress.Report(100); } diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index f75aeebdd..7f79653af 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -317,6 +317,11 @@ namespace MediaBrowser.Server.Startup.Common /// Task. public override async Task RunStartupTasks() { + if (ServerConfigurationManager.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion) + { + TaskManager.SuspendTriggers = true; + } + await base.RunStartupTasks().ConfigureAwait(false); Logger.Info("ServerId: {0}", SystemId); diff --git a/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs index 1df49845b..959543893 100644 --- a/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs +++ b/MediaBrowser.Server.Startup.Common/Migrations/DbMigration.cs @@ -20,13 +20,14 @@ namespace MediaBrowser.Server.Startup.Common.Migrations { if (_config.Configuration.MigrationVersion < CleanDatabaseScheduledTask.MigrationVersion) { + _taskManager.SuspendTriggers = true; CleanDatabaseScheduledTask.EnableUnavailableMessage = true; Task.Run(async () => { await Task.Delay(1000).ConfigureAwait(false); - _taskManager.QueueScheduledTask(); + _taskManager.Execute(); }); } } -- cgit v1.2.3 From de39408217b249102e38b8ef604d1777c090d86b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 9 Feb 2016 12:13:50 -0500 Subject: update person editor --- MediaBrowser.Api/PackageReviewService.cs | 2 +- MediaBrowser.Common.Implementations/Security/MbAdmin.cs | 4 ++-- MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs | 2 +- MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs | 2 +- MediaBrowser.Server.Startup.Common/ApplicationHost.cs | 4 ---- 5 files changed, 5 insertions(+), 9 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Api/PackageReviewService.cs b/MediaBrowser.Api/PackageReviewService.cs index b4656b83e..e70d6a713 100644 --- a/MediaBrowser.Api/PackageReviewService.cs +++ b/MediaBrowser.Api/PackageReviewService.cs @@ -102,7 +102,7 @@ namespace MediaBrowser.Api { private readonly IHttpClient _httpClient; private readonly IJsonSerializer _serializer; - private const string MbAdminUrl = "http://www.mb3admin.com/admin/"; + private const string MbAdminUrl = "https://www.mb3admin.com/admin/"; private readonly IServerApplicationHost _appHost; public PackageReviewService(IHttpClient httpClient, IJsonSerializer serializer, IServerApplicationHost appHost) diff --git a/MediaBrowser.Common.Implementations/Security/MbAdmin.cs b/MediaBrowser.Common.Implementations/Security/MbAdmin.cs index ab4a83257..76ff92c2e 100644 --- a/MediaBrowser.Common.Implementations/Security/MbAdmin.cs +++ b/MediaBrowser.Common.Implementations/Security/MbAdmin.cs @@ -3,11 +3,11 @@ namespace MediaBrowser.Common.Implementations.Security { public class MbAdmin { - public const string HttpUrl = "http://www.mb3admin.com/admin/"; + public const string HttpUrl = "https://www.mb3admin.com/admin/"; /// /// Leaving as http for now until we get it squared away /// - public const string HttpsUrl = "http://www.mb3admin.com/admin/"; + public const string HttpsUrl = "https://www.mb3admin.com/admin/"; } } diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index a6dbf77e9..d751083f0 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -21,7 +21,7 @@ namespace MediaBrowser.Common.Implementations.Security public class PluginSecurityManager : ISecurityManager { private const string MBValidateUrl = MbAdmin.HttpsUrl + "service/registration/validate"; - private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/admin/service/appstore/register"; + private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.com/admin/service/appstore/register"; /// /// The _is MB supporter diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs b/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs index be2817fd2..47c754643 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs @@ -18,7 +18,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints private readonly IHttpClient _httpClient; private readonly IUserManager _userManager; private readonly ILogger _logger; - private const string MbAdminUrl = "http://www.mb3admin.com/admin/"; + private const string MbAdminUrl = "https://www.mb3admin.com/admin/"; public UsageReporter(IApplicationHost applicationHost, IHttpClient httpClient, IUserManager userManager, ILogger logger) { diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 36d15b95a..b17f10af3 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -984,10 +984,6 @@ namespace MediaBrowser.Server.Startup.Common { get { - if (!ServerConfigurationManager.Configuration.EnableAutoUpdate) - { - return false; - } #if DEBUG return false; #endif -- cgit v1.2.3 From 5a2778f6d833b591dfe52fa03de19324a1253250 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 12 Feb 2016 15:26:03 -0500 Subject: add more play buttons --- MediaBrowser.Common.Implementations/Security/MbAdmin.cs | 4 ++-- MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'MediaBrowser.Common.Implementations') diff --git a/MediaBrowser.Common.Implementations/Security/MbAdmin.cs b/MediaBrowser.Common.Implementations/Security/MbAdmin.cs index 76ff92c2e..ab4a83257 100644 --- a/MediaBrowser.Common.Implementations/Security/MbAdmin.cs +++ b/MediaBrowser.Common.Implementations/Security/MbAdmin.cs @@ -3,11 +3,11 @@ namespace MediaBrowser.Common.Implementations.Security { public class MbAdmin { - public const string HttpUrl = "https://www.mb3admin.com/admin/"; + public const string HttpUrl = "http://www.mb3admin.com/admin/"; /// /// Leaving as http for now until we get it squared away /// - public const string HttpsUrl = "https://www.mb3admin.com/admin/"; + public const string HttpsUrl = "http://www.mb3admin.com/admin/"; } } diff --git a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs index d751083f0..a6dbf77e9 100644 --- a/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs +++ b/MediaBrowser.Common.Implementations/Security/PluginSecurityManager.cs @@ -21,7 +21,7 @@ namespace MediaBrowser.Common.Implementations.Security public class PluginSecurityManager : ISecurityManager { private const string MBValidateUrl = MbAdmin.HttpsUrl + "service/registration/validate"; - private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.com/admin/service/appstore/register"; + private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "http://mb3admin.com/admin/service/appstore/register"; /// /// The _is MB supporter -- cgit v1.2.3