From 6ffde49760e30c4f0c06d3973442d2977fb276f1 Mon Sep 17 00:00:00 2001 From: drmrbg Date: Fri, 28 Dec 2018 23:18:06 -0800 Subject: [PATCH 001/125] Attempt to fix Chromecast support --- .../Playback/BaseStreamingService.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 9c2e0e9d8f..f563fadb29 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -588,6 +588,22 @@ namespace MediaBrowser.Api.Playback } } + /// + /// Parses query parameters as StreamOptions + /// + /// The stream request. + private void ParseStreamOptions(StreamRequest request) + { + foreach (var param in Request.QueryString) { + if (Char.IsLower(param.Name[0])) { + // This was probably not parsed initially and should be a StreamOptions + // TODO: This should be incorporated either in the lower framework for parsing requests + // or the generated URL should correctly serialize it + request.StreamOptions[param.Name] = param.Value; + } + } + } + /// /// Parses the dlna headers. /// @@ -666,6 +682,8 @@ namespace MediaBrowser.Api.Playback ParseParams(request); } + ParseStreamOptions(request); + var url = Request.PathInfo; if (string.IsNullOrEmpty(request.AudioCodec)) From 69cf9e8fc4bc7b20a3d2df15877bc214ce726579 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 13:18:38 +0100 Subject: [PATCH 002/125] Give more info on error --- Emby.Dlna/DlnaManager.cs | 6 +++--- Emby.Server.Implementations/LiveTv/LiveTvManager.cs | 9 ++++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 62d1eb57ce..4c0f9415bc 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -531,7 +531,7 @@ namespace Emby.Dlna } } - class DlnaProfileEntryPoint /*: IServerEntryPoint*/ + class DlnaProfileEntryPoint : IServerEntryPoint { private readonly IApplicationPaths _appPaths; private readonly IFileSystem _fileSystem; @@ -551,7 +551,7 @@ namespace Emby.Dlna private void DumpProfiles() { - var list = new List + DeviceProfile[] list = new [] { new SamsungSmartTvProfile(), new XboxOneProfile(), @@ -597,4 +597,4 @@ namespace Emby.Dlna { } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 2e96796784..4e3cfe5df7 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2392,13 +2392,16 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { - info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); + // Let's try something + //info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); - var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); + IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); if (provider == null) { - throw new ResourceNotFoundException(); + throw new ResourceNotFoundException( + string.Format("Couldn't find provider with name: '{0}' of type: '{1}'", provider.Name, provider.Type) + ); } await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false); From 76d3f60f0664529bb80a24fb225f6091619c3564 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 15:25:08 +0100 Subject: [PATCH 003/125] Fix NullRefException --- Emby.Dlna/DlnaManager.cs | 5 +++-- Emby.Server.Implementations/LiveTv/LiveTvManager.cs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 4c0f9415bc..042a19d650 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -530,7 +530,7 @@ namespace Emby.Dlna }; } } - + /* class DlnaProfileEntryPoint : IServerEntryPoint { private readonly IApplicationPaths _appPaths; @@ -596,5 +596,6 @@ namespace Emby.Dlna public void Dispose() { } - } + }*/ } + diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 4e3cfe5df7..d57f7e8cc3 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2400,7 +2400,7 @@ namespace Emby.Server.Implementations.LiveTv if (provider == null) { throw new ResourceNotFoundException( - string.Format("Couldn't find provider with name: '{0}' of type: '{1}'", provider.Name, provider.Type) + string.Format("Couldn't find provider of type: '{0}'", info.Type) ); } From 6ebb00549b044a55669aed1f83f0a1d84a1e5903 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 17:42:54 +0100 Subject: [PATCH 004/125] Add missing XmlTvListingsProvider Added from https://github.com/thirunjuguna/emby/blob/e679ac4224c7ac8400f12ef95a063be4fcf3b5c0/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs --- .../LiveTv/Listings/XmlTvListingsProvider.cs | 260 ++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs new file mode 100644 index 0000000000..16252b557c --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -0,0 +1,260 @@ +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.LiveTv; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Emby.XmlTv.Classes; +using Emby.XmlTv.Entities; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; +using MediaBrowser.Common.Progress; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Logging; + +namespace Emby.Server.Implementations.LiveTv.Listings +{ + public class XmlTvListingsProvider : IListingsProvider + { + private readonly IServerConfigurationManager _config; + private readonly IHttpClient _httpClient; + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + private readonly IZipClient _zipClient; + + public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IFileSystem fileSystem, IZipClient zipClient) + { + _config = config; + _httpClient = httpClient; + _logger = logger; + _fileSystem = fileSystem; + _zipClient = zipClient; + } + + public string Name + { + get { return "XmlTV"; } + } + + public string Type + { + get { return "xmltv"; } + } + + private string GetLanguage(ListingsProviderInfo info) + { + if (!string.IsNullOrWhiteSpace(info.PreferredLanguage)) + { + return info.PreferredLanguage; + } + + return _config.Configuration.PreferredMetadataLanguage; + } + + private async Task GetXml(string path, CancellationToken cancellationToken) + { + _logger.Info("xmltv path: {0}", path); + + if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return UnzipIfNeeded(path, path); + } + + var cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; + var cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); + if (_fileSystem.FileExists(cacheFile)) + { + return UnzipIfNeeded(path, cacheFile); + } + + _logger.Info("Downloading xmltv listings from {0}", path); + + var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions + { + CancellationToken = cancellationToken, + Url = path, + Progress = new SimpleProgress(), + DecompressionMethod = CompressionMethod.Gzip, + + // It's going to come back gzipped regardless of this value + // So we need to make sure the decompression method is set to gzip + EnableHttpCompression = true, + + UserAgent = "Emby/3.0" + + }).ConfigureAwait(false); + + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFile)); + + _fileSystem.CopyFile(tempFile, cacheFile, true); + + return UnzipIfNeeded(path, cacheFile); + } + + private string UnzipIfNeeded(string originalUrl, string file) + { + var ext = Path.GetExtension(originalUrl.Split('?')[0]); + + if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase)) + { + using (var stream = _fileSystem.OpenRead(file)) + { + var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractAllFromGz(stream, tempFolder, true); + + return _fileSystem.GetFiles(tempFolder, true) + .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase)) + .Select(i => i.FullName) + .FirstOrDefault(); + } + } + + return file; + } + + public async Task> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(channelId)) + { + throw new ArgumentNullException("channelId"); + } + + /* + if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false)) + { + var length = endDateUtc - startDateUtc; + if (length.TotalDays > 1) + { + endDateUtc = startDateUtc.AddDays(1); + } + }*/ + + _logger.Debug("Getting xmltv programs for channel {0}", channelId); + + var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + var reader = new XmlTvReader(path, GetLanguage(info)); + + var results = reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken); + return results.Select(p => GetProgramInfo(p, info)); + } + + private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info) + { + var episodeTitle = p.Episode == null ? null : p.Episode.Title; + + var programInfo = new ProgramInfo + { + ChannelId = p.ChannelId, + EndDate = p.EndDate.UtcDateTime, + EpisodeNumber = p.Episode == null ? null : p.Episode.Episode, + EpisodeTitle = episodeTitle, + Genres = p.Categories, + StartDate = p.StartDate.UtcDateTime, + Name = p.Title, + Overview = p.Description, + ProductionYear = !p.CopyrightDate.HasValue ? (int?)null : p.CopyrightDate.Value.Year, + SeasonNumber = p.Episode == null ? null : p.Episode.Series, + IsSeries = p.Episode != null, + IsRepeat = p.IsPreviouslyShown && !p.IsNew, + IsPremiere = p.Premiere != null, + IsKids = p.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsMovie = p.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsNews = p.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsSports = p.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null, + HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source), + OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null, + CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null, + SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null + }; + + if (!string.IsNullOrWhiteSpace(p.ProgramId)) + { + programInfo.ShowId = p.ProgramId; + } + else + { + var uniqueString = (p.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/; + + if (programInfo.SeasonNumber.HasValue) + { + uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture); + } + if (programInfo.EpisodeNumber.HasValue) + { + uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture); + } + + programInfo.ShowId = uniqueString.GetMD5().ToString("N"); + + // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped + if (programInfo.IsSeries && !programInfo.IsRepeat) + { + if ((programInfo.EpisodeNumber ?? 0) == 0) + { + programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); + } + } + } + + // Construct an id from the channel and start date + programInfo.Id = String.Format("{0}_{1:O}", p.ChannelId, p.StartDate); + + if (programInfo.IsMovie) + { + programInfo.IsSeries = false; + programInfo.EpisodeNumber = null; + programInfo.EpisodeTitle = null; + } + + return programInfo; + } + + public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) + { + // Assume all urls are valid. check files for existence + if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path)) + { + throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); + } + + return Task.FromResult(true); + } + + public async Task> GetLineups(ListingsProviderInfo info, string country, string location) + { + // In theory this should never be called because there is always only one lineup + var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); + var reader = new XmlTvReader(path, GetLanguage(info)); + var results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); + } + + public async Task> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) + { + // In theory this should never be called because there is always only one lineup + var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + var reader = new XmlTvReader(path, GetLanguage(info)); + var results = reader.GetChannels(); + + // Should this method be async? + return results.Select(c => new ChannelInfo + { + Id = c.Id, + Name = c.DisplayName, + ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null, + Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number + + }).ToList(); + } + } +} From baa2afb61e90e99f32b17b572d836ba0dfbc4f0f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 17:56:47 +0100 Subject: [PATCH 005/125] Restore latest version Source: https://github.com/jellyfin/jellyfin/blob/30baa15839d268e3f03ac46844b61ec4b2aef1bc/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs --- .../LiveTv/Listings/XmlTvListingsProvider.cs | 62 ++++++++++++++++--- 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 16252b557c..08abd51e1e 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -102,23 +102,64 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase)) { - using (var stream = _fileSystem.OpenRead(file)) + try { - var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); - _fileSystem.CreateDirectory(tempFolder); + var tempFolder = ExtractGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.ErrorException("Error extracting from gz file {0}", ex, file); + } - _zipClient.ExtractAllFromGz(stream, tempFolder, true); - - return _fileSystem.GetFiles(tempFolder, true) - .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase)) - .Select(i => i.FullName) - .FirstOrDefault(); + try + { + var tempFolder = ExtractFirstFileFromGz(file); + return FindXmlFile(tempFolder); + } + catch (Exception ex) + { + _logger.ErrorException("Error extracting from zip file {0}", ex, file); } } return file; } + private string ExtractFirstFileFromGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml"); + + return tempFolder; + } + } + + private string ExtractGz(string file) + { + using (var stream = _fileSystem.OpenRead(file)) + { + var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + _fileSystem.CreateDirectory(tempFolder); + + _zipClient.ExtractAllFromGz(stream, tempFolder, true); + + return tempFolder; + } + } + + private string FindXmlFile(string directory) + { + return _fileSystem.GetFiles(directory, true) + .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase)) + .Select(i => i.FullName) + .FirstOrDefault(); + } + public async Task> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(channelId)) @@ -139,6 +180,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings _logger.Debug("Getting xmltv programs for channel {0}", channelId); var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); var results = reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken); @@ -232,6 +274,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { // In theory this should never be called because there is always only one lineup var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); + _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); var results = reader.GetChannels(); @@ -243,6 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { // In theory this should never be called because there is always only one lineup var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); var results = reader.GetChannels(); From 589aa2416aca71d6e487c46b2a464537a0c8392c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 18:21:49 +0100 Subject: [PATCH 006/125] Clean up XmlTvListeningProvider --- .../LiveTv/Listings/XmlTvListingsProvider.cs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 08abd51e1e..b8c4314a1a 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -1,6 +1,3 @@ -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.LiveTv; using System; using System.Collections.Generic; using System.Globalization; @@ -14,10 +11,13 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; +using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Logging; -namespace Emby.Server.Implementations.LiveTv.Listings +namespace Jellyfin.Server.Implementations.LiveTv.Listings { public class XmlTvListingsProvider : IListingsProvider { @@ -189,20 +189,20 @@ namespace Emby.Server.Implementations.LiveTv.Listings private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info) { - var episodeTitle = p.Episode == null ? null : p.Episode.Title; + var episodeTitle = p.Episode?.Title; var programInfo = new ProgramInfo { ChannelId = p.ChannelId, EndDate = p.EndDate.UtcDateTime, - EpisodeNumber = p.Episode == null ? null : p.Episode.Episode, + EpisodeNumber = p.Episode?.Episode, EpisodeTitle = episodeTitle, Genres = p.Categories, StartDate = p.StartDate.UtcDateTime, Name = p.Title, Overview = p.Description, - ProductionYear = !p.CopyrightDate.HasValue ? (int?)null : p.CopyrightDate.Value.Year, - SeasonNumber = p.Episode == null ? null : p.Episode.Series, + ProductionYear = p.CopyrightDate?.Year, + SeasonNumber = p.Episode?.Series, IsSeries = p.Episode != null, IsRepeat = p.IsPreviouslyShown && !p.IsNew, IsPremiere = p.Premiere != null, @@ -213,8 +213,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null, HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source), OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null, - CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null, - SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null + CommunityRating = p.StarRating, + SeriesId = p.Episode == null ? null : p.Title.GetMD5().ToString("N") }; if (!string.IsNullOrWhiteSpace(p.ProgramId)) @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); } - return Task.FromResult(true); + return Task.CompletedTask; } public async Task> GetLineups(ListingsProviderInfo info, string country, string location) From 9ff45cf9690621612a9f58e6abdf1c6cde3ddcda Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 18:30:29 +0100 Subject: [PATCH 007/125] Some voodoo magic to stop a crash --- .../Channels/RefreshChannelsScheduledTask.cs | 3 ++- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- Emby.Server.Implementations/LiveTv/LiveTvManager.cs | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs index 0208183614..9d1b751d75 100644 --- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs @@ -3,6 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Logging; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Progress; using MediaBrowser.Model.Tasks; @@ -54,7 +55,7 @@ namespace Emby.Server.Implementations.Channels get { return true; } } - public async Task Execute(System.Threading.CancellationToken cancellationToken, IProgress progress) + public async Task Execute(CancellationToken cancellationToken, IProgress progress) { var manager = (ChannelManager)_channelManager; diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 9021666a30..2d0eaf25ba 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -1298,4 +1298,4 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index d57f7e8cc3..7f2a5ad295 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2392,8 +2392,8 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { - // Let's try something - //info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); + // Voodoo + info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); @@ -2406,7 +2406,7 @@ namespace Emby.Server.Implementations.LiveTv await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false); - var config = GetConfiguration(); + LiveTvOptions config = GetConfiguration(); var list = config.ListingProviders.ToList(); var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); From f31457a457782cba0b34d409f93e051666c7a5c1 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 20:21:48 +0100 Subject: [PATCH 008/125] Final cleanup --- .../LiveTv/Listings/XmlTvListingsProvider.cs | 99 +++++++++---------- .../LiveTv/LiveTvManager.cs | 7 +- 2 files changed, 53 insertions(+), 53 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index b8c4314a1a..a8609ce2da 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -65,8 +65,8 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings return UnzipIfNeeded(path, path); } - var cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; - var cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); + string cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml"; + string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); if (_fileSystem.FileExists(cacheFile)) { return UnzipIfNeeded(path, cacheFile); @@ -74,7 +74,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings _logger.Info("Downloading xmltv listings from {0}", path); - var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions + string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions { CancellationToken = cancellationToken, Url = path, @@ -98,13 +98,13 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings private string UnzipIfNeeded(string originalUrl, string file) { - var ext = Path.GetExtension(originalUrl.Split('?')[0]); + string ext = Path.GetExtension(originalUrl.Split('?')[0]); if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase)) { try { - var tempFolder = ExtractGz(file); + string tempFolder = ExtractGz(file); return FindXmlFile(tempFolder); } catch (Exception ex) @@ -114,7 +114,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings try { - var tempFolder = ExtractFirstFileFromGz(file); + string tempFolder = ExtractFirstFileFromGz(file); return FindXmlFile(tempFolder); } catch (Exception ex) @@ -130,7 +130,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { using (var stream = _fileSystem.OpenRead(file)) { - var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); _fileSystem.CreateDirectory(tempFolder); _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml"); @@ -143,7 +143,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { using (var stream = _fileSystem.OpenRead(file)) { - var tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); + string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString()); _fileSystem.CreateDirectory(tempFolder); _zipClient.ExtractAllFromGz(stream, tempFolder, true); @@ -179,51 +179,47 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings _logger.Debug("Getting xmltv programs for channel {0}", channelId); - var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); - var results = reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken); - return results.Select(p => GetProgramInfo(p, info)); + return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) + .Select(p => GetProgramInfo(p, info)); } - private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info) + private ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) { - var episodeTitle = p.Episode?.Title; + string episodeTitle = program.Episode?.Title; var programInfo = new ProgramInfo { - ChannelId = p.ChannelId, - EndDate = p.EndDate.UtcDateTime, - EpisodeNumber = p.Episode?.Episode, + ChannelId = program.ChannelId, + EndDate = program.EndDate.UtcDateTime, + EpisodeNumber = program.Episode?.Episode, EpisodeTitle = episodeTitle, - Genres = p.Categories, - StartDate = p.StartDate.UtcDateTime, - Name = p.Title, - Overview = p.Description, - ProductionYear = p.CopyrightDate?.Year, - SeasonNumber = p.Episode?.Series, - IsSeries = p.Episode != null, - IsRepeat = p.IsPreviouslyShown && !p.IsNew, - IsPremiere = p.Premiere != null, - IsKids = p.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), - IsMovie = p.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), - IsNews = p.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), - IsSports = p.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), - ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null, - HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source), - OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null, - CommunityRating = p.StarRating, - SeriesId = p.Episode == null ? null : p.Title.GetMD5().ToString("N") + Genres = program.Categories, + StartDate = program.StartDate.UtcDateTime, + Name = program.Title, + Overview = program.Description, + ProductionYear = program.CopyrightDate?.Year, + SeasonNumber = program.Episode?.Series, + IsSeries = program.Episode != null, + IsRepeat = program.IsPreviouslyShown && !program.IsNew, + IsPremiere = program.Premiere != null, + IsKids = program.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)), + ImageUrl = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source) ? program.Icon.Source : null, + HasImage = program.Icon != null && !String.IsNullOrEmpty(program.Icon.Source), + OfficialRating = program.Rating != null && !String.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null, + CommunityRating = program.StarRating, + SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N") }; - if (!string.IsNullOrWhiteSpace(p.ProgramId)) + if (string.IsNullOrWhiteSpace(program.ProgramId)) { - programInfo.ShowId = p.ProgramId; - } - else - { - var uniqueString = (p.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/; + string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty) /*+ (p.IceTvEpisodeNumber ?? string.Empty)*/; if (programInfo.SeasonNumber.HasValue) { @@ -237,17 +233,20 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings programInfo.ShowId = uniqueString.GetMD5().ToString("N"); // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped - if (programInfo.IsSeries && !programInfo.IsRepeat) + if (programInfo.IsSeries + && !programInfo.IsRepeat + && (programInfo.EpisodeNumber ?? 0) == 0) { - if ((programInfo.EpisodeNumber ?? 0) == 0) - { - programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); - } + programInfo.ShowId = programInfo.ShowId + programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); } } + else + { + programInfo.ShowId = program.ProgramId; + } // Construct an id from the channel and start date - programInfo.Id = String.Format("{0}_{1:O}", p.ChannelId, p.StartDate); + programInfo.Id = String.Format("{0}_{1:O}", program.ChannelId, program.StartDate); if (programInfo.IsMovie) { @@ -273,10 +272,10 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings public async Task> GetLineups(ListingsProviderInfo info, string country, string location) { // In theory this should never be called because there is always only one lineup - var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); + string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); - var results = reader.GetChannels(); + IEnumerable results = reader.GetChannels(); // Should this method be async? return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); @@ -285,10 +284,10 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings public async Task> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) { // In theory this should never be called because there is always only one lineup - var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); + string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); _logger.Debug("Opening XmlTvReader for {0}", path); var reader = new XmlTvReader(path, GetLanguage(info)); - var results = reader.GetChannels(); + IEnumerable results = reader.GetChannels(); // Should this method be async? return results.Select(c => new ChannelInfo diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 7f2a5ad295..e4400220e6 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2392,7 +2392,8 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings) { - // Voodoo + // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider + // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider info = _jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info)); IListingsProvider provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); @@ -2408,8 +2409,8 @@ namespace Emby.Server.Implementations.LiveTv LiveTvOptions config = GetConfiguration(); - var list = config.ListingProviders.ToList(); - var index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); + List list = config.ListingProviders.ToList(); + int index = list.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase)); if (index == -1 || string.IsNullOrWhiteSpace(info.Id)) { From 00ef953b8e11fb0b58d2165932bbedb6e42da67c Mon Sep 17 00:00:00 2001 From: bfayers Date: Sun, 30 Dec 2018 20:48:08 +0000 Subject: [PATCH 009/125] replace all instanced of emby.media with jellyfin.media --- Emby.Notifications/Notifications.cs | 2 +- MediaBrowser.Providers/Movies/MovieDbProvider.cs | 2 +- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs index 3cadad6c8d..5725d1ba19 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/Notifications.cs @@ -137,7 +137,7 @@ namespace Emby.Notifications var notification = new NotificationRequest { - Description = "Please see emby.media for details.", + Description = "Please see jellyfin.media for details.", NotificationType = type, Name = _localization.GetLocalizedString("NewVersionIsAvailable") }; diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index e16e6aa8ca..c06a8f20f0 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -287,7 +287,7 @@ namespace MediaBrowser.Providers.Movies if (!string.IsNullOrEmpty(language)) { // They require this to be uppercase - // https://emby.media/community/index.php?/topic/32454-fr-follow-tmdbs-new-language-api-update/?p=311148 + // https://jellyfin.media/community/index.php?/topic/32454-fr-follow-tmdbs-new-language-api-update/?p=311148 var parts = language.Split('-'); if (parts.Length == 2) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index f6ea9b4b23..6f1bbfb293 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -353,7 +353,7 @@ namespace MediaBrowser.XbmcMetadata.Savers if (!string.IsNullOrEmpty(stream.Language)) { - // https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify + // https://jellyfin.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify writer.WriteElementString("language", RemoveInvalidXMLChars(stream.Language)); } From 0584700a760de37109eb8428b502defc5072797c Mon Sep 17 00:00:00 2001 From: bfayers Date: Sun, 30 Dec 2018 21:08:54 +0000 Subject: [PATCH 010/125] Write out explanation rather than linking to a community (TMDB uppercasing) --- MediaBrowser.Providers/Movies/MovieDbProvider.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index c06a8f20f0..c742e3df29 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -287,7 +287,8 @@ namespace MediaBrowser.Providers.Movies if (!string.IsNullOrEmpty(language)) { // They require this to be uppercase - // https://jellyfin.media/community/index.php?/topic/32454-fr-follow-tmdbs-new-language-api-update/?p=311148 + // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api. + // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab var parts = language.Split('-'); if (parts.Length == 2) From 9986a3d22cb6db87d3ce6ff13561b1fcbbb94498 Mon Sep 17 00:00:00 2001 From: bfayers Date: Sun, 30 Dec 2018 21:18:48 +0000 Subject: [PATCH 011/125] Go back to an emby.media/community link but via web archive --- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 6f1bbfb293..78afde80b3 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -353,7 +353,8 @@ namespace MediaBrowser.XbmcMetadata.Savers if (!string.IsNullOrEmpty(stream.Language)) { - // https://jellyfin.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify + // http://web.archive.org/web/20181230211547/https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify + // Web Archive version of link since it's not really explained in the thread. writer.WriteElementString("language", RemoveInvalidXMLChars(stream.Language)); } From 0f8b3c634708ce8e7b2e2ae6fed87b6b943b5bca Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 13 Dec 2018 14:18:25 +0100 Subject: [PATCH 012/125] Use Microsoft.Extensions.Logging abstraction --- .../ConnectionManager/ConnectionManager.cs | 2 +- Emby.Dlna/ConnectionManager/ControlHandler.cs | 2 +- .../ContentDirectory/ContentDirectory.cs | 2 +- Emby.Dlna/ContentDirectory/ControlHandler.cs | 6 +- Emby.Dlna/Didl/DidlBuilder.cs | 8 +- Emby.Dlna/DlnaManager.cs | 20 +- Emby.Dlna/Eventing/EventManager.cs | 8 +- Emby.Dlna/Main/DlnaEntryPoint.cs | 30 +- .../MediaReceiverRegistrar/ControlHandler.cs | 2 +- .../MediaReceiverRegistrar.cs | 2 +- Emby.Dlna/PlayTo/Device.cs | 18 +- Emby.Dlna/PlayTo/PlayToController.cs | 20 +- Emby.Dlna/PlayTo/PlayToManager.cs | 12 +- Emby.Dlna/Service/BaseControlHandler.cs | 16 +- Emby.Dlna/Service/BaseService.cs | 2 +- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 +- .../ImageMagickEncoder.cs | 8 +- Emby.Drawing.Net/GDIImageEncoder.cs | 8 +- Emby.Drawing.Skia/SkiaEncoder.cs | 8 +- Emby.Drawing/Common/ImageHeader.cs | 4 +- Emby.Drawing/ImageProcessor.cs | 20 +- .../IsoMounter/LinuxIsoManager.cs | 52 +-- Emby.IsoMounting/IsoMounter/LinuxMount.cs | 3 +- Emby.Notifications/NotificationManager.cs | 14 +- Emby.Notifications/Notifications.cs | 4 +- Emby.Photos/PhotoProvider.cs | 4 +- .../Activity/ActivityLogEntryPoint.cs | 10 +- .../Activity/ActivityManager.cs | 2 +- .../Activity/ActivityRepository.cs | 8 +- .../AppBase/BaseConfigurationManager.cs | 10 +- .../ApplicationHost.cs | 230 ++++++----- .../Channels/ChannelManager.cs | 30 +- .../Channels/ChannelPostScanTask.cs | 4 +- .../Channels/RefreshChannelsScheduledTask.cs | 2 +- .../Collections/CollectionManager.cs | 6 +- .../ServerConfigurationManager.cs | 8 +- .../Data/BaseSqliteRepository.cs | 16 +- .../Data/CleanDatabaseScheduledTask.cs | 8 +- .../SqliteDisplayPreferencesRepository.cs | 6 +- .../Data/SqliteItemRepository.cs | 32 +- .../Data/SqliteUserDataRepository.cs | 4 +- .../Data/SqliteUserRepository.cs | 6 +- .../Devices/DeviceId.cs | 8 +- .../Devices/DeviceManager.cs | 4 +- Emby.Server.Implementations/Dto/DtoService.cs | 14 +- .../EntryPoints/AutomaticRestartEntryPoint.cs | 8 +- .../EntryPoints/ExternalPortForwarding.cs | 18 +- .../EntryPoints/KeepServerAwake.cs | 4 +- .../EntryPoints/LibraryChangedNotifier.cs | 6 +- .../EntryPoints/RecordingNotifier.cs | 4 +- .../EntryPoints/ServerEventNotifier.cs | 4 +- .../EntryPoints/StartupWizard.cs | 4 +- .../EntryPoints/UdpServerEntryPoint.cs | 4 +- .../EntryPoints/UsageEntryPoint.cs | 6 +- .../EntryPoints/UsageReporter.cs | 4 +- .../EntryPoints/UserDataChangeNotifier.cs | 2 +- .../EnvironmentInfo/EnvironmentInfo.cs | 2 +- .../FFMpeg/FFMpegLoader.cs | 2 +- .../HttpClientManager/HttpClientManager.cs | 20 +- .../HttpServer/FileWriter.cs | 6 +- .../HttpServer/HttpListenerHost.cs | 24 +- .../HttpServer/HttpResultFactory.cs | 6 +- .../HttpServer/LoggerUtils.cs | 8 +- .../HttpServer/RangeRequestWriter.cs | 4 +- .../HttpServer/ResponseFilter.cs | 4 +- .../HttpServer/StreamWriter.cs | 2 +- .../HttpServer/WebSocketConnection.cs | 4 +- .../IO/FileRefresher.cs | 16 +- .../IO/LibraryMonitor.cs | 28 +- .../IO/ManagedFileSystem.cs | 6 +- .../IO/StreamHelper.cs | 2 +- .../Library/ConnectManager.cs | 46 +++ .../Library/CoreResolutionIgnoreRule.cs | 2 +- .../Library/LibraryManager.cs | 68 ++-- .../Library/LiveStreamHelper.cs | 10 +- .../Library/MediaSourceManager.cs | 22 +- .../Resolvers/Audio/MusicAlbumResolver.cs | 4 +- .../Resolvers/Audio/MusicArtistResolver.cs | 2 +- .../Library/Resolvers/BaseVideoResolver.cs | 2 +- .../Library/Resolvers/Movies/MovieResolver.cs | 2 +- .../Library/Resolvers/TV/SeasonResolver.cs | 4 +- .../Library/Resolvers/TV/SeriesResolver.cs | 10 +- .../Library/SearchEngine.cs | 6 +- .../Library/UserDataManager.cs | 6 +- .../Library/UserManager.cs | 20 +- .../Library/Validators/ArtistsPostScanTask.cs | 2 +- .../Library/Validators/ArtistsValidator.cs | 6 +- .../Validators/GameGenresPostScanTask.cs | 2 +- .../Library/Validators/GameGenresValidator.cs | 4 +- .../Library/Validators/GenresPostScanTask.cs | 2 +- .../Library/Validators/GenresValidator.cs | 4 +- .../Validators/MusicGenresPostScanTask.cs | 2 +- .../Validators/MusicGenresValidator.cs | 4 +- .../Library/Validators/PeopleValidator.cs | 10 +- .../Library/Validators/StudiosPostScanTask.cs | 2 +- .../Library/Validators/StudiosValidator.cs | 6 +- .../LiveTv/EmbyTV/DirectRecorder.cs | 12 +- .../LiveTv/EmbyTV/EmbyTV.cs | 94 ++--- .../LiveTv/EmbyTV/EncodedRecorder.cs | 31 +- .../LiveTv/EmbyTV/ItemDataProvider.cs | 6 +- .../LiveTv/EmbyTV/SeriesTimerManager.cs | 2 +- .../LiveTv/EmbyTV/TimerManager.cs | 12 +- .../LiveTv/Listings/SchedulesDirect.cs | 32 +- .../LiveTv/LiveTvDtoService.cs | 4 +- .../LiveTv/LiveTvManager.cs | 30 +- .../LiveTv/LiveTvMediaSourceProvider.cs | 8 +- .../LiveTv/TunerHosts/BaseTunerHost.cs | 14 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 6 +- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 4 +- .../HdHomerun/HdHomerunUdpStream.cs | 14 +- .../LiveTv/TunerHosts/LiveStream.cs | 20 +- .../LiveTv/TunerHosts/M3UTunerHost.cs | 4 +- .../LiveTv/TunerHosts/M3uParser.cs | 6 +- .../LiveTv/TunerHosts/SharedHttpStream.cs | 19 +- .../Localization/LocalizationManager.cs | 4 +- .../Logging/ConsoleLogger.cs | 13 - .../Logging/SimpleLogManager.cs | 360 ------------------ .../Logging/UnhandledExceptionWriter.cs | 45 --- .../MediaEncoder/EncodingManager.cs | 10 +- .../Net/SocketFactory.cs | 2 +- .../Networking/NetworkManager.cs | 24 +- .../News/NewsEntryPoint.cs | 4 +- .../Playlists/PlaylistManager.cs | 2 +- .../ResourceFileManager.cs | 4 +- .../ScheduledTasks/ChapterImagesTask.cs | 6 +- .../ScheduledTasks/DailyTrigger.cs | 4 +- .../ScheduledTasks/IntervalTrigger.cs | 2 +- .../ScheduledTasks/PluginUpdateTask.cs | 142 +++++++ .../ScheduledTasks/ScheduledTaskWorker.cs | 30 +- .../ScheduledTasks/StartupTrigger.cs | 2 +- .../ScheduledTasks/SystemEventTrigger.cs | 2 +- .../ScheduledTasks/SystemUpdateTask.cs | 8 +- .../ScheduledTasks/TaskManager.cs | 14 +- .../Tasks/DeleteCacheFileTask.cs | 10 +- .../Tasks/ReloadLoggerFileTask.cs | 110 ------ .../ScheduledTasks/WeeklyTrigger.cs | 2 +- .../Security/AuthenticationRepository.cs | 4 +- .../Security/PluginSecurityManager.cs | 12 +- .../Serialization/JsonSerializer.cs | 4 +- .../Serialization/XmlSerializer.cs | 6 +- .../Services/ServiceController.cs | 4 +- .../Services/ServiceHandler.cs | 5 +- .../Services/ServicePath.cs | 14 +- .../Session/SessionManager.cs | 44 +-- .../Session/SessionWebSocketListener.cs | 10 +- .../Session/WebSocketController.cs | 2 +- Emby.Server.Implementations/SystemEvents.cs | 2 +- .../TextEncoding/TextEncoding.cs | 8 +- Emby.Server.Implementations/Udp/UdpServer.cs | 16 +- .../Updates/InstallationManager.cs | 16 +- Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs | 6 +- MediaBrowser.Api/ApiEntryPoint.cs | 2 +- MediaBrowser.Api/BaseApiService.cs | 2 +- MediaBrowser.Api/Images/ImageService.cs | 6 +- MediaBrowser.Api/ItemLookupService.cs | 3 +- MediaBrowser.Api/ItemRefreshService.cs | 2 +- MediaBrowser.Api/Library/LibraryService.cs | 3 +- .../LiveTv/ProgressiveFileCopier.cs | 4 +- MediaBrowser.Api/PluginService.cs | 2 +- .../ScheduledTasksWebSocketListener.cs | 2 +- .../Session/SessionInfoWebSocketListener.cs | 2 +- MediaBrowser.Api/SimilarItemsHelper.cs | 2 +- MediaBrowser.Api/Subtitles/SubtitleService.cs | 3 +- .../System/ActivityLogWebSocketListener.cs | 2 +- MediaBrowser.Common/Events/EventHelper.cs | 10 +- MediaBrowser.Controller/Entities/BaseItem.cs | 12 +- .../Entities/CollectionFolder.cs | 12 +- MediaBrowser.Controller/Entities/Folder.cs | 20 +- .../Entities/TV/Episode.cs | 2 +- .../Entities/UserViewBuilder.cs | 6 +- MediaBrowser.Controller/IO/FileData.cs | 6 +- .../IResourceFileManager.cs | 2 +- MediaBrowser.Controller/Library/Profiler.cs | 4 +- .../MediaEncoding/EncodingJobInfo.cs | 4 +- .../MediaEncoding/JobLogger.cs | 4 +- .../Net/BasePeriodicWebSocketListener.cs | 9 +- .../Providers/DirectoryService.cs | 6 +- .../Providers/MetadataRefreshOptions.cs | 4 +- .../Session/SessionInfo.cs | 14 +- .../Parsers/BaseItemXmlParser.cs | 4 +- .../Parsers/BoxSetXmlParser.cs | 2 +- .../Parsers/GameSystemXmlParser.cs | 2 +- .../Parsers/GameXmlParser.cs | 2 +- .../Parsers/PlaylistXmlParser.cs | 2 +- .../Providers/BoxSetXmlProvider.cs | 2 +- .../Providers/GameSystemXmlProvider.cs | 2 +- .../Providers/GameXmlProvider.cs | 2 +- .../Providers/PlaylistXmlProvider.cs | 2 +- .../Savers/BaseXmlSaver.cs | 4 +- .../Savers/BoxSetXmlSaver.cs | 2 +- .../Savers/GameSystemXmlSaver.cs | 2 +- .../Savers/GameXmlSaver.cs | 2 +- .../Savers/PersonXmlSaver.cs | 2 +- .../Savers/PlaylistXmlSaver.cs | 2 +- .../Activity/ActivityLogEntry.cs | 4 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 14 +- MediaBrowser.Model/Logging/IConsoleLogger.cs | 7 - MediaBrowser.Model/Logging/ILogManager.cs | 56 --- MediaBrowser.Model/Logging/ILogger.cs | 78 ---- MediaBrowser.Model/Logging/LogHelper.cs | 97 ----- MediaBrowser.Model/Logging/LogSeverity.cs | 30 -- MediaBrowser.Model/Logging/NullLogger.cs | 44 --- MediaBrowser.Model/MediaBrowser.Model.csproj | 4 + MediaBrowser.Model/Tasks/ITaskTrigger.cs | 4 +- .../Books/AudioBookMetadataService.cs | 2 +- .../Books/BookMetadataService.cs | 2 +- .../BoxSets/BoxSetMetadataService.cs | 2 +- .../BoxSets/MovieDbBoxSetProvider.cs | 2 +- .../Channels/ChannelMetadataService.cs | 2 +- .../Chapters/ChapterManager.cs | 2 +- .../CollectionFolderMetadataService.cs | 2 +- .../Folders/FolderMetadataService.cs | 2 +- .../Folders/UserViewMetadataService.cs | 2 +- .../GameGenres/GameGenreMetadataService.cs | 2 +- .../Games/GameMetadataService.cs | 2 +- .../Games/GameSystemMetadataService.cs | 2 +- .../Genres/GenreMetadataService.cs | 2 +- .../LiveTv/ProgramMetadataService.cs | 2 +- MediaBrowser.Providers/Manager/ImageSaver.cs | 12 +- .../Manager/ItemImageProvider.cs | 16 +- .../Manager/MetadataService.cs | 30 +- .../Manager/ProviderManager.cs | 36 +- .../MediaInfo/FFProbeProvider.cs | 6 +- .../MediaInfo/FFProbeVideoInfo.cs | 10 +- .../MediaInfo/SubtitleDownloader.cs | 4 +- .../MediaInfo/SubtitleScheduledTask.cs | 4 +- .../MediaInfo/VideoImageProvider.cs | 4 +- .../Movies/GenericMovieDbInfo.cs | 2 +- .../Movies/MovieDbProvider.cs | 6 +- .../Movies/MovieDbSearch.cs | 4 +- .../Movies/MovieMetadataService.cs | 2 +- .../Music/AlbumMetadataService.cs | 2 +- .../Music/ArtistMetadataService.cs | 2 +- .../Music/AudioMetadataService.cs | 2 +- .../Music/MusicBrainzAlbumProvider.cs | 6 +- .../Music/MusicVideoMetadataService.cs | 2 +- .../MusicGenres/MusicGenreMetadataService.cs | 2 +- .../Omdb/OmdbItemProvider.cs | 2 +- .../People/MovieDbPersonProvider.cs | 2 +- .../People/PersonMetadataService.cs | 2 +- .../Photos/PhotoAlbumMetadataService.cs | 2 +- .../Photos/PhotoMetadataService.cs | 2 +- .../Playlists/PlaylistItemsProvider.cs | 4 +- .../Playlists/PlaylistMetadataService.cs | 2 +- .../Studios/StudioMetadataService.cs | 2 +- .../Subtitles/SubtitleManager.cs | 8 +- .../TV/DummySeasonProvider.cs | 6 +- .../TV/EpisodeMetadataService.cs | 2 +- .../TV/MissingEpisodeProvider.cs | 6 +- .../TV/Omdb/OmdbEpisodeProvider.cs | 2 +- .../TV/SeasonMetadataService.cs | 2 +- .../TV/SeriesMetadataService.cs | 4 +- .../TheMovieDb/MovieDbEpisodeImageProvider.cs | 6 +- .../TV/TheMovieDb/MovieDbEpisodeProvider.cs | 6 +- .../TV/TheMovieDb/MovieDbProviderBase.cs | 6 +- .../TV/TheMovieDb/MovieDbSeasonProvider.cs | 8 +- .../TV/TheMovieDb/MovieDbSeriesProvider.cs | 4 +- .../TV/TheTVDB/TvdbEpisodeProvider.cs | 4 +- .../TV/TheTVDB/TvdbPrescanTask.cs | 6 +- .../TV/TheTVDB/TvdbSeriesProvider.cs | 2 +- .../Users/UserMetadataService.cs | 2 +- .../Videos/VideoMetadataService.cs | 2 +- .../Years/YearMetadataService.cs | 2 +- MediaBrowser.Server.Mono/EmbyServer.csproj | 2 + .../ImageEncoderHelper.cs | 11 +- MediaBrowser.Server.Mono/MonoAppHost.cs | 8 +- .../Native/MonoFileSystem.cs | 4 +- MediaBrowser.Server.Mono/Program.cs | 54 +-- .../SocketSharp/SharpWebSocket.cs | 4 +- .../SocketSharp/WebSocketSharpListener.cs | 18 +- .../SocketSharp/WebSocketSharpRequest.cs | 2 +- .../SocketSharp/WebSocketSharpResponse.cs | 4 +- MediaBrowser.Tests/M3uParserTest.cs | 2 +- .../MediaEncoding/Subtitles/SrtParserTests.cs | 4 +- .../Api/DashboardService.cs | 4 +- .../Api/PackageCreator.cs | 2 +- MediaBrowser.XbmcMetadata/EntryPoint.cs | 4 +- .../Parsers/BaseNfoParser.cs | 4 +- .../Parsers/EpisodeNfoParser.cs | 2 +- .../Parsers/MovieNfoParser.cs | 4 +- .../Parsers/SeasonNfoParser.cs | 2 +- .../Parsers/SeriesNfoParser.cs | 4 +- .../Providers/AlbumNfoProvider.cs | 2 +- .../Providers/ArtistNfoProvider.cs | 2 +- .../Providers/BaseVideoNfoProvider.cs | 4 +- .../Providers/EpisodeNfoProvider.cs | 2 +- .../Providers/MovieNfoProvider.cs | 4 +- .../Providers/SeasonNfoProvider.cs | 2 +- .../Providers/SeriesNfoProvider.cs | 2 +- .../Savers/AlbumNfoSaver.cs | 2 +- .../Savers/ArtistNfoSaver.cs | 4 +- .../Savers/BaseNfoSaver.cs | 12 +- .../Savers/EpisodeNfoSaver.cs | 4 +- .../Savers/MovieNfoSaver.cs | 2 +- .../Savers/SeasonNfoSaver.cs | 2 +- .../Savers/SeriesNfoSaver.cs | 2 +- Mono.Nat/NatManager.cs | 2 +- Mono.Nat/Pmp/PmpNatDevice.cs | 8 +- Mono.Nat/Pmp/PmpSearcher.cs | 4 +- Mono.Nat/Upnp/Messages/GetServicesMessage.cs | 6 +- Mono.Nat/Upnp/Searchers/UpnpSearcher.cs | 4 +- Mono.Nat/Upnp/UpnpNatDevice.cs | 22 +- RSSDP/SsdpCommunicationsServer.cs | 16 +- SocketHttpListener/Net/HttpConnection.cs | 6 +- .../Net/HttpEndPointListener.cs | 12 +- SocketHttpListener/Net/HttpEndPointManager.cs | 2 +- SocketHttpListener/Net/HttpListener.cs | 4 +- SocketHttpListener/Net/HttpListenerContext.cs | 4 + .../Net/HttpListenerPrefixCollection.cs | 2 +- .../Net/HttpResponseStream.Managed.cs | 2 +- 310 files changed, 1421 insertions(+), 2058 deletions(-) create mode 100644 Emby.Server.Implementations/Library/ConnectManager.cs delete mode 100644 Emby.Server.Implementations/Logging/ConsoleLogger.cs delete mode 100644 Emby.Server.Implementations/Logging/SimpleLogManager.cs delete mode 100644 Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs create mode 100644 Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs delete mode 100644 Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs delete mode 100644 MediaBrowser.Model/Logging/IConsoleLogger.cs delete mode 100644 MediaBrowser.Model/Logging/ILogManager.cs delete mode 100644 MediaBrowser.Model/Logging/ILogger.cs delete mode 100644 MediaBrowser.Model/Logging/LogHelper.cs delete mode 100644 MediaBrowser.Model/Logging/LogSeverity.cs delete mode 100644 MediaBrowser.Model/Logging/NullLogger.cs diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index 3f33f3ebf1..ab747d189b 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -2,9 +2,9 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; using System.Collections.Generic; using MediaBrowser.Model.Xml; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.ConnectionManager { diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index ae983c5e75..7e3e5f650a 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Server; using Emby.Dlna.Service; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index 0aabe099c1..7c809a952a 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using Emby.Dlna.Service; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Controller.MediaEncoding; diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index bf9c48ac70..57d4078a58 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -12,7 +12,7 @@ using Emby.Dlna.Service; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -68,7 +68,7 @@ namespace Emby.Dlna.ContentDirectory _profile = profile; _config = config; - _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, libraryManager, mediaEncoder); + _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, libraryManager, mediaEncoder); } protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) @@ -1334,7 +1334,7 @@ namespace Emby.Dlna.ContentDirectory }; } - Logger.Error("Error parsing item Id: {0}. Returning user root folder.", id); + _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); return new ServerItem(_libraryManager.GetUserRootFolder()); } diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 8d59ea3ffd..22845586f3 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -11,7 +11,7 @@ using Emby.Dlna.ContentDirectory; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Globalization; @@ -180,7 +180,7 @@ namespace Emby.Dlna.Didl return _logger; } - return new NullLogger(); + return null; } private string GetMimeType(string input) @@ -925,7 +925,7 @@ namespace Emby.Dlna.Didl } catch (XmlException) { - //_logger.Error("Error adding xml value: " + value); + _logger?.LogError("Error adding xml value: {value}", name); } } @@ -937,7 +937,7 @@ namespace Emby.Dlna.Didl } catch (XmlException) { - //_logger.Error("Error adding xml value: " + value); + _logger?.LogError("Error adding xml value: {value}", value); } } diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 042a19d650..4c5bde6cd4 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -8,7 +8,7 @@ using Emby.Dlna.Profiles; using Emby.Dlna.Server; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -58,7 +58,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.ErrorException("Error extracting DLNA profiles.", ex); + _logger.LogError("Error extracting DLNA profiles.", ex); } } @@ -103,7 +103,7 @@ namespace Emby.Dlna if (profile != null) { - _logger.Debug("Found matching device profile: {0}", profile.Name); + _logger.LogDebug("Found matching device profile: {0}", profile.Name); } else { @@ -117,6 +117,7 @@ namespace Emby.Dlna { var builder = new StringBuilder(); + builder.AppendLine("No matching device profile found. The default will need to be used."); builder.AppendLine(string.Format("DeviceDescription:{0}", profile.DeviceDescription ?? string.Empty)); builder.AppendLine(string.Format("FriendlyName:{0}", profile.FriendlyName ?? string.Empty)); builder.AppendLine(string.Format("Manufacturer:{0}", profile.Manufacturer ?? string.Empty)); @@ -127,7 +128,7 @@ namespace Emby.Dlna builder.AppendLine(string.Format("ModelUrl:{0}", profile.ModelUrl ?? string.Empty)); builder.AppendLine(string.Format("SerialNumber:{0}", profile.SerialNumber ?? string.Empty)); - _logger.LogMultiline("No matching device profile found. The default will need to be used.", LogSeverity.Info, builder); + _logger.LogInformation(builder.ToString()); } private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) @@ -197,7 +198,7 @@ namespace Emby.Dlna } catch (ArgumentException ex) { - _logger.ErrorException("Error evaluating regex pattern {0}", ex, pattern); + _logger.LogError("Error evaluating regex pattern {0}", ex, pattern); return false; } } @@ -216,12 +217,12 @@ namespace Emby.Dlna if (profile != null) { - _logger.Debug("Found matching device profile: {0}", profile.Name); + _logger.LogDebug("Found matching device profile: {0}", profile.Name); } else { var headerString = string.Join(", ", headers.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - _logger.Debug("No matching device profile found. {0}", headerString); + _logger.LogDebug("No matching device profile found. {0}", headerString); } return profile; @@ -250,7 +251,7 @@ namespace Emby.Dlna return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase); case HeaderMatchType.Substring: var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1; - //_logger.Debug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch); + //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch); return isMatch; case HeaderMatchType.Regex: return Regex.IsMatch(value, header.Value, RegexOptions.IgnoreCase); @@ -323,7 +324,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.ErrorException("Error parsing profile file: {0}", ex, path); + _logger.LogError("Error parsing profile file: {0}", ex, path); return null; } @@ -598,4 +599,3 @@ namespace Emby.Dlna } }*/ } - diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs index 0638cff897..ea9ba3f22c 100644 --- a/Emby.Dlna/Eventing/EventManager.cs +++ b/Emby.Dlna/Eventing/EventManager.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -34,7 +34,7 @@ namespace Emby.Dlna.Eventing // Remove logging for now because some devices are sending this very frequently // TODO re-enable with dlna debug logging setting - //_logger.Debug("Renewing event subscription for {0} with timeout of {1} to {2}", + //_logger.LogDebug("Renewing event subscription for {0} with timeout of {1} to {2}", // subscription.NotificationType, // timeout, // subscription.CallbackUrl); @@ -60,7 +60,7 @@ namespace Emby.Dlna.Eventing // Remove logging for now because some devices are sending this very frequently // TODO re-enable with dlna debug logging setting - //_logger.Debug("Creating event subscription for {0} with timeout of {1} to {2}", + //_logger.LogDebug("Creating event subscription for {0} with timeout of {1} to {2}", // notificationType, // timeout, // callbackUrl); @@ -96,7 +96,7 @@ namespace Emby.Dlna.Eventing public EventSubscriptionResponse CancelEventSubscription(string subscriptionId) { - _logger.Debug("Cancelling event subscription {0}", subscriptionId); + _logger.LogDebug("Cancelling event subscription {0}", subscriptionId); EventSubscription sub; _subscriptions.TryRemove(subscriptionId, out sub); diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index cd535a98ab..4697287e9b 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -11,7 +11,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.TV; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; @@ -64,7 +64,7 @@ namespace Emby.Dlna.Main public static DlnaEntryPoint Current; public DlnaEntryPoint(IServerConfigurationManager config, - ILogManager logManager, + ILoggerFactory loggerFactory, IServerApplicationHost appHost, ISessionManager sessionManager, IHttpClient httpClient, @@ -102,7 +102,7 @@ namespace Emby.Dlna.Main _timerFactory = timerFactory; _environmentInfo = environmentInfo; _networkManager = networkManager; - _logger = logManager.GetLogger("Dlna"); + _logger = loggerFactory.CreateLogger("Dlna"); ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager, userDataManager, @@ -185,13 +185,13 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting ssdp handlers", ex); + _logger.LogError("Error starting ssdp handlers", ex); } } private void LogMessage(string msg) { - _logger.Debug(msg); + _logger.LogDebug(msg); } private void StartDeviceDiscovery(ISsdpCommunicationsServer communicationsServer) @@ -202,7 +202,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting device discovery", ex); + _logger.LogError("Error starting device discovery", ex); } } @@ -210,12 +210,12 @@ namespace Emby.Dlna.Main { try { - _logger.Info("Disposing DeviceDiscovery"); + _logger.LogInformation("Disposing DeviceDiscovery"); ((DeviceDiscovery)_deviceDiscovery).Dispose(); } catch (Exception ex) { - _logger.ErrorException("Error stopping device discovery", ex); + _logger.LogError("Error stopping device discovery", ex); } } @@ -243,7 +243,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error registering endpoint", ex); + _logger.LogError("Error registering endpoint", ex); } } @@ -263,7 +263,7 @@ namespace Emby.Dlna.Main var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.Info("Registering publisher for {0} on {1}", fullService, address.ToString()); + _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address.ToString()); var descriptorUri = "/dlna/" + udn + "/description.xml"; var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri); @@ -361,7 +361,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.ErrorException("Error starting PlayTo manager", ex); + _logger.LogError("Error starting PlayTo manager", ex); } } } @@ -374,12 +374,12 @@ namespace Emby.Dlna.Main { try { - _logger.Info("Disposing PlayToManager"); + _logger.LogInformation("Disposing PlayToManager"); _manager.Dispose(); } catch (Exception ex) { - _logger.ErrorException("Error disposing PlayTo manager", ex); + _logger.LogError("Error disposing PlayTo manager", ex); } _manager = null; } @@ -394,7 +394,7 @@ namespace Emby.Dlna.Main if (_communicationsServer != null) { - _logger.Info("Disposing SsdpCommunicationsServer"); + _logger.LogInformation("Disposing SsdpCommunicationsServer"); _communicationsServer.Dispose(); _communicationsServer = null; } @@ -409,7 +409,7 @@ namespace Emby.Dlna.Main { if (_Publisher != null) { - _logger.Info("Disposing SsdpDevicePublisher"); + _logger.LogInformation("Disposing SsdpDevicePublisher"); _Publisher.Dispose(); _Publisher = null; } diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs index daf46b1061..d1a595de0e 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Server; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index 4ed74a6844..f07af0464a 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Service; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.Xml; diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 47e3196e12..1cbb69d1da 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using Emby.Dlna.Common; using Emby.Dlna.Ssdp; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -108,7 +108,7 @@ namespace Emby.Dlna.PlayTo public void Start() { - _logger.Debug("Dlna Device.Start"); + _logger.LogDebug("Dlna Device.Start"); _timer = _timerFactory.Create(TimerCallback, null, 1000, Timeout.Infinite); } @@ -140,7 +140,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error updating device volume info for {0}", ex, Properties.Name); + _logger.LogError("Error updating device volume info for {0}", ex, Properties.Name); } } @@ -259,7 +259,7 @@ namespace Emby.Dlna.PlayTo return false; } - _logger.Debug("Setting mute"); + _logger.LogDebug("Setting mute"); var value = mute ? 1 : 0; await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) @@ -323,7 +323,7 @@ namespace Emby.Dlna.PlayTo url = url.Replace("&", "&"); - _logger.Debug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); + _logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI"); if (command == null) @@ -507,7 +507,7 @@ namespace Emby.Dlna.PlayTo if (_disposed) return; - //_logger.ErrorException("Error updating device info for {0}", ex, Properties.Name); + //_logger.LogError("Error updating device info for {0}", ex, Properties.Name); _connectFailureCount++; @@ -516,7 +516,7 @@ namespace Emby.Dlna.PlayTo var action = OnDeviceUnavailable; if (action != null) { - _logger.Debug("Disposing device due to loss of connection"); + _logger.LogDebug("Disposing device due to loss of connection"); action(); return; } @@ -767,7 +767,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Unable to parse xml {0}", ex, trackString); + _logger.LogError("Unable to parse xml {0}", ex, trackString); return new Tuple(true, null); } } @@ -887,7 +887,7 @@ namespace Emby.Dlna.PlayTo string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl); var httpClient = new SsdpHttpClient(_httpClient, _config); - _logger.Debug("Dlna Device.GetRenderingProtocolAsync"); + _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync"); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); rendererCommands = TransportCommands.Create(document); diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 2d0d7c99c1..272f2e1276 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -7,7 +7,7 @@ using Emby.Dlna.Didl; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using MediaBrowser.Model.System; using System; @@ -156,7 +156,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError("Error reporting progress", ex); } } @@ -204,7 +204,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting playback stopped", ex); + _logger.LogError("Error reporting playback stopped", ex); } } @@ -223,7 +223,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError("Error reporting progress", ex); } } @@ -247,7 +247,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError("Error reporting progress", ex); } } @@ -278,7 +278,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error reporting progress", ex); + _logger.LogError("Error reporting progress", ex); } } @@ -319,7 +319,7 @@ namespace Emby.Dlna.PlayTo public async Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken) { - _logger.Debug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); + _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId); @@ -351,7 +351,7 @@ namespace Emby.Dlna.PlayTo } } - _logger.Debug("{0} - Playlist created", _session.DeviceName); + _logger.LogDebug("{0} - Playlist created", _session.DeviceName); if (command.PlayCommand == PlayCommand.PlayLast) { @@ -539,7 +539,7 @@ namespace Emby.Dlna.PlayTo return _logger; } - return new NullLogger(); + return null; } private PlaylistItem GetPlaylistItem(BaseItem item, List mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) @@ -599,7 +599,7 @@ namespace Emby.Dlna.PlayTo { Playlist.Clear(); Playlist.AddRange(items); - _logger.Debug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count); + _logger.LogDebug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count); await SetPlaylistIndex(0).ConfigureAwait(false); return true; diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index ed3cf311b0..0384d8f11c 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System; using System.Collections.Generic; @@ -93,7 +93,7 @@ namespace Emby.Dlna.PlayTo if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 && nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1) { - //_logger.Debug("Upnp device {0} does not contain a MediaRenderer device (0).", location); + //_logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location); return; } @@ -121,7 +121,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.ErrorException("Error creating PlayTo device.", ex); + _logger.LogError("Error creating PlayTo device.", ex); } finally { @@ -155,9 +155,9 @@ namespace Emby.Dlna.PlayTo private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken) { var uri = info.Location; - _logger.Debug("Attempting to create PlayToController from location {0}", location); + _logger.LogDebug("Attempting to create PlayToController from location {0}", location); - _logger.Debug("Logging session activity from location {0}", location); + _logger.LogDebug("Logging session activity from location {0}", location); string uuid; if (info.Headers.TryGetValue("USN", out uuid)) { @@ -237,7 +237,7 @@ namespace Emby.Dlna.PlayTo SupportsMediaControl = true }); - _logger.Info("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName); + _logger.LogInformation("DLNA Session created for {0} - {1}", device.Properties.Name, device.Properties.ModelName); } } diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 4509414894..55fe7fb80d 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Server; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -20,13 +20,13 @@ namespace Emby.Dlna.Service private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; protected readonly IServerConfigurationManager Config; - protected readonly ILogger Logger; + protected readonly ILogger _logger; protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory; protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory) { Config = config; - Logger = logger; + _logger = logger; XmlReaderSettingsFactory = xmlReaderSettingsFactory; } @@ -52,7 +52,7 @@ namespace Emby.Dlna.Service } catch (Exception ex) { - Logger.ErrorException("Error processing control request", ex); + _logger.LogError("Error processing control request", ex); return new ControlErrorHandler().GetResponse(ex); } @@ -76,7 +76,7 @@ namespace Emby.Dlna.Service } } - Logger.Debug("Received control request {0}", requestInfo.LocalName); + _logger.LogDebug("Received control request {0}", requestInfo.LocalName); var result = GetResult(requestInfo.LocalName, requestInfo.Headers); @@ -118,7 +118,7 @@ namespace Emby.Dlna.Service IsSuccessful = true }; - //Logger.Debug(xml); + //logger.LogDebug(xml); controlResponse.Headers.Add("EXT", string.Empty); @@ -244,7 +244,7 @@ namespace Emby.Dlna.Service var originalHeaders = request.Headers; var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - Logger.Debug("Control request. Headers: {0}", headers); + _logger.LogDebug("Control request. Headers: {0}", headers); } private void LogResponse(ControlResponse response) @@ -258,7 +258,7 @@ namespace Emby.Dlna.Service var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); //builder.Append(response.Xml); - Logger.Debug("Control response. Headers: {0}", headers); + _logger.LogDebug("Control response. Headers: {0}", headers); } } } diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs index bc7f01d974..92b81a7acc 100644 --- a/Emby.Dlna/Service/BaseService.cs +++ b/Emby.Dlna/Service/BaseService.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dlna; using Emby.Dlna.Eventing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Dlna.Service { diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index a75e065c30..85dc4d94f5 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs index 9a313d9d3f..f5de730a10 100644 --- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using MediaBrowser.Model.IO; @@ -78,7 +78,7 @@ namespace Emby.Drawing.ImageMagick private void LogVersion() { - _logger.Info("ImageMagick version: " + GetVersion()); + _logger.LogInformation("ImageMagick version: " + GetVersion()); TestWebp(); Wand.SetMagickThreadCount(1); } @@ -103,7 +103,7 @@ namespace Emby.Drawing.ImageMagick } catch { - //_logger.ErrorException("Error loading webp: ", ex); + //_logger.LogError("Error loading webp: ", ex); _webpAvailable = false; } } @@ -295,7 +295,7 @@ namespace Emby.Drawing.ImageMagick } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError("Error drawing indicator overlay", ex); } } diff --git a/Emby.Drawing.Net/GDIImageEncoder.cs b/Emby.Drawing.Net/GDIImageEncoder.cs index 02e7657ddf..4391cc618e 100644 --- a/Emby.Drawing.Net/GDIImageEncoder.cs +++ b/Emby.Drawing.Net/GDIImageEncoder.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Drawing; using System.Drawing.Drawing2D; @@ -30,7 +30,7 @@ namespace Emby.Drawing.Net private void LogInfo() { - _logger.Info("GDIImageEncoder starting"); + _logger.LogInformation("GDIImageEncoder starting"); using (var stream = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".empty.png")) { using (var img = Image.FromStream(stream)) @@ -38,7 +38,7 @@ namespace Emby.Drawing.Net } } - _logger.Info("GDIImageEncoder started"); + _logger.LogInformation("GDIImageEncoder started"); } public string[] SupportedInputFormats @@ -214,7 +214,7 @@ namespace Emby.Drawing.Net } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError("Error drawing indicator overlay", ex); } } diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs index 9eb7055b4a..185b11f45b 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing.Skia/SkiaEncoder.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SkiaSharp; using System; using System.IO; @@ -81,7 +81,7 @@ namespace Emby.Drawing.Skia // test an operation that requires the native library SKPMColor.PreMultiply(SKColors.Black); - _logger.Info("SkiaSharp version: " + GetVersion()); + _logger.LogInformation("SkiaSharp version: " + GetVersion()); } public static string GetVersion() @@ -530,7 +530,7 @@ namespace Emby.Drawing.Skia throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath)); } - //_logger.Info("Color type {0}", bitmap.Info.ColorType); + //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType); var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height); @@ -660,7 +660,7 @@ namespace Emby.Drawing.Skia } catch (Exception ex) { - _logger.ErrorException("Error drawing indicator overlay", ex); + _logger.LogError("Error drawing indicator overlay", ex); } } diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs index 121e20debd..7b819c2fd6 100644 --- a/Emby.Drawing/Common/ImageHeader.cs +++ b/Emby.Drawing/Common/ImageHeader.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -235,4 +235,4 @@ namespace Emby.Drawing.Common throw new ArgumentException(ErrorMessage); } } -} \ No newline at end of file +} diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 495ba99a65..8cbe5f96a3 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -261,7 +261,7 @@ namespace Emby.Drawing //if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient) //{ // // Just spit out the original file if all the options are default - // _logger.Info("Returning original image {0}", originalImagePath); + // _logger.LogInformation("Returning original image {0}", originalImagePath); // return new ValueTuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); //} @@ -302,7 +302,7 @@ namespace Emby.Drawing { // Decoder failed to decode it #if DEBUG - _logger.ErrorException("Error encoding image", ex); + _logger.LogError("Error encoding image", ex); #endif // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -310,7 +310,7 @@ namespace Emby.Drawing catch (Exception ex) { // If it fails for whatever reason, return the original image - _logger.ErrorException("Error encoding image", ex); + _logger.LogError("Error encoding image", ex); // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -464,7 +464,7 @@ namespace Emby.Drawing } var path = info.Path; - _logger.Info("Getting image size for item {0} {1}", item.GetType().Name, path); + _logger.LogInformation("Getting image size for item {0} {1}", item.GetType().Name, path); var size = GetImageSize(path, allowSlowMethods); @@ -603,7 +603,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.ErrorException("Image conversion failed for {0}", ex, originalImagePath); + _logger.LogError("Image conversion failed for {0}", ex, originalImagePath); } } @@ -660,7 +660,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.ErrorException("Error enhancing image", ex); + _logger.LogError("Error enhancing image", ex); } return new ValueTuple(originalImagePath, dateModified, inputImageSupportsTransparency); @@ -827,11 +827,11 @@ namespace Emby.Drawing public void CreateImageCollage(ImageCollageOptions options) { - _logger.Info("Creating image collage and saving to {0}", options.OutputPath); + _logger.LogInformation("Creating image collage and saving to {0}", options.OutputPath); _imageEncoder.CreateImageCollage(options); - _logger.Info("Completed creation of image collage and saved to {0}", options.OutputPath); + _logger.LogInformation("Completed creation of image collage and saved to {0}", options.OutputPath); } public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType) @@ -853,7 +853,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name); + _logger.LogError("Error in image enhancer: {0}", ex, i.GetType().Name); } } diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs index 620d3bae9e..e6986ddcbe 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs @@ -4,7 +4,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using System.Runtime.InteropServices; @@ -20,7 +20,7 @@ namespace IsoMounter private readonly IEnvironmentInfo EnvironmentInfo; private readonly bool ExecutablesAvailable; private readonly IFileSystem FileSystem; - private readonly ILogger Logger; + private readonly ILogger _logger; private readonly string MountCommand; private readonly string MountPointRoot; private readonly IProcessFactory ProcessFactory; @@ -36,24 +36,24 @@ namespace IsoMounter EnvironmentInfo = environment; FileSystem = fileSystem; - Logger = logger; + _logger = logger; ProcessFactory = processFactory; MountPointRoot = FileSystem.DirectorySeparatorChar + "tmp" + FileSystem.DirectorySeparatorChar + "Emby"; - Logger.Debug( + _logger.LogDebug( "[{0}] System PATH is currently set to [{1}].", Name, EnvironmentInfo.GetEnvironmentVariable("PATH") ?? "" ); - Logger.Debug( + _logger.LogDebug( "[{0}] System path separator is [{1}].", Name, EnvironmentInfo.PathSeparator ); - Logger.Debug( + _logger.LogDebug( "[{0}] Mount point root is [{1}].", Name, MountPointRoot @@ -65,7 +65,7 @@ namespace IsoMounter SudoCommand = GetFullPathForExecutable("sudo"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [sudo] located at [{1}].", Name, SudoCommand @@ -73,7 +73,7 @@ namespace IsoMounter MountCommand = GetFullPathForExecutable("mount"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [mount] located at [{1}].", Name, MountCommand @@ -81,7 +81,7 @@ namespace IsoMounter UmountCommand = GetFullPathForExecutable("umount"); - Logger.Info( + _logger.LogInformation( "[{0}] Using version of [umount] located at [{1}].", Name, UmountCommand @@ -119,7 +119,7 @@ namespace IsoMounter { if (EnvironmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux) { - Logger.Info( + _logger.LogInformation( "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].", Name, path, @@ -182,7 +182,7 @@ namespace IsoMounter return; } - Logger.Info( + _logger.LogInformation( "[{0}] Disposing [{1}].", Name, disposing.ToString() @@ -230,7 +230,7 @@ namespace IsoMounter var uid = getuid(); - Logger.Debug( + _logger.LogDebug( "[{0}] Our current UID is [{1}], GetUserId() returned [{2}].", Name, uid.ToString(), @@ -267,13 +267,13 @@ namespace IsoMounter //StreamReader outputReader = process.StandardOutput.; //StreamReader errorReader = process.StandardError; - Logger.Debug( + _logger.LogDebug( "[{0}] Standard output from process is [{1}].", Name, process.StandardOutput.ReadToEnd() ); - Logger.Debug( + _logger.LogDebug( "[{0}] Standard error from process is [{1}].", Name, process.StandardError.ReadToEnd() @@ -283,7 +283,7 @@ namespace IsoMounter processFailed = true; - Logger.Debug( + _logger.LogDebug( "[{0}] Unhandled exception executing command, exception is [{1}].", Name, ex.Message @@ -308,13 +308,13 @@ namespace IsoMounter if (!string.IsNullOrEmpty(isoPath)) { - Logger.Info( + _logger.LogInformation( "[{0}] Attempting to mount [{1}].", Name, isoPath ); - Logger.Debug( + _logger.LogDebug( "[{0}] ISO will be mounted at [{1}].", Name, mountPoint @@ -342,7 +342,7 @@ namespace IsoMounter cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint); } - Logger.Debug( + _logger.LogDebug( "[{0}] Mount command [{1}], mount arguments [{2}].", Name, cmdFilename, @@ -351,7 +351,7 @@ namespace IsoMounter if (ExecuteCommand(cmdFilename, cmdArguments)) { - Logger.Info( + _logger.LogInformation( "[{0}] ISO mount completed successfully.", Name ); @@ -360,7 +360,7 @@ namespace IsoMounter } else { - Logger.Info( + _logger.LogInformation( "[{0}] ISO mount completed with errors.", Name ); @@ -371,7 +371,7 @@ namespace IsoMounter } catch (Exception ex) { - Logger.Info( + _logger.LogInformation( "[{0}] Unhandled exception removing mount point, exception is [{1}].", Name, ex.Message @@ -395,7 +395,7 @@ namespace IsoMounter if (mount != null) { - Logger.Info( + _logger.LogInformation( "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].", Name, mount.IsoPath, @@ -416,7 +416,7 @@ namespace IsoMounter cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath); } - Logger.Debug( + _logger.LogDebug( "[{0}] Umount command [{1}], umount arguments [{2}].", Name, cmdFilename, @@ -425,14 +425,14 @@ namespace IsoMounter if (ExecuteCommand(cmdFilename, cmdArguments)) { - Logger.Info( + _logger.LogInformation( "[{0}] ISO unmount completed successfully.", Name ); } else { - Logger.Info( + _logger.LogInformation( "[{0}] ISO unmount completed with errors.", Name ); @@ -445,7 +445,7 @@ namespace IsoMounter } catch (Exception ex) { - Logger.Info( + _logger.LogInformation( "[{0}] Unhandled exception removing mount point, exception is [{1}].", Name, ex.Message diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs index 9c60f9d0a8..a08a123921 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxMount.cs @@ -1,5 +1,7 @@ using System; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.System; namespace IsoMounter { @@ -79,4 +81,3 @@ namespace IsoMounter } } - diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index bb348d2677..209bc82aa7 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Notifications; using System; using System.Collections.Generic; @@ -25,11 +25,11 @@ namespace Emby.Notifications private INotificationService[] _services; private INotificationTypeFactory[] _typeFactories; - public NotificationManager(ILogManager logManager, IUserManager userManager, IServerConfigurationManager config) + public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config) { _userManager = userManager; _config = config; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } private NotificationOptions GetConfiguration() @@ -126,7 +126,7 @@ namespace Emby.Notifications User = user }; - _logger.Debug("Sending notification via {0} to user {1}", service.Name, user.Name); + _logger.LogDebug("Sending notification via {0} to user {1}", service.Name, user.Name); try { @@ -134,7 +134,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error sending notification to {0}", ex, service.Name); + _logger.LogError("Error sending notification to {0}", ex, service.Name); } } @@ -146,7 +146,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in IsEnabledForUser", ex); + _logger.LogError("Error in IsEnabledForUser", ex); return false; } } @@ -177,7 +177,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in GetNotificationTypes", ex); + _logger.LogError("Error in GetNotificationTypes", ex); return new List(); } diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs index 3cadad6c8d..ab78f9f917 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/Notifications.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Notifications; using MediaBrowser.Model.Tasks; using System; @@ -273,7 +273,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.ErrorException("Error sending notification", ex); + _logger.LogError("Error sending notification", ex); } } diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs index 3e998997a7..ace3b2afbf 100644 --- a/Emby.Photos/PhotoProvider.cs +++ b/Emby.Photos/PhotoProvider.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using TagLib; using TagLib.IFD; using TagLib.IFD.Entries; @@ -172,7 +172,7 @@ namespace Emby.Photos } catch (Exception e) { - _logger.ErrorException("Image Provider - Error reading image tag for {0}", e, item.Path); + _logger.LogError("Image Provider - Error reading image tag for {0}", e, item.Path); } } diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index e4b65b58dd..3f7b907a9e 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Updates; using System; @@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.Activity if (item == null) { - //_logger.Warn("PlaybackStopped reported with null media info."); + //_logger.LogWarning("PlaybackStopped reported with null media info."); return; } @@ -160,7 +160,7 @@ namespace Emby.Server.Implementations.Activity if (item == null) { - //_logger.Warn("PlaybackStart reported with null media info."); + //_logger.LogWarning("PlaybackStart reported with null media info."); return; } @@ -284,7 +284,7 @@ namespace Emby.Server.Implementations.Activity Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username), Type = "AuthenticationFailed", ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint), - Severity = LogSeverity.Error + Severity = LogLevel.Error }); } @@ -468,7 +468,7 @@ namespace Emby.Server.Implementations.Activity Type = NotificationType.TaskFailed.ToString(), Overview = string.Join(Environment.NewLine, vals.ToArray()), ShortOverview = runningTime, - Severity = LogSeverity.Error + Severity = LogLevel.Error }); } } diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs index 047bebf231..b0c8413978 100644 --- a/Emby.Server.Implementations/Activity/ActivityManager.cs +++ b/Emby.Server.Implementations/Activity/ActivityManager.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Linq; diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index 7f76d724be..a84d6d45fd 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -6,7 +6,7 @@ using System.Linq; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using MediaBrowser.Model.Activity; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using SQLitePCL.pretty; using MediaBrowser.Model.Extensions; @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.ErrorException("Error loading database file. Will reset and retry.", ex); + Logger.LogError("Error loading database file. Will reset and retry.", ex); FileSystem.DeleteFile(DbFilePath); @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.ErrorException("Error migrating activity log database", ex); + Logger.LogError("Error migrating activity log database", ex); } } @@ -308,7 +308,7 @@ namespace Emby.Server.Implementations.Activity index++; if (reader[index].SQLiteType != SQLiteType.Null) { - info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader[index].ToString(), true); + info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true); } return info; diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 385b4bd518..f55da91a8c 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -9,7 +9,7 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase @@ -99,12 +99,12 @@ namespace Emby.Server.Implementations.AppBase /// The application paths. /// The log manager. /// The XML serializer. - protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem) + protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { CommonApplicationPaths = applicationPaths; XmlSerializer = xmlSerializer; FileSystem = fileSystem; - Logger = logManager.GetLogger(GetType().Name); + Logger = loggerFactory.CreateLogger(GetType().Name); UpdateCachePath(); } @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.AppBase /// public void SaveConfiguration() { - Logger.Info("Saving system configuration"); + Logger.LogInformation("Saving system configuration"); var path = CommonApplicationPaths.SystemConfigurationFilePath; FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path)); @@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception ex) { - Logger.ErrorException("Error loading configuration file: {0}", ex, path); + Logger.LogError("Error loading configuration file: {0}", ex, path); return Activator.CreateInstance(configurationType); } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ad15b015de..455e4c311b 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -80,7 +80,7 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.News; @@ -202,10 +202,10 @@ namespace Emby.Server.Implementations public IPlugin[] Plugins { get; protected set; } /// - /// Gets or sets the log manager. + /// Gets or sets the logger factory. /// - /// The log manager. - public ILogManager LogManager { get; protected set; } + /// The logger factory. + public ILoggerFactory LoggerFactory { get; protected set; } /// /// Gets the application paths. @@ -275,12 +275,12 @@ namespace Emby.Server.Implementations /// IConfigurationManager. protected IConfigurationManager GetConfigurationManager() { - return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer, FileSystemManager); + return new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager); } protected virtual IResourceFileManager CreateResourceFileManager() { - return new ResourceFileManager(HttpResultFactory, LogManager.GetLogger("ResourceManager"), FileSystemManager); + return new ResourceFileManager(HttpResultFactory, LoggerFactory.CreateLogger("ResourceManager"), FileSystemManager); } /// @@ -391,7 +391,7 @@ namespace Emby.Server.Implementations /// Initializes a new instance of the class. /// public ApplicationHost(ServerApplicationPaths applicationPaths, - ILogManager logManager, + ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, @@ -405,7 +405,7 @@ namespace Emby.Server.Implementations // hack alert, until common can target .net core BaseExtensions.CryptographyProvider = CryptographyProvider; - XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer")); + XmlSerializer = new MyXmlSerializer(fileSystem, LoggerFactory.CreateLogger("XmlSerializer")); NetworkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -413,13 +413,13 @@ namespace Emby.Server.Implementations SystemEvents = systemEvents; ApplicationPaths = applicationPaths; - LogManager = logManager; + LoggerFactory = loggerFactory; FileSystemManager = fileSystem; ConfigurationManager = GetConfigurationManager(); // Initialize this early in case the -v command line option is used - Logger = LogManager.GetLogger("App"); + Logger = LoggerFactory.CreateLogger("App"); StartupOptions = options; ReleaseAssetFilename = releaseAssetFilename; @@ -427,7 +427,7 @@ namespace Emby.Server.Implementations ImageEncoder = imageEncoder; - SetBaseExceptionMessage(); + //SetBaseExceptionMessage(); fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); @@ -480,7 +480,7 @@ namespace Emby.Server.Implementations { if (_deviceId == null) { - _deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager); + _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger("SystemId"), FileSystemManager); } return _deviceId.Value; @@ -545,7 +545,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error creating {0}", ex, type.FullName); + Logger.LogError("Error creating {0}", ex, type.FullName); // Don't blow up in release mode return null; } @@ -625,7 +625,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading assembly {0}", ex, file); + Logger.LogError("Error loading assembly {0}", ex, file); return null; } } @@ -693,7 +693,7 @@ namespace Emby.Server.Implementations return parts; } - + /*/ private void SetBaseExceptionMessage() { var builder = GetBaseExceptionMessage(ApplicationPaths); @@ -701,8 +701,8 @@ namespace Emby.Server.Implementations builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine)); builder.Insert(0, "*** Error Report ***" + Environment.NewLine); - LogManager.ExceptionMessagePrefix = builder.ToString(); - } + LoggerFactory.ExceptionMessagePrefix = builder.ToString(); + }*/ /// /// Runs the startup tasks. @@ -726,20 +726,20 @@ namespace Emby.Server.Implementations // } //} - Logger.Info("ServerId: {0}", SystemId); + Logger.LogInformation("ServerId: {0}", SystemId); var entryPoints = GetExports(); RunEntryPoints(entryPoints, true); - Logger.Info("Core startup complete"); + Logger.LogInformation("Core startup complete"); HttpServer.GlobalResponse = null; - Logger.Info("Post-init migrations complete"); + Logger.LogInformation("Post-init migrations complete"); RunEntryPoints(entryPoints, false); - Logger.Info("All entry points have started"); + Logger.LogInformation("All entry points have started"); - LogManager.RemoveConsoleOutput(); + //LoggerFactory.RemoveConsoleOutput(); } private void RunEntryPoints(IEnumerable entryPoints, bool isBeforeStartup) @@ -752,7 +752,7 @@ namespace Emby.Server.Implementations } var name = entryPoint.GetType().FullName; - Logger.Info("Starting entry point {0}", name); + Logger.LogInformation("Starting entry point {0}", name); var now = DateTime.UtcNow; try { @@ -760,9 +760,9 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error in {0}", ex, name); + Logger.LogError("Error in {0}", ex, name); } - Logger.Info("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); + Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); } } @@ -777,13 +777,13 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error configuring autorun", ex); + Logger.LogError("Error configuring autorun", ex); } } private IJsonSerializer CreateJsonSerializer() { - return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer")); + return new JsonSerializer(FileSystemManager, LoggerFactory.CreateLogger("JsonSerializer")); } public void Init() @@ -799,13 +799,13 @@ namespace Emby.Server.Implementations } JsonSerializer = CreateJsonSerializer(); - + /* OnLoggerLoaded(true); - LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false); + LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false); - LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging + LoggerFactory.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging ? LogSeverity.Debug - : LogSeverity.Info; + : LogSeverity.Info;*/ DiscoverTypes(); @@ -815,10 +815,10 @@ namespace Emby.Server.Implementations FindParts(); } - + /* protected virtual void OnLoggerLoaded(bool isFirstLoad) { - Logger.Info("Application version: {0}", ApplicationVersion); + Logger.LogInformation("Application version: {0}", ApplicationVersion); if (!isFirstLoad) { @@ -836,11 +836,11 @@ namespace Emby.Server.Implementations Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder); } - } + }*/ protected virtual IHttpClient CreateHttpClient() { - return new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent); + return new HttpClientManager.HttpClientManager(ApplicationPaths, LoggerFactory.CreateLogger("HttpClient"), FileSystemManager, GetDefaultUserAgent); } public static IStreamHelper StreamHelper { get; set; } @@ -858,7 +858,7 @@ namespace Emby.Server.Implementations RegisterSingleInstance(JsonSerializer); RegisterSingleInstance(SystemEvents); - RegisterSingleInstance(LogManager, false); + RegisterSingleInstance(LoggerFactory, false); RegisterSingleInstance(Logger); RegisterSingleInstance(EnvironmentInfo); @@ -873,7 +873,7 @@ namespace Emby.Server.Implementations IsoManager = new IsoManager(); RegisterSingleInstance(IsoManager); - TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents); + TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory.CreateLogger("TaskManager"), FileSystemManager, SystemEvents); RegisterSingleInstance(TaskManager); RegisterSingleInstance(XmlSerializer); @@ -890,21 +890,21 @@ namespace Emby.Server.Implementations RegisterSingleInstance(CryptographyProvider); - SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory")); + SocketFactory = new SocketFactory(LoggerFactory.CreateLogger("SocketFactory")); RegisterSingleInstance(SocketFactory); RegisterSingleInstance(PowerManagement); - SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LogManager, FileSystemManager, CryptographyProvider); + SecurityManager = new PluginSecurityManager(this, HttpClient, JsonSerializer, ApplicationPaths, LoggerFactory, FileSystemManager, CryptographyProvider); RegisterSingleInstance(SecurityManager); - InstallationManager = new InstallationManager(LogManager.GetLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); + InstallationManager = new InstallationManager(LoggerFactory.CreateLogger("InstallationManager"), this, ApplicationPaths, HttpClient, JsonSerializer, SecurityManager, ServerConfigurationManager, FileSystemManager, CryptographyProvider, PackageRuntime); RegisterSingleInstance(InstallationManager); ZipClient = new ZipClient(FileSystemManager); RegisterSingleInstance(ZipClient); - HttpResultFactory = new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer, CreateBrotliCompressor()); + HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, CreateBrotliCompressor()); RegisterSingleInstance(HttpResultFactory); RegisterSingleInstance(this); @@ -915,36 +915,40 @@ namespace Emby.Server.Implementations IAssemblyInfo assemblyInfo = new AssemblyInfo(); RegisterSingleInstance(assemblyInfo); - LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LogManager.GetLogger("LocalizationManager"), assemblyInfo, new TextLocalizer()); + LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer, LoggerFactory.CreateLogger("LocalizationManager"), assemblyInfo, new TextLocalizer()); StringExtensions.LocalizationManager = LocalizationManager; RegisterSingleInstance(LocalizationManager); - TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LogManager.GetLogger("TextEncoding"), JsonSerializer); + TextEncoding = new TextEncoding.TextEncoding(FileSystemManager, LoggerFactory.CreateLogger("TextEncoding"), JsonSerializer); RegisterSingleInstance(TextEncoding); BlurayExaminer = new BdInfoExaminer(FileSystemManager, TextEncoding); RegisterSingleInstance(BlurayExaminer); RegisterSingleInstance(new XmlReaderSettingsFactory()); - UserDataManager = new UserDataManager(LogManager, ServerConfigurationManager, () => UserManager); + UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager); RegisterSingleInstance(UserDataManager); UserRepository = GetUserRepository(); // This is only needed for disposal purposes. If removing this, make sure to have the manager handle disposing it RegisterSingleInstance(UserRepository); - var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LogManager.GetLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager); + var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory.CreateLogger("SqliteDisplayPreferencesRepository"), JsonSerializer, ApplicationPaths, FileSystemManager); DisplayPreferencesRepository = displayPreferencesRepo; RegisterSingleInstance(DisplayPreferencesRepository); - var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LogManager.GetLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); + var itemRepo = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory.CreateLogger("SqliteItemRepository"), assemblyInfo, FileSystemManager, EnvironmentInfo, TimerFactory); ItemRepository = itemRepo; RegisterSingleInstance(ItemRepository); AuthenticationRepository = GetAuthenticationRepository(); RegisterSingleInstance(AuthenticationRepository); +<<<<<<< HEAD UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); +======= + UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this, JsonSerializer, FileSystemManager, CryptographyProvider); +>>>>>>> Use Microsoft.Extensions.Logging abstraction RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager); @@ -953,16 +957,16 @@ namespace Emby.Server.Implementations var musicManager = new MusicManager(LibraryManager); RegisterSingleInstance(new MusicManager(LibraryManager)); - LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo); + LibraryMonitor = new LibraryMonitor(LoggerFactory, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager, TimerFactory, SystemEvents, EnvironmentInfo); RegisterSingleInstance(LibraryMonitor); - RegisterSingleInstance(() => new SearchEngine(LogManager, LibraryManager, UserManager)); + RegisterSingleInstance(() => new SearchEngine(LoggerFactory, LibraryManager, UserManager)); CertificateInfo = GetCertificateInfo(true); Certificate = GetCertificate(CertificateInfo); HttpServer = new HttpListenerHost(this, - LogManager.GetLogger("HttpServer"), + LoggerFactory.CreateLogger("HttpServer"), ServerConfigurationManager, "web/index.html", NetworkManager, @@ -983,37 +987,37 @@ namespace Emby.Server.Implementations var encryptionManager = new EncryptionManager(); RegisterSingleInstance(encryptionManager); - DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LogManager.GetLogger("DeviceManager"), NetworkManager); + DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager); RegisterSingleInstance(DeviceManager); var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer); RegisterSingleInstance(newsService); - MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LogManager.GetLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); + MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); RegisterSingleInstance(MediaSourceManager); - SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); + SubtitleManager = new SubtitleManager(LoggerFactory.CreateLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, MediaSourceManager, ServerConfigurationManager, LocalizationManager); RegisterSingleInstance(SubtitleManager); - ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); + ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer); RegisterSingleInstance(ProviderManager); - DtoService = new DtoService(LogManager.GetLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); + DtoService = new DtoService(LoggerFactory.CreateLogger("DtoService"), LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, this, () => DeviceManager, () => MediaSourceManager, () => LiveTvManager); RegisterSingleInstance(DtoService); - ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LogManager.GetLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); + ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory.CreateLogger("ChannelManager"), ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient, ProviderManager); RegisterSingleInstance(ChannelManager); - SessionManager = new SessionManager(UserDataManager, LogManager.GetLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); + SessionManager = new SessionManager(UserDataManager, LoggerFactory.CreateLogger("SessionManager"), LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager, MediaSourceManager, TimerFactory); RegisterSingleInstance(SessionManager); - var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer, this, assemblyInfo); + var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory.CreateLogger("Dlna"), JsonSerializer, this, assemblyInfo); RegisterSingleInstance(dlnaManager); - CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"), ProviderManager); + CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("CollectionManager"), ProviderManager); RegisterSingleInstance(CollectionManager); - PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager, ProviderManager); + PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory.CreateLogger("PlaylistManager"), UserManager, ProviderManager); RegisterSingleInstance(PlaylistManager); LiveTvManager = new LiveTvManager(this, HttpClient, ServerConfigurationManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, ProviderManager, FileSystemManager, SecurityManager, () => ChannelManager); @@ -1022,12 +1026,12 @@ namespace Emby.Server.Implementations UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager); RegisterSingleInstance(UserViewManager); - NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager); + NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager); RegisterSingleInstance(NotificationManager); - RegisterSingleInstance(new DeviceDiscovery(LogManager.GetLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory)); + RegisterSingleInstance(new DeviceDiscovery(LoggerFactory.CreateLogger("IDeviceDiscovery"), ServerConfigurationManager, SocketFactory, TimerFactory)); - ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); + ChapterManager = new ChapterManager(LibraryManager, LoggerFactory.CreateLogger("ChapterManager"), ServerConfigurationManager, ItemRepository); RegisterSingleInstance(ChapterManager); RegisterMediaEncoder(assemblyInfo); @@ -1037,7 +1041,7 @@ namespace Emby.Server.Implementations var activityLogRepo = GetActivityLogRepository(); RegisterSingleInstance(activityLogRepo); - RegisterSingleInstance(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager)); + RegisterSingleInstance(new ActivityManager(LoggerFactory.CreateLogger("ActivityManager"), activityLogRepo, UserManager)); var authContext = new AuthorizationContext(AuthenticationRepository, UserManager); RegisterSingleInstance(authContext); @@ -1046,14 +1050,14 @@ namespace Emby.Server.Implementations AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager); RegisterSingleInstance(AuthService); - SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding); + SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory.CreateLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory, TextEncoding); RegisterSingleInstance(SubtitleEncoder); RegisterSingleInstance(CreateResourceFileManager()); displayPreferencesRepo.Initialize(); - var userDataRepo = new SqliteUserDataRepository(LogManager.GetLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager); + var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger("SqliteUserDataRepository"), ApplicationPaths, FileSystemManager); SetStaticProperties(); @@ -1082,9 +1086,9 @@ namespace Emby.Server.Implementations } } - public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup) + public static void LogEnvironmentInfo(ILogger Logger, IApplicationPaths appPaths, bool isStartup) { - logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths)); + Logger.LogInformation("Jellyfin:\n{ex}", GetBaseExceptionMessage(appPaths).ToString()); } protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths) @@ -1103,17 +1107,6 @@ namespace Emby.Server.Implementations builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem)); builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess)); builder.AppendLine(string.Format("User Interactive: {0}", Environment.UserInteractive)); - - Type type = Type.GetType("Mono.Runtime"); - if (type != null) - { - MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); - if (displayName != null) - { - builder.AppendLine("Mono: " + displayName.Invoke(null, null)); - } - } - builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount)); builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath)); builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath)); @@ -1130,7 +1123,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error setting http limit", ex); + Logger.LogError("Error setting http limit", ex); } } @@ -1189,7 +1182,7 @@ namespace Emby.Server.Implementations //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { - Logger.Error("No private key included in SSL cert {0}.", certificateLocation); + Logger.LogError("No private key included in SSL cert {0}.", certificateLocation); return null; } @@ -1197,14 +1190,14 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading cert from {0}", ex, certificateLocation); + Logger.LogError("Error loading cert from {0}", ex, certificateLocation); return null; } } private IImageProcessor GetImageProcessor() { - return new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder); + return new ImageProcessor(LoggerFactory.CreateLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, ImageEncoder, () => LibraryManager, TimerFactory, () => MediaEncoder); } protected virtual FFMpegInstallInfo GetFfmpegInstallInfo() @@ -1262,7 +1255,8 @@ namespace Emby.Server.Implementations probePath = info.ProbePath; var hasExternalEncoder = string.Equals(info.Version, "external", StringComparison.OrdinalIgnoreCase); - var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(LogManager.GetLogger("MediaEncoder"), + var mediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder( + LoggerFactory.CreateLogger("MediaEncoder"), JsonSerializer, encoderPath, probePath, @@ -1292,7 +1286,7 @@ namespace Emby.Server.Implementations /// Task{IUserRepository}. private IUserRepository GetUserRepository() { - var repo = new SqliteUserRepository(LogManager.GetLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer); + var repo = new SqliteUserRepository(LoggerFactory.CreateLogger("SqliteUserRepository"), ApplicationPaths, JsonSerializer); repo.Initialize(); @@ -1301,7 +1295,7 @@ namespace Emby.Server.Implementations private IAuthenticationRepository GetAuthenticationRepository() { - var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager); + var repo = new AuthenticationRepository(LoggerFactory.CreateLogger("AuthenticationRepository"), ServerConfigurationManager); repo.Initialize(); @@ -1310,7 +1304,7 @@ namespace Emby.Server.Implementations private IActivityRepository GetActivityLogRepository() { - var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager); + var repo = new ActivityRepository(LoggerFactory.CreateLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths, FileSystemManager); repo.Initialize(); @@ -1325,7 +1319,7 @@ namespace Emby.Server.Implementations ((SqliteItemRepository)ItemRepository).ImageProcessor = ImageProcessor; // For now there's no real way to inject these properly - BaseItem.Logger = LogManager.GetLogger("BaseItem"); + BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem"); BaseItem.ConfigurationManager = ServerConfigurationManager; BaseItem.LibraryManager = LibraryManager; BaseItem.ProviderManager = ProviderManager; @@ -1425,7 +1419,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error getting plugin Id from {0}.", ex, plugin.GetType().FullName); + Logger.LogError("Error getting plugin Id from {0}.", ex, plugin.GetType().FullName); } } @@ -1437,7 +1431,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName); + Logger.LogError("Error loading plugin {0}", ex, plugin.GetType().FullName); return null; } @@ -1449,7 +1443,7 @@ namespace Emby.Server.Implementations /// protected void DiscoverTypes() { - Logger.Info("Loading assemblies"); + Logger.LogInformation("Loading assemblies"); var assemblyInfos = GetComposablePartAssemblies(); @@ -1460,11 +1454,11 @@ namespace Emby.Server.Implementations if (path == null) { - Logger.Info("Loading {0}", assembly.FullName); + Logger.LogInformation("Loading {0}", assembly.FullName); } else { - Logger.Info("Loading {0} from {1}", assembly.FullName, path); + Logger.LogInformation("Loading {0} from {1}", assembly.FullName, path); } } @@ -1506,7 +1500,7 @@ namespace Emby.Server.Implementations { if (loaderException != null) { - Logger.Error("LoaderException: " + loaderException.Message); + Logger.LogError("LoaderException: " + loaderException.Message); } } } @@ -1517,7 +1511,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error loading types from assembly", ex); + Logger.LogError("Error loading types from assembly", ex); return new List>(); } @@ -1564,7 +1558,7 @@ namespace Emby.Server.Implementations ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system." : "Error starting Http Server"; - Logger.ErrorException(msg, ex); + Logger.LogError(msg, ex); if (HttpPort == ServerConfiguration.DefaultHttpPort) { @@ -1580,7 +1574,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error starting http server", ex); + Logger.LogError("Error starting http server", ex); throw; } @@ -1615,7 +1609,7 @@ namespace Emby.Server.Implementations // } // catch (Exception ex) // { - // Logger.ErrorException("Error creating ssl cert", ex); + // Logger.LogError("Error creating ssl cert", ex); // return null; // } // } @@ -1672,7 +1666,7 @@ namespace Emby.Server.Implementations if (requiresRestart) { - Logger.Info("App needs to be restarted due to configuration change."); + Logger.LogInformation("App needs to be restarted due to configuration change."); NotifyPendingRestart(); } @@ -1683,7 +1677,7 @@ namespace Emby.Server.Implementations /// public void NotifyPendingRestart() { - Logger.Info("App needs to be restarted."); + Logger.LogInformation("App needs to be restarted."); var changed = !HasPendingRestart; @@ -1720,10 +1714,10 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error sending server restart notification", ex); + Logger.LogError("Error sending server restart notification", ex); } - Logger.Info("Calling RestartInternal"); + Logger.LogInformation("Calling RestartInternal"); RestartInternal(); }); @@ -1849,13 +1843,13 @@ namespace Emby.Server.Implementations { var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion); - Logger.Info("File {0} has version {1}", path, result); + Logger.LogInformation("File {0} has version {1}", path, result); return result; } catch (Exception ex) { - Logger.ErrorException("Error getting version number from {0}", ex, path); + Logger.LogError("Error getting version number from {0}", ex, path); return new Version(1, 0); } @@ -1940,13 +1934,13 @@ namespace Emby.Server.Implementations if (version < minRequiredVersion) { - Logger.Info("Not loading {0} {1} because the minimum supported version is {2}. Please update to the newer version", filename, version, minRequiredVersion); + Logger.LogInformation("Not loading {0} {1} because the minimum supported version is {2}. Please update to the newer version", filename, version, minRequiredVersion); return false; } } catch (Exception ex) { - Logger.ErrorException("Error getting version number from {0}", ex, path); + Logger.LogError("Error getting version number from {0}", ex, path); return false; } @@ -2053,7 +2047,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error getting local Ip address information", ex); + Logger.LogError("Error getting local Ip address information", ex); } return null; @@ -2210,19 +2204,19 @@ namespace Emby.Server.Implementations var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid); - Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, valid); + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid); return valid; } } } catch (OperationCanceledException) { - Logger.Debug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); throw; } catch (Exception ex) { - Logger.Debug("Ping test result to {0}. Success: {1} {2}", apiUrl, false, ex.Message); + Logger.LogDebug("Ping test result to {0}. Success: {1} {2}", apiUrl, false, ex.Message); _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); return false; @@ -2261,7 +2255,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error sending server shutdown notification", ex); + Logger.LogError("Error sending server shutdown notification", ex); } ShutdownInternal(); @@ -2274,7 +2268,7 @@ namespace Emby.Server.Implementations /// private void RegisterServerWithAdministratorAccess() { - Logger.Info("Requesting administrative access to authorize http server"); + Logger.LogInformation("Requesting administrative access to authorize http server"); try { @@ -2286,7 +2280,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error authorizing server", ex); + Logger.LogError("Error authorizing server", ex); } } @@ -2454,7 +2448,7 @@ namespace Emby.Server.Implementations catch (Exception ex) { Console.WriteLine("Error launching url: {0}", url); - Logger.ErrorException("Error launching url: {0}", ex, url); + Logger.LogError("Error launching url: {0}", ex, url); throw; } @@ -2475,7 +2469,7 @@ namespace Emby.Server.Implementations /// The package. protected void OnApplicationUpdated(PackageVersionInfo package) { - Logger.Info("Application has been updated to version {0}", package.versionStr); + Logger.LogInformation("Application has been updated to version {0}", package.versionStr); EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs { @@ -2510,15 +2504,15 @@ namespace Emby.Server.Implementations { var type = GetType(); - LogManager.AddConsoleOutput(); - Logger.Info("Disposing " + type.Name); + //LoggerFactory.AddConsoleOutput(); + Logger.LogInformation("Disposing " + type.Name); var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList(); DisposableParts.Clear(); foreach (var part in parts) { - Logger.Info("Disposing " + part.GetType().Name); + Logger.LogInformation("Disposing " + part.GetType().Name); try { @@ -2526,7 +2520,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name); + Logger.LogError("Error disposing {0}", ex, part.GetType().Name); } } } diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index dfc9c34744..aa04c98f09 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Model.Channels; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; @@ -300,7 +300,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name); + _logger.LogError("Error getting channel information for {0}", ex, channelInfo.Name); } numComplete++; @@ -709,7 +709,7 @@ namespace Emby.Server.Implementations.Channels // Not yet sure why this is causing a problem query.GroupByPresentationUniqueKey = false; - //_logger.Debug("GetChannelItemsInternal"); + //_logger.LogDebug("GetChannelItemsInternal"); // null if came from cache if (itemsResult != null) @@ -849,7 +849,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error writing to channel cache file: {0}", ex, path); + _logger.LogError("Error writing to channel cache file: {0}", ex, path); } } @@ -912,7 +912,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.ErrorException("Error retrieving channel item from database", ex); + _logger.LogError("Error retrieving channel item from database", ex); } if (item == null) @@ -1051,7 +1051,7 @@ namespace Emby.Server.Implementations.Channels { if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes)) { - _logger.Debug("Forcing update due to TrailerTypes {0}", item.Name); + _logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name); forceUpdate = true; } trailer.TrailerTypes = info.TrailerTypes.ToArray(); @@ -1060,7 +1060,7 @@ namespace Emby.Server.Implementations.Channels if (info.DateModified > item.DateModified) { item.DateModified = info.DateModified; - _logger.Debug("Forcing update due to DateModified {0}", item.Name); + _logger.LogDebug("Forcing update due to DateModified {0}", item.Name); forceUpdate = true; } @@ -1069,20 +1069,20 @@ namespace Emby.Server.Implementations.Channels //{ // item.ExternalEtag = info.Etag; // forceUpdate = true; - // _logger.Debug("Forcing update due to ExternalEtag {0}", item.Name); + // _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name); //} if (!internalChannelId.Equals(item.ChannelId)) { forceUpdate = true; - _logger.Debug("Forcing update due to ChannelId {0}", item.Name); + _logger.LogDebug("Forcing update due to ChannelId {0}", item.Name); } item.ChannelId = internalChannelId; if (!item.ParentId.Equals(parentFolderId)) { forceUpdate = true; - _logger.Debug("Forcing update due to parent folder Id {0}", item.Name); + _logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name); } item.ParentId = parentFolderId; @@ -1092,7 +1092,7 @@ namespace Emby.Server.Implementations.Channels if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase)) { forceUpdate = true; - _logger.Debug("Forcing update due to SeriesName {0}", item.Name); + _logger.LogDebug("Forcing update due to SeriesName {0}", item.Name); } hasSeries.SeriesName = info.SeriesName; } @@ -1100,7 +1100,7 @@ namespace Emby.Server.Implementations.Channels if (!string.Equals(item.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase)) { forceUpdate = true; - _logger.Debug("Forcing update due to ExternalId {0}", item.Name); + _logger.LogDebug("Forcing update due to ExternalId {0}", item.Name); } item.ExternalId = info.Id; @@ -1125,7 +1125,7 @@ namespace Emby.Server.Implementations.Channels if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary)) { item.SetImagePath(ImageType.Primary, info.ImageUrl); - _logger.Debug("Forcing update due to ImageUrl {0}", item.Name); + _logger.LogDebug("Forcing update due to ImageUrl {0}", item.Name); forceUpdate = true; } @@ -1134,7 +1134,7 @@ namespace Emby.Server.Implementations.Channels if (item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase)) { item.Tags = item.Tags.Except(new[] { "livestream" }, StringComparer.OrdinalIgnoreCase).ToArray(); - _logger.Debug("Forcing update due to Tags {0}", item.Name); + _logger.LogDebug("Forcing update due to Tags {0}", item.Name); forceUpdate = true; } } @@ -1143,7 +1143,7 @@ namespace Emby.Server.Implementations.Channels if (!item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase)) { item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray(); - _logger.Debug("Forcing update due to Tags {0}", item.Name); + _logger.LogDebug("Forcing update due to Tags {0}", item.Name); forceUpdate = true; } } diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs index b211908d89..bd717bc6ab 100644 --- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Channels private void CleanChannel(Guid id, CancellationToken cancellationToken) { - _logger.Info("Cleaning channel {0} from database", id); + _logger.LogInformation("Cleaning channel {0} from database", id); // Delete all channel items var allIds = _libraryManager.GetItemIds(new InternalItemsQuery diff --git a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs index 9d1b751d75..ab6acf3c57 100644 --- a/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/Channels/RefreshChannelsScheduledTask.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index bcfc58ca15..155d7ed4a0 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -265,7 +265,7 @@ namespace Emby.Server.Implementations.Collections if (child == null) { - _logger.Warn("No collection title exists with the supplied Id"); + _logger.LogWarning("No collection title exists with the supplied Id"); continue; } @@ -365,7 +365,7 @@ namespace Emby.Server.Implementations.Collections } catch (Exception ex) { - _logger.ErrorException("Error creating camera uploads library", ex); + _logger.LogError("Error creating camera uploads library", ex); } _config.Configuration.CollectionsUpgraded = true; diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index 47e2ec0a8f..26a7c421fb 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -14,7 +14,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; @@ -30,11 +30,11 @@ namespace Emby.Server.Implementations.Configuration /// Initializes a new instance of the class. /// /// The application paths. - /// The log manager. + /// The paramref name="loggerFactory" factory. /// The XML serializer. /// The file system. - public ServerConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem) - : base(applicationPaths, logManager, xmlSerializer, fileSystem) + public ServerConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) + : base(applicationPaths, loggerFactory, xmlSerializer, fileSystem) { UpdateMetadataPath(); } diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 76ebff3a81..8e59596dd3 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; using System.Linq; using SQLitePCL; @@ -75,22 +75,22 @@ namespace Emby.Server.Implementations.Data if (!_versionLogged) { _versionLogged = true; - Logger.Info("Sqlite version: " + SQLite3.Version); - Logger.Info("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray())); + Logger.LogInformation("Sqlite version: " + SQLite3.Version); + Logger.LogInformation("Sqlite compiler options: " + string.Join(",", SQLite3.CompilerOptions.ToArray())); } ConnectionFlags connectionFlags; if (isReadOnly) { - //Logger.Info("Opening read connection"); + //Logger.LogInformation("Opening read connection"); //connectionFlags = ConnectionFlags.ReadOnly; connectionFlags = ConnectionFlags.Create; connectionFlags |= ConnectionFlags.ReadWrite; } else { - //Logger.Info("Opening write connection"); + //Logger.LogInformation("Opening write connection"); connectionFlags = ConnectionFlags.Create; connectionFlags |= ConnectionFlags.ReadWrite; } @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.Data { _defaultWal = db.Query("PRAGMA journal_mode").SelectScalarString().First(); - Logger.Info("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal); + Logger.LogInformation("Default journal_mode for {0} is {1}", DbFilePath, _defaultWal); } var queries = new List @@ -235,7 +235,7 @@ namespace Emby.Server.Implementations.Data } db.ExecuteAll(string.Join(";", queries.ToArray())); - Logger.Info("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First()); + Logger.LogInformation("PRAGMA synchronous=" + db.Query("PRAGMA synchronous").SelectScalarString().First()); } protected virtual bool EnableTempStoreMemory @@ -323,7 +323,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error disposing database", ex); + Logger.LogError("Error disposing database", ex); } } diff --git a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs index 8611cabc13..536cf21f6c 100644 --- a/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs +++ b/Emby.Server.Implementations/Data/CleanDatabaseScheduledTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Data var numComplete = 0; var numItems = itemIds.Count; - _logger.Debug("Cleaning {0} items with dead parent links", numItems); + _logger.LogDebug("Cleaning {0} items with dead parent links", numItems); foreach (var itemId in itemIds) { @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Data if (item != null) { - _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty); + _logger.LogInformation("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty); _libraryManager.DeleteItem(item, new DeleteOptions { @@ -75,4 +75,4 @@ namespace Emby.Server.Implementations.Data progress.Report(100); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 09ff7e09d2..307342135e 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using SQLitePCL.pretty; @@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error loading database file. Will reset and retry.", ex); + Logger.LogError("Error loading database file. Will reset and retry.", ex); FileSystem.DeleteFile(DbFilePath); @@ -251,4 +251,4 @@ namespace Emby.Server.Implementations.Data return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 50cd693044..7239eec931 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -24,7 +24,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Reflection; @@ -667,7 +667,7 @@ namespace Emby.Server.Implementations.Data var userDataKey = tuple.Item4; SaveItem(item, topParent, userDataKey, saveItemStatement); - //Logger.Debug(_saveItemCommand.CommandText); + //logger.LogDebug(_saveItemCommand.CommandText); var inheritedTags = tuple.Item5; @@ -886,12 +886,12 @@ namespace Emby.Server.Implementations.Data if (topParent != null) { - //Logger.Debug("Item {0} has top parent {1}", item.Id, topParent.Id); + //logger.LogDebug("Item {0} has top parent {1}", item.Id, topParent.Id); saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N")); } else { - //Logger.Debug("Item {0} has null top parent", item.Id); + //logger.LogDebug("Item {0} has null top parent", item.Id); saveItemStatement.TryBindNull("@TopParentId"); } @@ -1230,7 +1230,7 @@ namespace Emby.Server.Implementations.Data } CheckDisposed(); - //Logger.Info("Retrieving item {0}", id.ToString("N")); + //logger.LogInformation("Retrieving item {0}", id.ToString("N")); using (WriteLock.Read()) { using (var connection = CreateConnection(true)) @@ -1345,7 +1345,7 @@ namespace Emby.Server.Implementations.Data if (type == null) { - //Logger.Debug("Unknown type {0}", typeString); + //logger.LogDebug("Unknown type {0}", typeString); return null; } @@ -1364,7 +1364,7 @@ namespace Emby.Server.Implementations.Data } catch (SerializationException ex) { - Logger.ErrorException("Error deserializing item", ex); + Logger.LogError("Error deserializing item", ex); } } } @@ -2686,7 +2686,7 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - //Logger.Info("GetItemList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -2744,7 +2744,7 @@ namespace Emby.Server.Implementations.Data CheckDisposed(); - //Logger.Info("GetItemList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -2910,14 +2910,14 @@ namespace Emby.Server.Implementations.Data if (elapsed >= slowThreshold) { - Logger.Debug("{2} query time (slow): {0}ms. Query: {1}", + Logger.LogDebug("{2} query time (slow): {0}ms. Query: {1}", Convert.ToInt32(elapsed), commandText, methodName); } else { - //Logger.Debug("{2} query time: {0}ms. Query: {1}", + //logger.LogDebug("{2} query time: {0}ms. Query: {1}", // Convert.ToInt32(elapsed), // commandText, // methodName); @@ -2942,7 +2942,7 @@ namespace Emby.Server.Implementations.Data TotalRecordCount = returnList.Count }; } - //Logger.Info("GetItems: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItems: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -3216,7 +3216,7 @@ namespace Emby.Server.Implementations.Data } CheckDisposed(); - //Logger.Info("GetItemIdsList: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemIdsList: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -3376,7 +3376,7 @@ namespace Emby.Server.Implementations.Data TotalRecordCount = returnList.Count }; } - //Logger.Info("GetItemIds: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemIds: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -5565,7 +5565,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type } CheckDisposed(); - //Logger.Info("GetItemValues: " + _environmentInfo.StackTrace); + //logger.LogInformation("GetItemValues: " + _environmentInfo.StackTrace); var now = DateTime.UtcNow; @@ -5734,7 +5734,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type var list = new List>(); var result = new QueryResult>(); - //Logger.Info("GetItemValues {0}", string.Join(";", statementTexts.ToArray())); + //logger.LogInformation("GetItemValues {0}", string.Join(";", statementTexts.ToArray())); var statements = PrepareAllSafe(db, statementTexts); if (!isReturningZeroItems) diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 07d64a2b0c..6d4ddcedd9 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SQLitePCL.pretty; using MediaBrowser.Controller.Library; @@ -416,4 +416,4 @@ namespace Emby.Server.Implementations.Data // handled by library database } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index da828aa117..9ac255ec44 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using SQLitePCL.pretty; @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.ErrorException("Error migrating users database", ex); + Logger.LogError("Error migrating users database", ex); } } @@ -233,4 +233,4 @@ namespace Emby.Server.Implementations.Data } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index 5e0323ddb4..fe953bfb99 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -3,7 +3,7 @@ using System.IO; using System.Text; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Devices { @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Devices return value; } - _logger.Error("Invalid value found in device id file"); + _logger.LogError("Invalid value found in device id file"); } } catch (DirectoryNotFoundException) @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error reading file", ex); + _logger.LogError("Error reading file", ex); } return null; @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error writing to file", ex); + _logger.LogError("Error writing to file", ex); } } diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index 5c84590ae2..c5c86f5b9d 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Devices; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Session; @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.ErrorException("Error creating camera uploads library", ex); + _logger.LogError("Error creating camera uploads library", ex); } _config.Configuration.CameraUploadUpgraded = true; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 0831b10753..4243099950 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -16,7 +16,7 @@ using MediaBrowser.Controller.Sync; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -225,7 +225,7 @@ namespace Emby.Server.Implementations.Dto catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name); + _logger.LogError("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name); } } @@ -547,7 +547,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info", ex, type); + _logger.LogError("Error getting {0} image info", ex, type); return null; } } @@ -560,7 +560,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError("Error getting {0} image info for {1}", ex, image.Type, image.Path); return null; } } @@ -619,7 +619,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error getting person {0}", ex, c); + _logger.LogError("Error getting person {0}", ex, c); return null; } @@ -1451,7 +1451,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - //_logger.ErrorException("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path); + //_logger.LogError("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path); return null; } } @@ -1464,7 +1464,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.ErrorException("Error in image enhancer: {0}", ex, enhancer.GetType().Name); + _logger.LogError("Error in image enhancer: {0}", ex, enhancer.GetType().Name); } } diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs index 561f5ee12e..cd5fca40d1 100644 --- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using System; using System.Linq; @@ -65,7 +65,7 @@ namespace Emby.Server.Implementations.EntryPoints { DisposeTimer(); - _logger.Info("Automatically restarting the system because it is idle and a restart is required."); + _logger.LogInformation("Automatically restarting the system because it is idle and a restart is required."); try { @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error restarting server", ex); + _logger.LogError("Error restarting server", ex); } } } @@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error getting timers", ex); + _logger.LogError("Error getting timers", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index aa672a1b7a..46fbc94fdc 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using Mono.Nat; using System.Threading; @@ -29,9 +29,9 @@ namespace Emby.Server.Implementations.EntryPoints private NatManager _natManager; - public ExternalPortForwarding(ILogManager logmanager, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory) + public ExternalPortForwarding(ILoggerFactory loggerFactory, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient, ITimerFactory timerFactory) { - _logger = logmanager.GetLogger("PortMapper"); + _logger = loggerFactory.CreateLogger("PortMapper"); _appHost = appHost; _config = config; _deviceDiscovery = deviceDiscovery; @@ -84,7 +84,7 @@ namespace Emby.Server.Implementations.EntryPoints private void Start() { - _logger.Debug("Starting NAT discovery"); + _logger.LogDebug("Starting NAT discovery"); if (_natManager == null) { _natManager = new NatManager(_logger, _httpClient); @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.EntryPoints _usnsHandled.Add(identifier); } - _logger.Debug("Found NAT device: " + identifier); + _logger.LogDebug("Found NAT device: " + identifier); IPAddress address; if (IPAddress.TryParse(info.Location.Host, out address)) @@ -216,7 +216,7 @@ namespace Emby.Server.Implementations.EntryPoints catch { // Commenting out because users are reporting problems out of our control - //_logger.ErrorException("Error creating port forwarding rules", ex); + //_logger.LogError("Error creating port forwarding rules", ex); } } @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations.EntryPoints private Task CreatePortMap(INatDevice device, int privatePort, int publicPort) { - _logger.Debug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString()); + _logger.LogDebug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString()); return device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort) { @@ -284,7 +284,7 @@ namespace Emby.Server.Implementations.EntryPoints private void DisposeNat() { - _logger.Debug("Stopping NAT discovery"); + _logger.LogDebug("Stopping NAT discovery"); if (_timer != null) { @@ -309,7 +309,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error stopping NAT Discovery", ex); + _logger.LogError("Error stopping NAT Discovery", ex); } } } diff --git a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs index 8ae85e3909..a9121ba32d 100644 --- a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs +++ b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using MediaBrowser.Model.System; @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error resetting system standby timer", ex); + _logger.LogError("Error resetting system standby timer", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index 9a2ae34bcb..ff283667bc 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -331,7 +331,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error in GetLibraryUpdateInfo", ex); + _logger.LogError("Error in GetLibraryUpdateInfo", ex); return; } @@ -346,7 +346,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error sending LibraryChanged message", ex); + _logger.LogError("Error sending LibraryChanged message", ex); } } } diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index d41d76c6b8..24cd659e10 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs index e5748989e7..f6a74c4ecf 100644 --- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs @@ -163,7 +163,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception) { - //Logger.ErrorException("Error sending message", ex); + //Logger.LogError("Error sending message", ex); } } @@ -179,7 +179,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception) { - //Logger.ErrorException("Error sending message", ex); + //Logger.LogError("Error sending message", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs index 6d73f98ad3..ffd98bf787 100644 --- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs +++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs @@ -1,7 +1,7 @@ using Emby.Server.Implementations.Browser; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Controller.Configuration; namespace Emby.Server.Implementations.EntryPoints @@ -61,4 +61,4 @@ namespace Emby.Server.Implementations.EntryPoints { } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 5edc5fadef..1bb11ce406 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,7 +1,7 @@ using System; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using Emby.Server.Implementations.Udp; using MediaBrowser.Model.Net; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.ErrorException("Failed to start UDP Server", ex); + _logger.LogError("Failed to start UDP Server", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs index 4507640409..ca79262b0b 100644 --- a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -91,7 +91,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.ErrorException("Error sending anonymous usage statistics.", ex); + //_logger.LogError("Error sending anonymous usage statistics.", ex); } } @@ -119,7 +119,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.ErrorException("Error sending anonymous usage statistics.", ex); + //_logger.LogError("Error sending anonymous usage statistics.", ex); } } diff --git a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs index d9c9e1a400..e962bb59b2 100644 --- a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs +++ b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs @@ -9,7 +9,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.EntryPoints throw new ArgumentException("Client info must have a device Id"); } - _logger.Info("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}", + _logger.LogInformation("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}", app.AppName ?? "Unknown App", app.AppVersion ?? "Unknown", app.DeviceId, diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 36e29e46ae..58309ea1c7 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 583e93706e..7655051095 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -92,4 +92,4 @@ namespace Emby.Server.Implementations.EnvironmentInfo Environment.SetEnvironmentVariable(name, value); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs index fe1df0953b..5f043e1275 100644 --- a/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs +++ b/Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index d53606e878..b3f8ef8848 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -14,7 +14,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Controller.IO; @@ -131,7 +131,7 @@ namespace Emby.Server.Implementations.HttpClientManager var userInfo = uriAddress.UserInfo; if (!string.IsNullOrWhiteSpace(userInfo)) { - _logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url); + _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url); url = url.Replace(userInfo + "@", string.Empty); } @@ -421,11 +421,11 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogRequestAsDebug) { - _logger.Debug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); + _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } else { - _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); + _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url); } } @@ -595,11 +595,11 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogRequestAsDebug) { - _logger.Debug("HttpClientManager.GetTempFileResponse url: {0}", options.Url); + _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } else { - _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url); + _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url); } } @@ -685,7 +685,7 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogErrors) { - _logger.ErrorException("Error " + webException.Status + " getting response from " + options.Url, webException); + _logger.LogError("Error " + webException.Status + " getting response from " + options.Url, webException); } var exception = new HttpException(webException.Message, webException); @@ -723,7 +723,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrors) { - _logger.ErrorException("Error getting response from " + options.Url, ex); + _logger.LogError("Error getting response from " + options.Url, ex); } return ex; @@ -789,7 +789,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrors) { - _logger.Error(msg); + _logger.LogError(msg); } client.LastTimeout = DateTime.UtcNow; @@ -824,7 +824,7 @@ namespace Emby.Server.Implementations.HttpClientManager { var msg = reader.ReadToEnd(); - _logger.Error(msg); + _logger.LogError(msg); } } } diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs index 353ba52821..1a875e5334 100644 --- a/Emby.Server.Implementations/HttpServer/FileWriter.cs +++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs @@ -5,7 +5,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using System.Linq; @@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.HttpServer var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength); Headers["Content-Range"] = rangeString; - Logger.Info("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString); + Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString); } /// @@ -173,7 +173,7 @@ namespace Emby.Server.Implementations.HttpServer if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - Logger.Debug("Transmit file {0}", path); + Logger.LogDebug("Transmit file {0}", path); } //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0; diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 70a233c6fe..2a353584ca 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -252,11 +252,11 @@ namespace Emby.Server.Implementations.HttpServer if (logExceptionStackTrace) { - _logger.ErrorException("Error processing request", ex); + _logger.LogError("Error processing request", ex); } else if (logExceptionMessage) { - _logger.Error(ex.Message); + _logger.LogError(ex.Message); } var httpRes = httpReq.Response; @@ -274,7 +274,7 @@ namespace Emby.Server.Implementations.HttpServer } catch { - //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); + //_logger.LogError("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); } } @@ -320,10 +320,10 @@ namespace Emby.Server.Implementations.HttpServer if (_listener != null) { - _logger.Info("Stopping HttpListener..."); + _logger.LogInformation("Stopping HttpListener..."); var task = _listener.Stop(); Task.WaitAll(task); - _logger.Info("HttpListener stopped"); + _logger.LogInformation("HttpListener stopped"); } } @@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.HttpServer var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) { - _logger.Error("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl); + _logger.LogError("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl); return null; } @@ -729,7 +729,7 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.Error("Could not find handler for {0}", pathInfo); + _logger.LogError("Could not find handler for {0}", pathInfo); return null; } @@ -783,7 +783,7 @@ namespace Emby.Server.Implementations.HttpServer ServiceController = new ServiceController(); - _logger.Info("Calling ServiceStack AppHost.Init"); + _logger.LogInformation("Calling ServiceStack AppHost.Init"); var types = services.Select(r => r.GetType()).ToArray(); @@ -853,7 +853,7 @@ namespace Emby.Server.Implementations.HttpServer //using (var reader = new StreamReader(stream)) //{ // var json = reader.ReadToEnd(); - // Logger.Info(json); + // logger.LogInformation(json); // return _jsonSerializer.DeserializeFromString(json, type); //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); @@ -919,7 +919,7 @@ namespace Emby.Server.Implementations.HttpServer return Task.CompletedTask; } - //_logger.Debug("Websocket message received: {0}", result.MessageType); + //_logger.LogDebug("Websocket message received: {0}", result.MessageType); var tasks = _webSocketListeners.Select(i => Task.Run(async () => { @@ -929,7 +929,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.ErrorException("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty); + _logger.LogError("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty); } })); diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index a0a471cb26..73b2afe640 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -1,6 +1,6 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -37,12 +37,12 @@ namespace Emby.Server.Implementations.HttpServer /// /// Initializes a new instance of the class. /// - public HttpResultFactory(ILogManager logManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor) + public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor) { _fileSystem = fileSystem; _jsonSerializer = jsonSerializer; _brotliCompressor = brotliCompressor; - _logger = logManager.GetLogger("HttpResultFactory"); + _logger = loggerfactory.CreateLogger("HttpResultFactory"); } /// diff --git a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs index 3aa48efd43..5b7bbe79cb 100644 --- a/Emby.Server.Implementations/HttpServer/LoggerUtils.cs +++ b/Emby.Server.Implementations/HttpServer/LoggerUtils.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using MediaBrowser.Model.Services; @@ -11,7 +11,7 @@ namespace Emby.Server.Implementations.HttpServer { if (headers == null) { - logger.Info("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty); + logger.LogInformation("{0} {1}. UserAgent: {2}", "HTTP " + method, url, userAgent ?? string.Empty); } else { @@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.HttpServer index++; } - logger.Info("HTTP {0} {1}. {2}", method, url, headerText); + logger.LogInformation("HTTP {0} {1}. {2}", method, url, headerText); } } @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.HttpServer //var headerText = headers == null ? string.Empty : "Headers: " + string.Join(", ", headers.Where(i => i.Name.IndexOf("Access-", StringComparison.OrdinalIgnoreCase) == -1).Select(i => i.Name + "=" + i.Value).ToArray()); var headerText = string.Empty; - logger.Info("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText); + logger.LogInformation("HTTP Response {0} to {1}. Time: {2}{3}. {4} {5}", statusCode, endPoint, Convert.ToInt32(durationMs).ToString(CultureInfo.InvariantCulture), logSuffix, url, headerText); } } } diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index 4177c7e786..dc20ee1a24 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -226,4 +226,4 @@ namespace Emby.Server.Implementations.HttpServer public string StatusDescription { get; set; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index 385d19b6bc..b1759069cc 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Globalization; using System.Text; @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.HttpServer if (exception != null) { - _logger.ErrorException("Error processing request for {0}", exception, req.RawUrl); + _logger.LogError("Error processing request for {0}", exception, req.RawUrl); if (!string.IsNullOrEmpty(exception.Message)) { diff --git a/Emby.Server.Implementations/HttpServer/StreamWriter.cs b/Emby.Server.Implementations/HttpServer/StreamWriter.cs index 3f394d3acd..0a44a5fe5e 100644 --- a/Emby.Server.Implementations/HttpServer/StreamWriter.cs +++ b/Emby.Server.Implementations/HttpServer/StreamWriter.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index d449e4424a..ca8723dde6 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -1,7 +1,7 @@ using System.Text; using MediaBrowser.Common.Events; using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.ErrorException("Error processing web socket message", ex); + _logger.LogError("Error processing web socket message", ex); } } diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 4be30f8b74..6087f3cf27 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; @@ -38,7 +38,7 @@ namespace Emby.Server.Implementations.IO public FileRefresher(string path, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ITaskManager taskManager, ILogger logger, ITimerFactory timerFactory, IEnvironmentInfo environmentInfo, ILibraryManager libraryManager1) { - logger.Debug("New file refresher created for {0}", path); + logger.LogDebug("New file refresher created for {0}", path); Path = path; _fileSystem = fileSystem; @@ -108,7 +108,7 @@ namespace Emby.Server.Implementations.IO { lock (_timerLock) { - Logger.Debug("Resetting file refresher from {0} to {1}", Path, path); + Logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path); Path = path; AddAffectedPath(path); @@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.IO paths = _affectedPaths.ToList(); } - Logger.Debug("Timer stopped."); + Logger.LogDebug("Timer stopped."); DisposeTimer(); EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger); @@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error processing directory changes", ex); + Logger.LogError("Error processing directory changes", ex); } } @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.IO continue; } - Logger.Info(item.Name + " (" + item.Path + ") will be refreshed."); + Logger.LogInformation(item.Name + " (" + item.Path + ") will be refreshed."); try { @@ -172,11 +172,11 @@ namespace Emby.Server.Implementations.IO // For now swallow and log. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable) // Should we remove it from it's parent? - Logger.ErrorException("Error refreshing {0}", ex, item.Name); + Logger.LogError("Error refreshing {0}", ex, item.Name); } catch (Exception ex) { - Logger.ErrorException("Error refreshing {0}", ex, item.Name); + Logger.LogError("Error refreshing {0}", ex, item.Name); } } } diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index 00fe447f0f..22d1783eda 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Threading; @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, path); + Logger.LogError("Error in ReportFileSystemChanged for {0}", ex, path); } } } @@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO /// /// Initializes a new instance of the class. /// - public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo) + public LibraryMonitor(ILoggerFactory loggerFactory, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo) { if (taskManager == null) { @@ -150,7 +150,7 @@ namespace Emby.Server.Implementations.IO LibraryManager = libraryManager; TaskManager = taskManager; - Logger = logManager.GetLogger(GetType().Name); + Logger = loggerFactory.CreateLogger(GetType().Name); ConfigurationManager = configurationManager; _fileSystem = fileSystem; _timerFactory = timerFactory; @@ -291,7 +291,7 @@ namespace Emby.Server.Implementations.IO if (!_fileSystem.DirectoryExists(path)) { // Seeing a crash in the mono runtime due to an exception being thrown on a different thread - Logger.Info("Skipping realtime monitor for {0} because the path does not exist", path); + Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path); return; } @@ -344,7 +344,7 @@ namespace Emby.Server.Implementations.IO if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; - Logger.Info("Watching directory " + path); + Logger.LogInformation("Watching directory " + path); } else { @@ -354,7 +354,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error watching path: {0}", ex, path); + Logger.LogError("Error watching path: {0}", ex, path); } }); } @@ -382,7 +382,7 @@ namespace Emby.Server.Implementations.IO { using (watcher) { - Logger.Info("Stopping directory watching for path {0}", watcher.Path); + Logger.LogInformation("Stopping directory watching for path {0}", watcher.Path); watcher.Created -= watcher_Changed; watcher.Deleted -= watcher_Changed; @@ -439,7 +439,7 @@ namespace Emby.Server.Implementations.IO var ex = e.GetException(); var dw = (FileSystemWatcher)sender; - Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex); + Logger.LogError("Error in Directory watcher for: " + dw.Path, ex); DisposeWatcher(dw, true); } @@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.IO { try { - //Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath); + //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath); var path = e.FullPath; @@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath); + Logger.LogError("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath); } } @@ -487,13 +487,13 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(i, path)) { - //Logger.Debug("Ignoring change to {0}", path); + //logger.LogDebug("Ignoring change to {0}", path); return true; } if (_fileSystem.ContainsSubPath(i, path)) { - //Logger.Debug("Ignoring change to {0}", path); + //logger.LogDebug("Ignoring change to {0}", path); return true; } @@ -503,7 +503,7 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(parent, path)) { - //Logger.Debug("Ignoring change to {0}", path); + //logger.LogDebug("Ignoring change to {0}", path); return true; } } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 66d7802c6f..42b9ae23bc 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -5,7 +5,7 @@ using System.IO; using System.Linq; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace Emby.Server.Implementations.IO @@ -395,7 +395,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName); + Logger.LogError("Error determining CreationTimeUtc for {0}", ex, info.FullName); return DateTime.MinValue; } } @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName); + Logger.LogError("Error determining LastAccessTimeUtc for {0}", ex, info.FullName); return DateTime.MinValue; } } diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs index 48a5063e80..e918176111 100644 --- a/Emby.Server.Implementations/IO/StreamHelper.cs +++ b/Emby.Server.Implementations/IO/StreamHelper.cs @@ -163,7 +163,7 @@ namespace Emby.Server.Implementations.IO var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false); //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/Emby.Server.Implementations/Library/ConnectManager.cs b/Emby.Server.Implementations/Library/ConnectManager.cs new file mode 100644 index 0000000000..c05385673a --- /dev/null +++ b/Emby.Server.Implementations/Library/ConnectManager.cs @@ -0,0 +1,46 @@ +using MediaBrowser.Common.Events; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Connect; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Connect; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Events; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Serialization; +using MediaBrowser.Model.Users; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Cryptography; +using MediaBrowser.Model.IO; +using MediaBrowser.Controller.Authentication; +using MediaBrowser.Controller.Security; +using MediaBrowser.Controller.Devices; +using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.Plugins; + +namespace Emby.Server.Implementations.Library +{ + public class ConnectManager : IConnectManager + { + public ConnectManager() + { + } + + } +} diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index 59f0a9fc9d..7fb979d66a 100644 --- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -9,7 +9,7 @@ using System.Linq; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index bd823e0c11..52fb8938a6 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller.Resolvers; using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using Emby.Naming.Audio; using Emby.Naming.Common; @@ -351,7 +351,7 @@ namespace Emby.Server.Implementations.Library if (item is LiveTvProgram) { - _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", + _logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", item.GetType().Name, item.Name ?? "Unknown name", item.Path ?? string.Empty, @@ -359,7 +359,7 @@ namespace Emby.Server.Implementations.Library } else { - _logger.Info("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", + _logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}", item.GetType().Name, item.Name ?? "Unknown name", item.Path ?? string.Empty, @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Library foreach (var metadataPath in GetMetadataPaths(item, children)) { - _logger.Debug("Deleting path {0}", metadataPath); + _logger.LogDebug("Deleting path {0}", metadataPath); try { @@ -384,7 +384,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error deleting {0}", ex, metadataPath); + _logger.LogError("Error deleting {0}", ex, metadataPath); } } @@ -400,12 +400,12 @@ namespace Emby.Server.Implementations.Library { if (fileSystemInfo.IsDirectory) { - _logger.Debug("Deleting path {0}", fileSystemInfo.FullName); + _logger.LogDebug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteDirectory(fileSystemInfo.FullName, true); } else { - _logger.Debug("Deleting path {0}", fileSystemInfo.FullName); + _logger.LogDebug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteFile(fileSystemInfo.FullName); } } @@ -489,7 +489,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path); + _logger.LogError("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path); return null; } } @@ -587,7 +587,7 @@ namespace Emby.Server.Implementations.Library { if (parent != null && parent.IsPhysicalRoot) { - _logger.ErrorException("Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", ex, isPhysicalRoot, isVf); + _logger.LogError("Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", ex, isPhysicalRoot, isVf); files = new FileSystemMetadata[] { }; } @@ -639,7 +639,7 @@ namespace Emby.Server.Implementations.Library foreach (var dupe in dupes) { - _logger.Info("Found duplicate path: {0}", dupe); + _logger.LogInformation("Found duplicate path: {0}", dupe); } var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList(); @@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving path {0}", ex, f.FullName); + _logger.LogError("Error resolving path {0}", ex, f.FullName); return null; } }).Where(i => i != null); @@ -735,7 +735,7 @@ namespace Emby.Server.Implementations.Library // In case program data folder was moved if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal)) { - _logger.Info("Resetting root folder path to {0}", rootFolderPath); + _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath); rootFolder.Path = rootFolderPath; } @@ -805,7 +805,7 @@ namespace Emby.Server.Implementations.Library // In case program data folder was moved if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal)) { - _logger.Info("Resetting user root folder path to {0}", userRootPath); + _logger.LogInformation("Resetting user root folder path to {0}", userRootPath); tmpItem.Path = userRootPath; } @@ -827,7 +827,7 @@ namespace Emby.Server.Implementations.Library throw new ArgumentNullException("path"); } - //_logger.Info("FindByPath {0}", path); + //_logger.LogInformation("FindByPath {0}", path); var query = new InternalItemsQuery { @@ -1080,7 +1080,7 @@ namespace Emby.Server.Implementations.Library private async Task PerformLibraryValidation(IProgress progress, CancellationToken cancellationToken) { - _logger.Info("Validating media library"); + _logger.LogInformation("Validating media library"); await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false); @@ -1135,7 +1135,7 @@ namespace Emby.Server.Implementations.Library progress.Report(innerPercent); }); - _logger.Debug("Running post-scan task {0}", task.GetType().Name); + _logger.LogDebug("Running post-scan task {0}", task.GetType().Name); try { @@ -1143,12 +1143,12 @@ namespace Emby.Server.Implementations.Library } catch (OperationCanceledException) { - _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name); + _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name); throw; } catch (Exception ex) { - _logger.ErrorException("Error running postscan task", ex); + _logger.LogError("Error running postscan task", ex); } numComplete++; @@ -1199,7 +1199,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving shortcut file {0}", ex, i); + _logger.LogError("Error resolving shortcut file {0}", ex, i); return null; } }) @@ -1262,7 +1262,7 @@ namespace Emby.Server.Implementations.Library item = RetrieveItem(id); - //_logger.Debug("GetitemById {0}", id); + //_logger.LogDebug("GetitemById {0}", id); if (item != null) { @@ -1440,7 +1440,7 @@ namespace Emby.Server.Implementations.Library return true; } - //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name); + //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name); return false; })) @@ -1506,7 +1506,7 @@ namespace Emby.Server.Implementations.Library return true; } - //_logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name); + //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name); return false; })) @@ -1650,7 +1650,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting intros", ex); + _logger.LogError("Error getting intros", ex); return new List(); } @@ -1670,7 +1670,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting intro files", ex); + _logger.LogError("Error getting intro files", ex); return new List(); } @@ -1693,7 +1693,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value); + _logger.LogError("Unable to locate item with Id {0}.", info.ItemId.Value); } } else if (!string.IsNullOrEmpty(info.Path)) @@ -1705,7 +1705,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.Error("Intro resolver returned null for {0}.", info.Path); + _logger.LogError("Intro resolver returned null for {0}.", info.Path); } else { @@ -1724,12 +1724,12 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error resolving path {0}.", ex, info.Path); + _logger.LogError("Error resolving path {0}.", ex, info.Path); } } else { - _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId."); + _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId."); } return video; @@ -1873,7 +1873,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemAdded event handler", ex); + _logger.LogError("Error in ItemAdded event handler", ex); } } } @@ -1904,7 +1904,7 @@ namespace Emby.Server.Implementations.Library } //var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name; - //_logger.Debug("Saving {0} to database.", logName); + //_logger.LogDebug("Saving {0} to database.", logName); ItemRepository.SaveItems(items, cancellationToken); @@ -1929,7 +1929,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemUpdated event handler", ex); + _logger.LogError("Error in ItemUpdated event handler", ex); } } } @@ -1965,7 +1965,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error in ItemRemoved event handler", ex); + _logger.LogError("Error in ItemRemoved event handler", ex); } } } @@ -2808,7 +2808,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting person", ex); + _logger.LogError("Error getting person", ex); return null; } @@ -2836,7 +2836,7 @@ namespace Emby.Server.Implementations.Library { try { - _logger.Debug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url); + _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url); await _providerManagerFactory().SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index e027e133fb..d0b3152ba7 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System.Collections.Generic; using MediaBrowser.Model.Serialization; @@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.Library { mediaInfo = _json.DeserializeFromFile(cacheFilePath); - //_logger.Debug("Found cached media info"); + //_logger.LogDebug("Found cached media info"); } catch { @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Library delayMs = Math.Max(3000, delayMs); if (delayMs > 0) { - _logger.Info("Waiting {0}ms before probing the live stream", delayMs); + _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); } } @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Library Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); _json.SerializeToFile(mediaInfo, cacheFilePath); - //_logger.Debug("Saved media info to {0}", cacheFilePath); + //_logger.LogDebug("Saved media info to {0}", cacheFilePath); } } @@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.Library mediaStreams = newList; } - _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); mediaSource.Bitrate = mediaInfo.Bitrate; mediaSource.Container = mediaInfo.Container; diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 0dc436800f..2f8a1aa5e0 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -255,7 +255,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting media sources", ex); + _logger.LogError("Error getting media sources", ex); return new List(); } } @@ -476,12 +476,12 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error probing live tv stream", ex); + _logger.LogError("Error probing live tv stream", ex); AddMediaInfo(mediaSource, isAudio); } var json = _jsonSerializer.SerializeToString(mediaSource); - _logger.Info("Live stream opened: " + json); + _logger.LogInformation("Live stream opened: " + json); var clone = _jsonSerializer.DeserializeFromString(json); if (!request.UserId.Equals(Guid.Empty)) @@ -624,7 +624,7 @@ namespace Emby.Server.Implementations.Library { mediaInfo = _jsonSerializer.DeserializeFromFile(cacheFilePath); - //_logger.Debug("Found cached media info"); + //_logger.LogDebug("Found cached media info"); } catch (Exception ex) { @@ -658,7 +658,7 @@ namespace Emby.Server.Implementations.Library _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath)); _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath); - //_logger.Debug("Saved media info to {0}", cacheFilePath); + //_logger.LogDebug("Saved media info to {0}", cacheFilePath); } } @@ -679,7 +679,7 @@ namespace Emby.Server.Implementations.Library mediaStreams = newList; } - _logger.Info("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); mediaSource.Bitrate = mediaInfo.Bitrate; mediaSource.Container = mediaInfo.Container; @@ -815,16 +815,16 @@ namespace Emby.Server.Implementations.Library { liveStream.ConsumerCount--; - _logger.Info("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount); + _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount); if (liveStream.ConsumerCount <= 0) { _openStreams.Remove(id); - _logger.Info("Closing live stream {0}", id); + _logger.LogInformation("Closing live stream {0}", id); await liveStream.Close().ConfigureAwait(false); - _logger.Info("Live stream {0} closed successfully", id); + _logger.LogInformation("Live stream {0} closed successfully", id); } } } @@ -883,4 +883,4 @@ namespace Emby.Server.Implementations.Library } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index a33f101aeb..dbfcf41e8b 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Naming.Audio; using System; using System.Collections.Generic; @@ -128,7 +128,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { if (IsMultiDiscFolder(path, libraryOptions)) { - logger.Debug("Found multi-disc folder: " + path); + logger.LogDebug("Found multi-disc folder: " + path); discSubfolderCount++; } else diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 2ad8396731..71ccd7da8e 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Linq; diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 556748183f..143af40767 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -7,7 +7,7 @@ using System.IO; using System.Linq; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers { diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 1394e3858e..68b6c57ae6 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -14,7 +14,7 @@ using System.Linq; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.Movies { diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index d8343f7c65..0fe42fa736 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Model.Globalization; using Emby.Naming.Common; using Emby.Naming.TV; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Resolvers.TV { @@ -72,7 +72,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (episodeInfo.EpisodeNumber.HasValue && episodeInfo.SeasonNumber.HasValue) { - _logger.Debug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", + _logger.LogDebug("Found folder underneath series with episode number: {0}. Season {1}. Episode {2}", path, episodeInfo.SeasonNumber.Value, episodeInfo.EpisodeNumber.Value); diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 951f439c24..32e8b6120d 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Naming.Common; using Emby.Naming.TV; using System; @@ -131,14 +131,14 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { //if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) //{ - // //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName); + // //logger.LogDebug("Igoring series file or folder marked hidden: {0}", child.FullName); // continue; //} // Can't enforce this because files saved by Bitcasa are always marked System //if ((attributes & FileAttributes.System) == FileAttributes.System) //{ - // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName); + // logger.LogDebug("Igoring series subfolder marked system: {0}", child.FullName); // continue; //} @@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) { - //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); + //logger.LogDebug("{0} is a series because of season folder {1}.", path, child.FullName); return true; } } @@ -181,7 +181,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV } } - //logger.Debug("{0} is not a series folder.", path); + //logger.LogDebug("{0} is not a series folder.", path); return false; } diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index a7db46ef2d..1212ba549e 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Search; using System; @@ -23,12 +23,12 @@ namespace Emby.Server.Implementations.Library private readonly IUserManager _userManager; private readonly ILogger _logger; - public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager) + public SearchEngine(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager) { _libraryManager = libraryManager; _userManager = userManager; - _logger = logManager.GetLogger("SearchEngine"); + _logger = loggerFactory.CreateLogger("SearchEngine"); } public QueryResult GetSearchHints(SearchQuery query) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 3714a7544f..62371799b6 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -32,10 +32,10 @@ namespace Emby.Server.Implementations.Library private Func _userManager; - public UserDataManager(ILogManager logManager, IServerConfigurationManager config, Func userManager) + public UserDataManager(ILoggerFactory loggerFactory, IServerConfigurationManager config, Func userManager) { _config = config; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _userManager = userManager; } diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index da80a48247..2e675ee7e7 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -15,7 +15,7 @@ using MediaBrowser.Model.Connect; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; using System; @@ -340,7 +340,7 @@ namespace Emby.Server.Implementations.Library UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1); } - _logger.Info("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied"); + _logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied"); return success ? user : null; } @@ -392,7 +392,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error authenticating with provider {0}", ex, provider.Name); + _logger.LogError("Error authenticating with provider {0}", ex, provider.Name); return false; } @@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.Library if (newValue >= maxCount) { - //_logger.Debug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture)); + //_logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue.ToString(CultureInfo.InvariantCulture)); //user.Policy.IsDisabled = true; //fireLockout = true; @@ -575,7 +575,7 @@ namespace Emby.Server.Implementations.Library catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name); + _logger.LogError("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name); } } @@ -599,7 +599,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError("Error getting {0} image info for {1}", ex, image.Type, image.Path); return null; } } @@ -775,7 +775,7 @@ namespace Emby.Server.Implementations.Library } catch (IOException ex) { - _logger.ErrorException("Error deleting file {0}", ex, configPath); + _logger.LogError("Error deleting file {0}", ex, configPath); } DeleteUserPolicy(user); @@ -1045,7 +1045,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error reading policy file: {0}", ex, path); + _logger.LogError("Error reading policy file: {0}", ex, path); return GetDefaultPolicy(user); } @@ -1109,7 +1109,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error deleting policy file", ex); + _logger.LogError("Error deleting policy file", ex); } } @@ -1144,7 +1144,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.ErrorException("Error reading policy file: {0}", ex, path); + _logger.LogError("Error reading policy file: {0}", ex, path); return new UserConfiguration(); } diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs index 4d718dbee8..eee66c8ac5 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs index cd2aab4c82..593a9a1ef4 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError("Error refreshing {0}", ex, name); } numComplete++; @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Library.Validators continue; } - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs index ee6c4461c2..ea1f2e552e 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs index f7fbb93318..ffa5608ddd 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError("Error refreshing {0}", ex, name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs index be46decfb1..4f4133340c 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs @@ -3,7 +3,7 @@ using System; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs index d71e77a9a7..e59b747de4 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError("Error refreshing {0}", ex, name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs index cd40215486..edc6f3ad6d 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs index 98d53c1250..ec8568afcc 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError("Error refreshing {0}", ex, name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index 1f4e1de924..a4949099ab 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; @@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.Library.Validators var numPeople = people.Count; - _logger.Debug("Will refresh {0} people", numPeople); + _logger.LogDebug("Will refresh {0} people", numPeople); foreach (var person in people) { @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error validating IBN entry {0}", ex, person); + _logger.LogError("Error validating IBN entry {0}", ex, person); } // Update progress @@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.Library.Validators foreach (var item in deadEntities) { - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { @@ -108,7 +108,7 @@ namespace Emby.Server.Implementations.Library.Validators progress.Report(100); - _logger.Info("People validation complete"); + _logger.LogInformation("People validation complete"); } } } diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs index d23efb6d3b..45747dda1c 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs index f306309b3c..fec9890328 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.ErrorException("Error refreshing {0}", ex, name); + _logger.LogError("Error refreshing {0}", ex, name); } numComplete++; @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.Library.Validators foreach (var item in deadEntities) { - _logger.Info("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); + _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name); _libraryManager.DeleteItem(item, new DeleteOptions { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 0c7980ca0b..327b0181a6 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -8,7 +8,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV { @@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source is infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) { - _logger.Info("Opened recording stream from tuner provider"); + _logger.LogInformation("Opened recording stream from tuner provider"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); @@ -86,7 +86,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file {0}", targetFile); + _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); @@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 167f2a84b2..11cb57ff78 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -12,7 +12,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -170,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating virtual folder", ex); + _logger.LogError("Error creating virtual folder", ex); } pathsAdded.AddRange(pathsToCreate); @@ -196,13 +196,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error creating recording folders", ex); + _logger.LogError("Error creating recording folders", ex); } } private async Task RemovePathFromLibrary(string path) { - _logger.Debug("Removing path from library: {0}", path); + _logger.LogDebug("Removing path from library: {0}", path); var requiresRefresh = false; var virtualFolders = _libraryManager.GetVirtualFolders() @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing virtual folder", ex); + _logger.LogError("Error removing virtual folder", ex); } } else @@ -236,7 +236,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error removing media path", ex); + _logger.LogError("Error removing media path", ex); } } } @@ -342,7 +342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError("Error getting channels", ex); } } @@ -364,7 +364,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error adding metadata", ex); + _logger.LogError("Error adding metadata", ex); } } } @@ -406,7 +406,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var channel in channels) { - _logger.Info("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); + _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id); } result = new EpgChannelData(channels); @@ -595,7 +595,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error getting channels", ex); + _logger.LogError("Error getting channels", ex); } } @@ -718,7 +718,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -984,11 +984,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId)) { - _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); continue; } - _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false); @@ -996,7 +996,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (epgChannel == null) { - _logger.Debug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); + _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty); programs = new List(); } else @@ -1042,7 +1042,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public async Task GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List currentLiveStreams, CancellationToken cancellationToken) { - _logger.Info("Streaming Channel " + channelId); + _logger.LogInformation("Streaming Channel " + channelId); var result = string.IsNullOrEmpty(streamId) ? null : @@ -1052,7 +1052,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { result.ConsumerCount++; - _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); + _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount); return result; } @@ -1067,7 +1067,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV result.OriginalStreamId = streamId; - _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); + _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId); return result; } @@ -1174,7 +1174,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var timer = e.Argument; - _logger.Info("Recording timer fired for {0}.", timer.Name); + _logger.LogInformation("Recording timer fired for {0}.", timer.Name); try { @@ -1182,7 +1182,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingEndDate <= DateTime.UtcNow) { - _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); + _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id); OnTimerOutOfDate(timer); return; } @@ -1190,7 +1190,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false); if (!registration.IsValid) { - _logger.Warn("Emby Premiere required to use Emby DVR."); + _logger.LogWarning("Emby Premiere required to use Emby DVR."); OnTimerOutOfDate(timer); return; } @@ -1208,7 +1208,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _logger.Info("Skipping RecordStream because it's already in progress."); + _logger.LogInformation("Skipping RecordStream because it's already in progress."); } } catch (OperationCanceledException) @@ -1217,7 +1217,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error recording stream", ex); + _logger.LogError("Error recording stream", ex); } } @@ -1342,7 +1342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } if (programInfo == null) { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } @@ -1390,9 +1390,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var duration = recordingEndDate - DateTime.UtcNow; - _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); - _logger.Info("Writing file to path: " + recordPath); + _logger.LogInformation("Writing file to path: " + recordPath); Action onStarted = async () => { @@ -1414,16 +1414,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false); recordingStatus = RecordingStatus.Completed; - _logger.Info("Recording completed: {0}", recordPath); + _logger.LogInformation("Recording completed: {0}", recordPath); } catch (OperationCanceledException) { - _logger.Info("Recording stopped: {0}", recordPath); + _logger.LogInformation("Recording stopped: {0}", recordPath); recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { - _logger.ErrorException("Error recording to {0}", ex, recordPath); + _logger.LogError("Error recording to {0}", ex, recordPath); recordingStatus = RecordingStatus.Error; } @@ -1435,7 +1435,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error closing live stream", ex); + _logger.LogError("Error closing live stream", ex); } } @@ -1450,7 +1450,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) { const int retryIntervalSeconds = 60; - _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds); + _logger.LogInformation("Retrying recording in {0} seconds.", retryIntervalSeconds); timer.Status = RecordingStatus.New; timer.PrePaddingSeconds = 0; @@ -1511,20 +1511,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting 0-byte failed recording file {0}", ex, path); + _logger.LogError("Error deleting 0-byte failed recording file {0}", ex, path); } } } private void TriggerRefresh(string path) { - _logger.Info("Triggering refresh on {0}", path); + _logger.LogInformation("Triggering refresh on {0}", path); var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); if (item != null) { - _logger.Info("Refreshing recording parent {0}", item.Path); + _logger.LogInformation("Refreshing recording parent {0}", item.Path); _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) { @@ -1642,7 +1642,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting item", ex); + _logger.LogError("Error deleting item", ex); } } } @@ -1668,7 +1668,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error deleting recording", ex); + _logger.LogError("Error deleting recording", ex); } } } @@ -1773,14 +1773,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV UseShellExecute = false }); - _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); process.Exited += Process_Exited; process.Start(); } catch (Exception ex) { - _logger.ErrorException("Error running recording post processor", ex); + _logger.LogError("Error running recording post processor", ex); } } @@ -1794,7 +1794,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var process = (IProcess)sender; try { - _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode); + _logger.LogInformation("Recording post-processing script completed with exit code {0}", process.ExitCode); } catch { @@ -1875,7 +1875,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError("Error saving recording image", ex); } } @@ -1890,7 +1890,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError("Error saving recording image", ex); } } @@ -1903,7 +1903,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError("Error saving recording image", ex); } } @@ -1916,7 +1916,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving recording image", ex); + _logger.LogError("Error saving recording image", ex); } } } @@ -1984,7 +1984,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error saving nfo", ex); + _logger.LogError("Error saving nfo", ex); } } @@ -2790,7 +2790,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase)) { - _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); + _logger.LogInformation("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url); configuredDevice.Url = device.Url; await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false); @@ -2807,14 +2807,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV foreach (var device in discoveredDevices) { - _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url); + _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url); } return discoveredDevices; } catch (Exception ex) { - _logger.ErrorException("Error discovering tuner devices", ex); + _logger.LogError("Error discovering tuner devices", ex); return new List(); } @@ -2827,4 +2827,4 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return manager.GetConfiguration("xbmcmetadata"); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 9506a82beb..af5e96c057 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -8,7 +8,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; - using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -18,7 +17,7 @@ using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Library; @@ -78,7 +77,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false); - _logger.Info("Recording completed to file {0}", targetFile); + _logger.LogInformation("Recording completed to file {0}", targetFile); } private EncodingOptions GetEncodingOptions() @@ -112,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _process = process; var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - _logger.Info(commandLineLogMessage); + _logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(logFilePath)); @@ -137,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback StartStreamingLog(process.StandardError.BaseStream, _logFileStream); - _logger.Info("ffmpeg recording process started for {0}", _targetPath); + _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); return _taskCompletionSource.Task; } @@ -270,14 +269,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Stopping ffmpeg recording process for {0}", _targetPath); //process.Kill(); _process.StandardInput.WriteLine("q"); } catch (Exception ex) { - _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath); + _logger.LogError("Error stopping recording transcoding job for {0}", ex, _targetPath); } if (_hasExited) @@ -287,7 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath); + _logger.LogInformation("Calling recording process.WaitForExit for {0}", _targetPath); if (_process.WaitForExit(10000)) { @@ -296,7 +295,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath); + _logger.LogError("Error waiting for recording process to exit for {0}", ex, _targetPath); } if (_hasExited) @@ -306,13 +305,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.Info("Killing ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Killing ffmpeg recording process for {0}", _targetPath); _process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath); + _logger.LogError("Error killing recording transcoding job for {0}", ex, _targetPath); } } } @@ -330,7 +329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var exitCode = process.ExitCode; - _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath); + _logger.LogInformation("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath); if (exitCode == 0) { @@ -343,7 +342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch { - _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath); + _logger.LogError("FFMpeg recording exited with an error for {0}.", _targetPath); _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath))); } } @@ -358,7 +357,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error disposing recording log stream", ex); + _logger.LogError("Error disposing recording log stream", ex); } _logFileStream = null; @@ -388,8 +387,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error reading ffmpeg recording log", ex); + _logger.LogError("Error reading ffmpeg recording log", ex); } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 4ba2269a61..813a7a5f9a 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (_items == null) { - Logger.Info("Loading live tv data from {0}", _dataPath); + Logger.LogInformation("Loading live tv data from {0}", _dataPath); _items = GetItemsFromFile(_dataPath); } return _items.ToList(); @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - Logger.ErrorException("Error deserializing {0}", ex, jsonFile); + Logger.LogError("Error deserializing {0}", ex, jsonFile); } return new List(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 63cd26c7e1..620ba76501 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using MediaBrowser.Model.IO; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index b5f93b8828..f00a54c7f3 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Events; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Concurrent; @@ -122,7 +122,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (startDate < now) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = item }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = item }, base.Logger); return; } @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.ErrorException("Error scheduling wake timer", ex); + _logger.LogError("Error scheduling wake timer", ex); } } @@ -153,12 +153,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (_timers.TryAdd(item.Id, timer)) { - _logger.Info("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); } else { timer.Dispose(); - _logger.Warn("Timer already exists for item {0}", item.Id); + _logger.LogWarning("Timer already exists for item {0}", item.Id); } } @@ -178,7 +178,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var timer = GetAll().FirstOrDefault(i => string.Equals(i.Id, timerId, StringComparison.OrdinalIgnoreCase)); if (timer != null) { - EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = timer }, Logger); + EventHelper.FireEventIfNotNull(TimerFired, this, new GenericEventArgs { Argument = timer }, base.Logger); } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 2d0eaf25ba..48b4e58339 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (string.IsNullOrEmpty(token)) { - _logger.Warn("SchedulesDirect token is empty, returning empty program list"); + _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); return programsInfo; } @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings string stationID = channelId; - _logger.Info("Channel Station ID is: " + stationID); + _logger.LogInformation("Channel Station ID is: " + stationID); List requestList = new List() { @@ -100,7 +100,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings }; var requestString = _jsonSerializer.SerializeToString(requestList); - _logger.Debug("Request string for schedules is: " + requestString); + _logger.LogDebug("Request string for schedules is: " + requestString); var httpOptions = new HttpRequestOptions() { @@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings StreamReader reader = new StreamReader(response.Content); string responseString = reader.ReadToEnd(); var dailySchedules = _jsonSerializer.DeserializeFromString>(responseString); - _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); + _logger.LogDebug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); httpOptions = new HttpRequestOptions() { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var schedules = dailySchedules.SelectMany(d => d.programs); foreach (ScheduleDirect.Program schedule in schedules) { - //_logger.Debug("Proccesing Schedule for statio ID " + stationID + + //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID + // " which corresponds to channel " + channelNumber + " and program id " + // schedule.programID + " which says it has images? " + // programDict[schedule.programID].hasImageArtwork); @@ -453,7 +453,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings url = apiUrl + "/image/" + uri; } } - //_logger.Debug("URL for image is : " + url); + //_logger.LogDebug("URL for image is : " + url); return url; } @@ -527,7 +527,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.ErrorException("Error getting image info from schedules direct", ex); + _logger.LogError("Error getting image info from schedules direct", ex); return new List(); } @@ -578,14 +578,14 @@ namespace Emby.Server.Implementations.LiveTv.Listings } else { - _logger.Info("No lineups available"); + _logger.LogInformation("No lineups available"); } } } } catch (Exception ex) { - _logger.Error("Error getting headends", ex); + _logger.LogError("Error getting headends", ex); } return lineups; @@ -750,7 +750,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken = cancellationToken, LogErrorResponseBody = true }; - //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + + //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + // httpOptions.RequestContent); using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false)) @@ -758,7 +758,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var root = await _jsonSerializer.DeserializeFromStreamAsync(responce.Content).ConfigureAwait(false); if (root.message == "OK") { - _logger.Info("Authenticated with Schedules Direct token: " + root.token); + _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); return root.token; } @@ -780,7 +780,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new ArgumentException("Listings Id required"); } - _logger.Info("Adding new LineUp "); + _logger.LogInformation("Adding new LineUp "); var httpOptions = new HttpRequestOptions() { @@ -823,7 +823,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new Exception("token required"); } - _logger.Info("Headends on account "); + _logger.LogInformation("Headends on account "); var options = new HttpRequestOptions() { @@ -927,8 +927,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings using (var response = httpResponse.Content) { var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); - _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); - _logger.Info("Mapping Stations to Channel"); + _logger.LogInformation("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); + _logger.LogInformation("Mapping Stations to Channel"); var allStations = root.stations ?? new List(); diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index b0ffd057d4..cc8840e14a 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading; @@ -376,7 +376,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting image info for {0}", ex, info.Name); + _logger.LogError("Error getting image info for {0}", ex, info.Name); } return null; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index e4400220e6..5c0f76ba19 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -14,7 +14,7 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using System; @@ -263,7 +263,7 @@ namespace Emby.Server.Implementations.LiveTv var channel = (LiveTvChannel)_libraryManager.GetItemById(id); isVideo = channel.ChannelType == ChannelType.TV; service = GetService(channel); - _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); + _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); var supportsManagedStream = service as ISupportsDirectStreamProvider; if (supportsManagedStream != null) @@ -282,7 +282,7 @@ namespace Emby.Server.Implementations.LiveTv var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - _logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + _logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); } info.RequiresClosing = true; @@ -1093,7 +1093,7 @@ namespace Emby.Server.Implementations.LiveTv { cancellationToken.ThrowIfCancellationRequested(); - _logger.Debug("Refreshing guide from {0}", service.Name); + _logger.LogDebug("Refreshing guide from {0}", service.Name); try { @@ -1112,7 +1112,7 @@ namespace Emby.Server.Implementations.LiveTv catch (Exception ex) { cleanDatabase = false; - _logger.ErrorException("Error refreshing channels for service", ex); + _logger.LogError("Error refreshing channels for service", ex); } numComplete++; @@ -1175,7 +1175,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name); + _logger.LogError("Error getting channel information for {0}", ex, channelInfo.Item2.Name); } numComplete++; @@ -1193,7 +1193,7 @@ namespace Emby.Server.Implementations.LiveTv var guideDays = GetGuideDays(); - _logger.Info("Refreshing guide with {0} days of guide data", guideDays); + _logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays); cancellationToken.ThrowIfCancellationRequested(); @@ -1269,7 +1269,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.Debug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); + _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); if (newPrograms.Count > 0) { @@ -1304,7 +1304,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name); + _logger.LogError("Error getting programs for channel {0}", ex, currentChannel.Name); } numComplete++; @@ -1649,7 +1649,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError("Error getting recordings", ex); return new List>(); } }); @@ -1725,7 +1725,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError("Error getting recordings", ex); return new List>(); } }); @@ -1880,7 +1880,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError("Error getting recordings", ex); return new List>(); } }); @@ -1926,7 +1926,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.ErrorException("Error getting recordings", ex); + _logger.LogError("Error getting recordings", ex); return new List>(); } }); @@ -2162,7 +2162,7 @@ namespace Emby.Server.Implementations.LiveTv await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false); } - _logger.Info("New recording scheduled"); + _logger.LogInformation("New recording scheduled"); if (!(service is EmbyTV.EmbyTV)) { @@ -2183,7 +2183,7 @@ namespace Emby.Server.Implementations.LiveTv if (!registration.IsValid) { - _logger.Info("Creating series recordings requires an active Emby Premiere subscription."); + _logger.LogInformation("Creating series recordings requires an active Emby Premiere subscription."); return; } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 26a84a2750..d13f08b1bb 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -29,14 +29,14 @@ namespace Emby.Server.Implementations.LiveTv private readonly IServerApplicationHost _appHost; private IApplicationPaths _appPaths; - public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) + public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) { _liveTvManager = liveTvManager; _jsonSerializer = jsonSerializer; _mediaSourceManager = mediaSourceManager; _mediaEncoder = mediaEncoder; _appHost = appHost; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _appPaths = appPaths; } @@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); + _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); return list; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index ca5e51971d..97c33f1fa8 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false); var list = result.ToList(); - //Logger.Info("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); + //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list)); if (!string.IsNullOrEmpty(key) && list.Count > 0) { @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error getting channel list", ex); + Logger.LogError("Error getting channel list", ex); if (enableCache) { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError("Error getting channels", ex); } } } @@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.Error("Error getting channels", ex); + Logger.LogError("Error getting channels", ex); } } @@ -216,12 +216,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var startTime = DateTime.UtcNow; await liveStream.Open(cancellationToken).ConfigureAwait(false); var endTime = DateTime.UtcNow; - Logger.Info("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); + Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds); return liveStream; } catch (Exception ex) { - Logger.Error("Error opening tuner", ex); + Logger.LogError("Error opening tuner", ex); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index e873eb8e98..a8d1dcaa31 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -303,7 +303,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (Exception ex) { - Logger.ErrorException("Error getting tuner info", ex); + Logger.LogError("Error getting tuner info", ex); } } @@ -581,7 +581,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var profile = streamId.Split('_')[0]; - Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); + Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile); var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 2bc5a0ed3e..0e84622bda 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -6,7 +6,7 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Controller.LiveTv; using System.Net; @@ -244,7 +244,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private async Task ReleaseLockkey(ISocket tcpClient, uint lockKeyValue) { - _logger.Info("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); + _logger.LogInformation("HdHomerunManager.ReleaseLockkey {0}", lockKeyValue); var ipEndPoint = new IpEndPointInfo(_remoteIp, HdHomeRunPort); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 33103979e4..933c341242 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; @@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); - Logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host); + Logger.LogInformation("Opening HDHR UDP Live stream from {0}", uri.Host); var remoteAddress = IPAddress.Parse(uri.Host); var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host); @@ -71,7 +71,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (Exception) { - Logger.Error("Unable to determine local ip address for Legacy HDHomerun stream."); + Logger.LogError("Unable to determine local ip address for Legacy HDHomerun stream."); return; } } @@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { if (!(ex is OperationCanceledException)) { - Logger.ErrorException("Error opening live stream:", ex); + Logger.LogError("Error opening live stream:", ex); } throw; } @@ -131,12 +131,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (OperationCanceledException ex) { - Logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); + Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); openTaskCompletionSource.TrySetException(ex); } catch (Exception ex) { - Logger.ErrorException("Error opening live stream:", ex); + Logger.LogError("Error opening live stream:", ex); openTaskCompletionSource.TrySetException(ex); } @@ -346,4 +346,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 7e0ac4131d..b1eda3b7f2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.LiveTv; using System.Linq; @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { EnableStreamSharing = false; - Logger.Info("Closing " + GetType().Name); + Logger.LogInformation("Closing " + GetType().Name); LiveStreamCancellationTokenSource.Cancel(); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error closing live stream", ex); + Logger.LogError("Error closing live stream", ex); } } @@ -120,7 +120,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { if (retryCount == 0) { - Logger.Info("Deleting temp files {0}", string.Join(", ", paths.ToArray())); + Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray())); } var failedFiles = new List(); @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - //Logger.ErrorException("Error deleting file {0}", ex, path); + //Logger.LogError("Error deleting file {0}", ex, path); failedFiles.Add(path); } } @@ -181,14 +181,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts isLastFile = nextFileInfo.Item2; } - Logger.Info("Live Stream ended."); + Logger.LogInformation("Live Stream ended."); } private Tuple GetNextFile(string currentFile) { var files = GetStreamFilePaths(); - //Logger.Info("Live stream files: {0}", string.Join(", ", files.ToArray())); + //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray())); if (string.IsNullOrEmpty(currentFile)) { @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken) { - //Logger.Info("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); + //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit); using (var inputStream = (FileStream)GetInputStream(path, allowAsync)) { @@ -227,7 +227,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private void TrySeek(FileStream stream, long offset) { - //Logger.Info("TrySeek live stream"); + //logger.LogInformation("TrySeek live stream"); try { stream.Seek(offset, SeekOrigin.End); @@ -242,7 +242,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error seeking stream", ex); + Logger.LogError("Error seeking stream", ex); } } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index a1bff2b5bd..a54bd16139 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -205,4 +205,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return Task.FromResult(new List()); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index ca744b615e..208225c1ed 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -12,7 +12,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.LiveTv.TunerHosts @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase)) { extInf = line.Substring(ExtInfPrefix.Length).Trim(); - _logger.Info("Found m3u channel: {0}", extInf); + _logger.LogInformation("Found m3u channel: {0}", extInf); } else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) { @@ -335,4 +335,4 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts return dict; } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 572edb1678..ca53036a41 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -9,7 +9,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using System.Globalization; @@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); var typeName = GetType().Name; - Logger.Info("Opening " + typeName + " Live stream from {0}", url); + Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); var httpRequestOptions = new HttpRequestOptions { @@ -125,17 +125,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { try { + Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using (response) + using (var stream = response.Content) + using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var stream = response.Content) - { - Logger.Info("Beginning {0} stream to {1}", GetType().Name, TempFilePath); - - using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) - { - await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); - } - } + await ApplicationHost.StreamHelper.CopyToAsync(stream, fileStream, 81920, () => Resolve(openTaskCompletionSource), cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -143,7 +138,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.ErrorException("Error copying live stream.", ex); + Logger.LogError("Error copying live stream.", ex); } EnableStreamSharing = false; await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 71a4ca8244..c6de9d9570 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -10,7 +10,7 @@ using System.Globalization; using System.IO; using System.Linq; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Reflection; namespace Emby.Server.Implementations.Localization @@ -82,7 +82,7 @@ namespace Emby.Server.Implementations.Localization using (var stream = _assemblyInfo.GetManifestResourceStream(type, resource)) { var target = Path.Combine(localizationPath, filename); - _logger.Info("Extracting ratings to {0}", target); + _logger.LogInformation("Extracting ratings to {0}", target); using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { diff --git a/Emby.Server.Implementations/Logging/ConsoleLogger.cs b/Emby.Server.Implementations/Logging/ConsoleLogger.cs deleted file mode 100644 index 51199f08ae..0000000000 --- a/Emby.Server.Implementations/Logging/ConsoleLogger.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using MediaBrowser.Model.Logging; - -namespace Emby.Server.Implementations.Logging -{ - public class ConsoleLogger : IConsoleLogger - { - public void WriteLine(string message) - { - Console.WriteLine(message); - } - } -} diff --git a/Emby.Server.Implementations/Logging/SimpleLogManager.cs b/Emby.Server.Implementations/Logging/SimpleLogManager.cs deleted file mode 100644 index 390814c34e..0000000000 --- a/Emby.Server.Implementations/Logging/SimpleLogManager.cs +++ /dev/null @@ -1,360 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Logging; - -namespace Emby.Server.Implementations.Logging -{ - public class SimpleLogManager : ILogManager, IDisposable - { - public LogSeverity LogSeverity { get; set; } - public string ExceptionMessagePrefix { get; set; } - private FileLogger _fileLogger; - - private readonly string LogDirectory; - private readonly string LogFilePrefix; - public string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; - - public SimpleLogManager(string logDirectory, string logFileNamePrefix) - { - LogDirectory = logDirectory; - LogFilePrefix = logFileNamePrefix; - } - - public ILogger GetLogger(string name) - { - return new NamedLogger(name, this); - } - - public async Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken) - { - LogSeverity = severity; - - var logger = _fileLogger; - if (logger != null) - { - logger.Dispose(); - await TryMoveToArchive(logger.Path, cancellationToken).ConfigureAwait(false); - } - - var newPath = Path.Combine(LogDirectory, LogFilePrefix + ".txt"); - - if (File.Exists(newPath)) - { - newPath = await TryMoveToArchive(newPath, cancellationToken).ConfigureAwait(false); - } - - _fileLogger = new FileLogger(newPath); - - if (LoggerLoaded != null) - { - try - { - LoggerLoaded(this, EventArgs.Empty); - } - catch (Exception ex) - { - GetLogger("Logger").ErrorException("Error in LoggerLoaded event", ex); - } - } - } - - private async Task TryMoveToArchive(string file, CancellationToken cancellationToken, int retryCount = 0) - { - var archivePath = GetArchiveFilePath(); - - try - { - File.Move(file, archivePath); - - return file; - } - catch (FileNotFoundException) - { - return file; - } - catch (DirectoryNotFoundException) - { - return file; - } - catch - { - if (retryCount >= 50) - { - return GetArchiveFilePath(); - } - - await Task.Delay(100, cancellationToken).ConfigureAwait(false); - - return await TryMoveToArchive(file, cancellationToken, retryCount + 1).ConfigureAwait(false); - } - } - - private string GetArchiveFilePath() - { - return Path.Combine(LogDirectory, LogFilePrefix + "-" + decimal.Floor(DateTime.Now.Ticks / 10000000) + ".txt"); - } - - public event EventHandler LoggerLoaded; - - public void Flush() - { - var logger = _fileLogger; - if (logger != null) - { - logger.Flush(); - } - } - - private bool _console = true; - public void AddConsoleOutput() - { - _console = true; - } - - public void RemoveConsoleOutput() - { - _console = false; - } - - public void Log(string message) - { - if (_console) - { - Console.WriteLine(message); - } - - var logger = _fileLogger; - if (logger != null) - { - message = DateTime.Now.ToString(DateTimeFormat) + " " + message; - - logger.Log(message); - } - } - - public void Dispose() - { - var logger = _fileLogger; - if (logger != null) - { - logger.Dispose(); - - var task = TryMoveToArchive(logger.Path, CancellationToken.None); - Task.WaitAll(task); - } - - _fileLogger = null; - } - } - - public class FileLogger : IDisposable - { - private readonly FileStream _fileStream; - - private bool _disposed; - private readonly CancellationTokenSource _cancellationTokenSource; - private readonly BlockingCollection _queue = new BlockingCollection(); - - public string Path { get; set; } - - public FileLogger(string path) - { - Path = path; - - Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)); - - _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 32768); - _cancellationTokenSource = new CancellationTokenSource(); - - Task.Factory.StartNew(LogInternal, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); - } - - private void LogInternal() - { - while (!_cancellationTokenSource.IsCancellationRequested && !_disposed) - { - try - { - foreach (var message in _queue.GetConsumingEnumerable()) - { - var bytes = Encoding.UTF8.GetBytes(message + Environment.NewLine); - if (_disposed) - { - return; - } - - _fileStream.Write(bytes, 0, bytes.Length); - if (_disposed) - { - return; - } - - _fileStream.Flush(true); - } - } - catch - { - - } - } - } - - public void Log(string message) - { - if (_disposed) - { - return; - } - - _queue.Add(message); - } - - public void Flush() - { - if (_disposed) - { - return; - } - - _fileStream.Flush(true); - } - - public void Dispose() - { - if (_disposed) - { - return; - } - - _disposed = true; - _cancellationTokenSource.Cancel(); - - var stream = _fileStream; - if (stream != null) - { - using (stream) - { - stream.Flush(true); - } - } - } - } - - public class NamedLogger : ILogger - { - public string Name { get; private set; } - private readonly SimpleLogManager _logManager; - - public NamedLogger(string name, SimpleLogManager logManager) - { - Name = name; - _logManager = logManager; - } - - public void Info(string message, params object[] paramList) - { - Log(LogSeverity.Info, message, paramList); - } - - public void Error(string message, params object[] paramList) - { - Log(LogSeverity.Error, message, paramList); - } - - public void Warn(string message, params object[] paramList) - { - Log(LogSeverity.Warn, message, paramList); - } - - public void Debug(string message, params object[] paramList) - { - if (_logManager.LogSeverity == LogSeverity.Info) - { - return; - } - Log(LogSeverity.Debug, message, paramList); - } - - public void Fatal(string message, params object[] paramList) - { - Log(LogSeverity.Fatal, message, paramList); - } - - public void FatalException(string message, Exception exception, params object[] paramList) - { - ErrorException(message, exception, paramList); - } - - public void ErrorException(string message, Exception exception, params object[] paramList) - { - LogException(LogSeverity.Error, message, exception, paramList); - } - - private void LogException(LogSeverity level, string message, Exception exception, params object[] paramList) - { - message = FormatMessage(message, paramList).Replace(Environment.NewLine, ". "); - - var messageText = LogHelper.GetLogMessage(exception); - - var prefix = _logManager.ExceptionMessagePrefix; - - if (!string.IsNullOrWhiteSpace(prefix)) - { - messageText.Insert(0, prefix); - } - - LogMultiline(message, level, messageText); - } - - private static string FormatMessage(string message, params object[] paramList) - { - if (paramList != null) - { - for (var i = 0; i < paramList.Length; i++) - { - var obj = paramList[i]; - - message = message.Replace("{" + i + "}", (obj == null ? "null" : obj.ToString())); - } - } - - return message; - } - - public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent) - { - if (severity == LogSeverity.Debug && _logManager.LogSeverity == LogSeverity.Info) - { - return; - } - - additionalContent.Insert(0, message + Environment.NewLine); - - const char tabChar = '\t'; - - var text = additionalContent.ToString() - .Replace(Environment.NewLine, Environment.NewLine + tabChar) - .TrimEnd(tabChar); - - if (text.EndsWith(Environment.NewLine)) - { - text = text.Substring(0, text.LastIndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase)); - } - - Log(severity, text); - } - - public void Log(LogSeverity severity, string message, params object[] paramList) - { - message = severity + " " + Name + ": " + FormatMessage(message, paramList); - - _logManager.Log(message); - } - } -} diff --git a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs b/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs deleted file mode 100644 index 7104935e15..0000000000 --- a/Emby.Server.Implementations/Logging/UnhandledExceptionWriter.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; -using System; -using System.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Server.Implementations.Logging -{ - public class UnhandledExceptionWriter - { - private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; - private readonly ILogManager _logManager; - private readonly IFileSystem _fileSystem; - private readonly IConsoleLogger _console; - - public UnhandledExceptionWriter(IApplicationPaths appPaths, ILogger logger, ILogManager logManager, IFileSystem fileSystem, IConsoleLogger console) - { - _appPaths = appPaths; - _logger = logger; - _logManager = logManager; - _fileSystem = fileSystem; - _console = console; - } - - public void Log(Exception ex) - { - _logger.ErrorException("UnhandledException", ex); - _logManager.Flush(); - - var path = Path.Combine(_appPaths.LogDirectoryPath, "unhandled_" + Guid.NewGuid() + ".txt"); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path)); - - var builder = LogHelper.GetLogMessage(ex); - - // Write to console just in case file logging fails - _console.WriteLine("UnhandledException"); - - var logMessage = builder.ToString(); - _console.WriteLine(logMessage); - - _fileSystem.WriteAllText(path, logMessage); - } - } -} diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index c6033b4f48..3c72635817 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.MediaEncoder { if (chapter.StartPositionTicks >= runtimeTicks) { - _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name); + _logger.LogInformation("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name); break; } @@ -166,7 +166,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (Exception ex) { - _logger.ErrorException("Error extracting chapter images for {0}", ex, string.Join(",", video.Path)); + _logger.LogError("Error extracting chapter images for {0}", ex, string.Join(",", video.Path)); success = false; break; } @@ -226,7 +226,7 @@ namespace Emby.Server.Implementations.MediaEncoder foreach (var image in deadImages) { - _logger.Debug("Deleting dead chapter image {0}", image); + _logger.LogDebug("Deleting dead chapter image {0}", image); try { @@ -234,7 +234,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (IOException ex) { - _logger.ErrorException("Error deleting {0}.", ex, image); + _logger.LogError("Error deleting {0}.", ex, image); } } } diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 9726ef0974..3f93e767fb 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -3,7 +3,7 @@ using System.IO; using System.Net; using System.Net.Sockets; using Emby.Server.Implementations.Networking; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace Emby.Server.Implementations.Net diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs index 4699b5bd48..7945680b36 100644 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ b/Emby.Server.Implementations/Networking/NetworkManager.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using System.Numerics; @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error binding to NetworkAddressChanged event", ex); + Logger.LogError("Error binding to NetworkAddressChanged event", ex); } try @@ -45,20 +45,20 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error binding to NetworkChange_NetworkAvailabilityChanged event", ex); + Logger.LogError("Error binding to NetworkChange_NetworkAvailabilityChanged event", ex); } } } private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { - Logger.Debug("NetworkAvailabilityChanged"); + Logger.LogDebug("NetworkAvailabilityChanged"); OnNetworkChanged(); } private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) { - Logger.Debug("NetworkAddressChanged"); + Logger.LogDebug("NetworkAddressChanged"); OnNetworkChanged(); } @@ -189,7 +189,7 @@ namespace Emby.Server.Implementations.Networking foreach (var subnet_Match in subnets) { - //Logger.Debug("subnet_Match:" + subnet_Match); + //logger.LogDebug("subnet_Match:" + subnet_Match); if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase)) { @@ -355,13 +355,13 @@ namespace Emby.Server.Implementations.Networking try { var host = uri.DnsSafeHost; - Logger.Debug("Resolving host {0}", host); + Logger.LogDebug("Resolving host {0}", host); address = GetIpAddresses(host).Result.FirstOrDefault(); if (address != null) { - Logger.Debug("{0} resolved to {1}", host, address); + Logger.LogDebug("{0} resolved to {1}", host, address); return IsInLocalNetworkInternal(address.ToString(), false); } @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error resovling hostname", ex); + Logger.LogError("Error resovling hostname", ex); } } } @@ -399,7 +399,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error in GetAllNetworkInterfaces", ex); + Logger.LogError("Error in GetAllNetworkInterfaces", ex); return new List(); } @@ -409,7 +409,7 @@ namespace Emby.Server.Implementations.Networking try { // suppress logging because it might be causing nas device wake up - //Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); + //logger.LogDebug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus); var ipProperties = network.GetIPProperties(); @@ -428,7 +428,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.ErrorException("Error querying network interface", ex); + Logger.LogError("Error querying network interface", ex); return new List(); } diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs index 38a2505934..95ec2a672c 100644 --- a/Emby.Server.Implementations/News/NewsEntryPoint.cs +++ b/Emby.Server.Implementations/News/NewsEntryPoint.cs @@ -4,7 +4,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Notifications; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.News; using MediaBrowser.Model.Notifications; using MediaBrowser.Model.Serialization; @@ -67,7 +67,7 @@ namespace Emby.Server.Implementations.News } catch (Exception ex) { - _logger.ErrorException("Error downloading news", ex); + _logger.LogError("Error downloading news", ex); } } diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index 1e8d30ab9e..f5a429552e 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Playlists; using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs index ce29b52f6f..b268e00db9 100644 --- a/Emby.Server.Implementations/ResourceFileManager.cs +++ b/Emby.Server.Implementations/ResourceFileManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - _logger.ErrorException("Error in Path.GetFullPath", ex); + _logger.LogError("Error in Path.GetFullPath", ex); } // Don't allow file system access outside of the source folder diff --git a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs index 8ed2dbaedf..f259b4d931 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; @@ -44,9 +44,9 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Initializes a new instance of the class. /// - public ChapterImagesTask(ILogManager logManager, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem) + public ChapterImagesTask(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager, IFileSystem fileSystem) { - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _libraryManager = libraryManager; _itemRepo = itemRepo; _appPaths = appPaths; diff --git a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs index a2779c7cdb..afcee02e5f 100644 --- a/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/DailyTrigger.cs @@ -2,7 +2,7 @@ using System.Globalization; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.ScheduledTasks var dueTime = triggerDate - now; - logger.Info("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + logger.LogInformation("Daily trigger for {0} set to fire at {1}, which is {2} minutes from now.", taskName, triggerDate.ToString(), dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); } diff --git a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs index dcccb252a3..5f6a0dfe66 100644 --- a/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/IntervalTrigger.cs @@ -2,7 +2,7 @@ using System.Linq; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs new file mode 100644 index 0000000000..c77efb5cdb --- /dev/null +++ b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -0,0 +1,142 @@ +using MediaBrowser.Common; +using MediaBrowser.Common.Updates; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Net; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Progress; +using MediaBrowser.Model.Tasks; + +namespace Emby.Server.Implementations.ScheduledTasks +{ + /// + /// Plugin Update Task + /// + public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask + { + /// + /// The _logger + /// + private readonly ILogger _logger; + + private readonly IInstallationManager _installationManager; + + private readonly IApplicationHost _appHost; + + public PluginUpdateTask(ILogger logger, IInstallationManager installationManager, IApplicationHost appHost) + { + _logger = logger; + _installationManager = installationManager; + _appHost = appHost; + } + + /// + /// Creates the triggers that define when the task will run + /// + /// IEnumerable{BaseTaskTrigger}. + public IEnumerable GetDefaultTriggers() + { + return new[] { + + // At startup + new TaskTriggerInfo {Type = TaskTriggerInfo.TriggerStartup}, + + // Every so often + new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks} + }; + } + + public string Key + { + get { return "PluginUpdates"; } + } + + /// + /// Update installed plugins + /// + /// The cancellation token. + /// The progress. + /// Task. + public async Task Execute(CancellationToken cancellationToken, IProgress progress) + { + progress.Report(0); + + var packagesToInstall = (await _installationManager.GetAvailablePluginUpdates(_appHost.ApplicationVersion, true, cancellationToken).ConfigureAwait(false)).ToList(); + + progress.Report(10); + + var numComplete = 0; + + foreach (var package in packagesToInstall) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + await _installationManager.InstallPackage(package, true, new SimpleProgress(), cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // InstallPackage has it's own inner cancellation token, so only throw this if it's ours + if (cancellationToken.IsCancellationRequested) + { + throw; + } + } + catch (HttpException ex) + { + _logger.LogError("Error downloading {0}", ex, package.name); + } + catch (IOException ex) + { + _logger.LogError("Error updating {0}", ex, package.name); + } + + // Update progress + lock (progress) + { + numComplete++; + double percent = numComplete; + percent /= packagesToInstall.Count; + + progress.Report(90 * percent + 10); + } + } + + progress.Report(100); + } + + /// + /// Gets the name of the task + /// + /// The name. + public string Name + { + get { return "Check for plugin updates"; } + } + + /// + /// Gets the description. + /// + /// The description. + public string Description + { + get { return "Downloads and installs updates for plugins that are configured to update automatically."; } + } + + public string Category + { + get { return "Application"; } + } + + public bool IsHidden => true; + + public bool IsEnabled => true; + + public bool IsLogged => true; + } +} diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index eeb38bf540..93e02063b7 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -10,7 +10,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Progress; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.ErrorException("Error deserializing {0}", ex, path); + Logger.LogError("Error deserializing {0}", ex, path); } _readFromFile = true; } @@ -360,7 +360,7 @@ namespace Emby.Server.Implementations.ScheduledTasks return; } - Logger.Info("{0} fired for task: {1}", trigger.GetType().Name, Name); + Logger.LogInformation("{0} fired for task: {1}", trigger.GetType().Name, Name); trigger.Stop(); @@ -408,7 +408,7 @@ namespace Emby.Server.Implementations.ScheduledTasks CurrentCancellationTokenSource = new CancellationTokenSource(); - Logger.Info("Executing {0}", Name); + Logger.LogInformation("Executing {0}", Name); ((TaskManager)TaskManager).OnTaskExecuting(this); @@ -436,7 +436,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.ErrorException("Error", ex); + Logger.LogError("Error", ex); failureException = ex; @@ -493,7 +493,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { if (State == TaskState.Running) { - Logger.Info("Attempting to cancel Scheduled Task {0}", Name); + Logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name); CurrentCancellationTokenSource.Cancel(); } } @@ -614,7 +614,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var elapsedTime = endTime - startTime; - Logger.Info("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds); + Logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds); var result = new TaskResult { @@ -664,12 +664,12 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Info(Name + ": Cancelling"); + Logger.LogInformation(Name + ": Cancelling"); token.Cancel(); } catch (Exception ex) { - Logger.ErrorException("Error calling CancellationToken.Cancel();", ex); + Logger.LogError("Error calling CancellationToken.Cancel();", ex); } } var task = _currentTask; @@ -677,21 +677,21 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Info(Name + ": Waiting on Task"); + Logger.LogInformation(Name + ": Waiting on Task"); var exited = Task.WaitAll(new[] { task }, 2000); if (exited) { - Logger.Info(Name + ": Task exited"); + Logger.LogInformation(Name + ": Task exited"); } else { - Logger.Info(Name + ": Timed out waiting for task to stop"); + Logger.LogInformation(Name + ": Timed out waiting for task to stop"); } } catch (Exception ex) { - Logger.ErrorException("Error calling Task.WaitAll();", ex); + Logger.LogError("Error calling Task.WaitAll();", ex); } } @@ -699,12 +699,12 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - Logger.Debug(Name + ": Disposing CancellationToken"); + Logger.LogDebug(Name + ": Disposing CancellationToken"); token.Dispose(); } catch (Exception ex) { - Logger.ErrorException("Error calling CancellationToken.Dispose();", ex); + Logger.LogError("Error calling CancellationToken.Dispose();", ex); } } if (wassRunning) diff --git a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs index 20a4304cc8..35366a044c 100644 --- a/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/StartupTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs index c4623bf5b3..def142f88a 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemEventTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs index 0c9eb0f1b8..4cb97cbdae 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs @@ -1,6 +1,6 @@ using MediaBrowser.Common; using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (!updateInfo.IsUpdateAvailable) { - Logger.Debug("No application update available."); + Logger.LogDebug("No application update available."); return; } @@ -83,13 +83,13 @@ namespace Emby.Server.Implementations.ScheduledTasks if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate) { - Logger.Info("Update Revision {0} available. Updating...", updateInfo.AvailableVersion); + Logger.LogInformation("Update Revision {0} available. Updating...", updateInfo.AvailableVersion); await _appHost.UpdateApplication(updateInfo.Package, cancellationToken, progress).ConfigureAwait(false); } else { - Logger.Info("A new version of " + _appHost.Name + " is available."); + Logger.LogInformation("A new version of " + _appHost.Name + " is available."); } } diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index 8963693ab5..0322583dcc 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -185,7 +185,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); + Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); } else { @@ -217,13 +217,13 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); + Logger.LogError("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); + Logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -246,7 +246,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); + Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); } else { @@ -263,7 +263,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var type = task.ScheduledTask.GetType(); - Logger.Info("Queueing task {0}", type.Name); + Logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -360,7 +360,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// private void ExecuteQueuedTasks() { - Logger.Info("ExecuteQueuedTasks"); + Logger.LogInformation("ExecuteQueuedTasks"); // Execute queued tasks lock (_taskQueue) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index 05fb08447a..efadd71111 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -6,7 +6,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks.Tasks @@ -132,11 +132,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.ErrorException("Error deleting directory {0}", ex, directory); + _logger.LogError("Error deleting directory {0}", ex, directory); } catch (IOException ex) { - _logger.ErrorException("Error deleting directory {0}", ex, directory); + _logger.LogError("Error deleting directory {0}", ex, directory); } } } @@ -150,11 +150,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.ErrorException("Error deleting file {0}", ex, path); + _logger.LogError("Error deleting file {0}", ex, path); } catch (IOException ex) { - _logger.ErrorException("Error deleting file {0}", ex, path); + _logger.LogError("Error deleting file {0}", ex, path); } } diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs deleted file mode 100644 index fbc3a309ea..0000000000 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ReloadLoggerFileTask.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Tasks; - -namespace Emby.Server.Implementations.ScheduledTasks.Tasks -{ - /// - /// Class ReloadLoggerFileTask - /// - public class ReloadLoggerFileTask : IScheduledTask, IConfigurableScheduledTask - { - /// - /// Gets or sets the log manager. - /// - /// The log manager. - private ILogManager LogManager { get; set; } - /// - /// Gets or sets the configuration manager. - /// - /// The configuration manager. - private IConfigurationManager ConfigurationManager { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The logManager. - /// The configuration manager. - public ReloadLoggerFileTask(ILogManager logManager, IConfigurationManager configurationManager) - { - LogManager = logManager; - ConfigurationManager = configurationManager; - } - - /// - /// Gets the default triggers. - /// - /// IEnumerable{BaseTaskTrigger}. - public IEnumerable GetDefaultTriggers() - { - var trigger = new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, TimeOfDayTicks = TimeSpan.FromHours(0).Ticks }; //12am - - return new[] { trigger }; - } - - /// - /// Executes the internal. - /// - /// The cancellation token. - /// The progress. - /// Task. - public Task Execute(CancellationToken cancellationToken, IProgress progress) - { - cancellationToken.ThrowIfCancellationRequested(); - - progress.Report(0); - - return LogManager.ReloadLogger(ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging - ? LogSeverity.Debug - : LogSeverity.Info, cancellationToken); - } - - /// - /// Gets the name. - /// - /// The name. - public string Name - { - get { return "Rotate log file"; } - } - - public string Key { get; } - - /// - /// Gets the description. - /// - /// The description. - public string Description - { - get { return "Moves logging to a new file to help reduce log file sizes."; } - } - - /// - /// Gets the category. - /// - /// The category. - public string Category - { - get { return "Application"; } - } - - public bool IsHidden - { - get { return false; } - } - - public bool IsEnabled - { - get { return true; } - } - - public bool IsLogged - { - get { return true; } - } - } -} diff --git a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs index 82b4499172..e694e08558 100644 --- a/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/WeeklyTrigger.cs @@ -1,7 +1,7 @@ using System; using System.Threading; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index f75eb63649..d2c6ed33ba 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -7,7 +7,7 @@ using System.Threading; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using MediaBrowser.Controller.Security; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using SQLitePCL.pretty; using MediaBrowser.Model.Extensions; @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Security } catch (Exception ex) { - Logger.ErrorException("Error migrating authentication database", ex); + Logger.LogError("Error migrating authentication database", ex); } } diff --git a/Emby.Server.Implementations/Security/PluginSecurityManager.cs b/Emby.Server.Implementations/Security/PluginSecurityManager.cs index 8d8d6700e2..aa0f390307 100644 --- a/Emby.Server.Implementations/Security/PluginSecurityManager.cs +++ b/Emby.Server.Implementations/Security/PluginSecurityManager.cs @@ -12,7 +12,7 @@ using MediaBrowser.Controller; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.Security /// Initializes a new instance of the class. /// public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer, - IApplicationPaths appPaths, ILogManager logManager, IFileSystem fileSystem, ICryptoProvider cryptographyProvider) + IApplicationPaths appPaths, ILoggerFactory loggerFactory, IFileSystem fileSystem, ICryptoProvider cryptographyProvider) { if (httpClient == null) { @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Security _appPaths = appPaths; _fileSystem = fileSystem; _cryptographyProvider = cryptographyProvider; - _logger = logManager.GetLogger("SecurityManager"); + _logger = loggerFactory.CreateLogger("SecurityManager"); } /// @@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.Security if (reg == null) { var msg = "Result from appstore registration was null."; - _logger.Error(msg); + _logger.LogError(msg); throw new ArgumentException(msg); } if (!String.IsNullOrEmpty(reg.key)) @@ -152,7 +152,7 @@ namespace Emby.Server.Implementations.Security } catch (HttpException e) { - _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired) { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.Security } catch (Exception e) { - _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); SaveAppStoreInfo(parameters); //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually. throw new Exception("Error registering store sale"); diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs index 26371d21d5..423fe7b183 100644 --- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs +++ b/Emby.Server.Implementations/Serialization/JsonSerializer.cs @@ -1,7 +1,7 @@ using System; using System.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System.Threading.Tasks; @@ -69,7 +69,7 @@ namespace Emby.Common.Implementations.Serialization private Stream OpenFile(string path) { - //_logger.Debug("Deserializing file {0}", path); + //_logger.LogDebug("Deserializing file {0}", path); return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072); } diff --git a/Emby.Server.Implementations/Serialization/XmlSerializer.cs b/Emby.Server.Implementations/Serialization/XmlSerializer.cs index e0603a01ff..dfc3249198 100644 --- a/Emby.Server.Implementations/Serialization/XmlSerializer.cs +++ b/Emby.Server.Implementations/Serialization/XmlSerializer.cs @@ -4,7 +4,7 @@ using System.IO; using System.Xml; using System.Xml.Serialization; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.Serialization @@ -90,7 +90,7 @@ namespace Emby.Server.Implementations.Serialization /// The file. public void SerializeToFile(object obj, string file) { - _logger.Debug("Serializing to file {0}", file); + _logger.LogDebug("Serializing to file {0}", file); using (var stream = new FileStream(file, FileMode.Create)) { SerializeToStream(obj, stream); @@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.Serialization /// System.Object. public object DeserializeFromFile(Type type, string file) { - _logger.Debug("Deserializing file {0}", file); + _logger.LogDebug("Deserializing file {0}", file); using (var stream = _fileSystem.OpenRead(file)) { return DeserializeFromStream(type, stream); diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs index 3726c9f6b0..84ca2d9d1e 100644 --- a/Emby.Server.Implementations/Services/ServiceController.cs +++ b/Emby.Server.Implementations/Services/ServiceController.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Emby.Server.Implementations.HttpServer; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.Services @@ -183,4 +183,4 @@ namespace Emby.Server.Implementations.Services } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs index e76857a8df..50965b4a97 100644 --- a/Emby.Server.Implementations/Services/ServiceHandler.cs +++ b/Emby.Server.Implementations/Services/ServiceHandler.cs @@ -4,7 +4,7 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.HttpServer; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace Emby.Server.Implementations.Services @@ -63,7 +63,8 @@ namespace Emby.Server.Implementations.Services if (this.RestPath == null) { string contentType; - this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, new NullLogger(), out contentType); + // TODO: change null out + this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, null, out contentType); if (contentType != null) ResponseContentType = contentType; diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs index f0e80c2169..ef64d20b4b 100644 --- a/Emby.Server.Implementations/Services/ServicePath.cs +++ b/Emby.Server.Implementations/Services/ServicePath.cs @@ -4,7 +4,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Text; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Extensions; namespace Emby.Server.Implementations.Services @@ -354,25 +354,25 @@ namespace Emby.Server.Implementations.Services if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) { - //logger.Info("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + //logger.LogInformation("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase)) { - //logger.Info("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs); + //logger.LogInformation("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs); return false; } if (!ExplodeComponents(ref withPathInfoParts)) { - //logger.Info("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + //logger.LogInformation("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) { - //logger.Info("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + //logger.LogInformation("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } @@ -393,7 +393,7 @@ namespace Emby.Server.Implementations.Services // Ensure there are still enough parts left to match the remainder if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1)) { - //logger.Info("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); + //logger.LogInformation("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } } @@ -416,7 +416,7 @@ namespace Emby.Server.Implementations.Services if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch)) { - //logger.Info("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch); + //logger.LogInformation("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch); return false; } pathIx++; diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index a2102dc452..2b2b3c6779 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -15,7 +15,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; using MediaBrowser.Model.Users; @@ -248,7 +248,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error updating user", ex); + _logger.LogError("Error updating user", ex); } } } @@ -528,7 +528,7 @@ namespace Emby.Server.Implementations.Session foreach (var session in idle) { - _logger.Debug("Session {0} has gone idle while playing", session.Id); + _logger.LogDebug("Session {0} has gone idle while playing", session.Id); try { @@ -543,7 +543,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.Debug("Error calling OnPlaybackStopped", ex); + _logger.LogDebug("Error calling OnPlaybackStopped", ex); } } @@ -847,7 +847,7 @@ namespace Emby.Server.Implementations.Session { var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown"; - _logger.Info("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms", + _logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms", session.Client, session.ApplicationVersion, info.Item.Name, @@ -882,7 +882,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error closing live stream", ex); + _logger.LogError("Error closing live stream", ex); } } @@ -1095,7 +1095,7 @@ namespace Emby.Server.Implementations.Session if (item == null) { - _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id); + _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id); return new List(); } @@ -1151,7 +1151,7 @@ namespace Emby.Server.Implementations.Session if (item == null) { - _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id); + _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id); return new List(); } @@ -1222,7 +1222,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendRestartRequiredNotification.", ex); + _logger.LogError("Error in SendRestartRequiredNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1249,7 +1249,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendServerShutdownNotification.", ex); + _logger.LogError("Error in SendServerShutdownNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1266,7 +1266,7 @@ namespace Emby.Server.Implementations.Session { CheckDisposed(); - _logger.Debug("Beginning SendServerRestartNotification"); + _logger.LogDebug("Beginning SendServerRestartNotification"); var sessions = Sessions.ToList(); @@ -1278,7 +1278,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error in SendServerRestartNotification.", ex); + _logger.LogError("Error in SendServerRestartNotification.", ex); } }, cancellationToken)).ToArray(); @@ -1462,7 +1462,7 @@ namespace Emby.Server.Implementations.Session if (existing != null) { - _logger.Info("Reissuing access token: " + existing.AccessToken); + _logger.LogInformation("Reissuing access token: " + existing.AccessToken); return existing.AccessToken; } @@ -1481,7 +1481,7 @@ namespace Emby.Server.Implementations.Session UserName = user.Name }; - _logger.Info("Creating new access token for user {0}", user.Id); + _logger.LogInformation("Creating new access token for user {0}", user.Id); _authRepo.Create(newToken); return newToken.AccessToken; @@ -1513,7 +1513,7 @@ namespace Emby.Server.Implementations.Session { CheckDisposed(); - _logger.Info("Logging out access token {0}", existing.AccessToken); + _logger.LogInformation("Logging out access token {0}", existing.AccessToken); _authRepo.Delete(existing); @@ -1529,7 +1529,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error reporting session ended", ex); + _logger.LogError("Error reporting session ended", ex); } } } @@ -1599,7 +1599,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error saving device capabilities", ex); + _logger.LogError("Error saving device capabilities", ex); } } } @@ -1692,7 +1692,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error getting {0} image info", ex, type); + _logger.LogError("Error getting {0} image info", ex, type); return null; } } @@ -1818,7 +1818,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1840,7 +1840,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1862,7 +1862,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); @@ -1886,7 +1886,7 @@ namespace Emby.Server.Implementations.Session } catch (Exception ex) { - _logger.ErrorException("Error sending message", ex); + _logger.LogError("Error sending message", ex); } }, cancellationToken)).ToArray(); diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 9ab4753fb9..3bb022b326 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; using System; @@ -40,14 +40,14 @@ namespace Emby.Server.Implementations.Session /// Initializes a new instance of the class. /// /// The session manager. - /// The log manager. + /// The logger factory. /// The json. /// The HTTP server. /// The server manager. - public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json, IHttpServer httpServer) + public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer) { _sessionManager = sessionManager; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _json = json; _httpServer = httpServer; httpServer.WebSocketConnected += _serverManager_WebSocketConnected; @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Session } else { - _logger.Warn("Unable to determine session based on url: {0}", e.Argument.Url); + _logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url); } } diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index ddac9660f2..bdae5cf8fa 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Session; using MediaBrowser.Model.System; diff --git a/Emby.Server.Implementations/SystemEvents.cs b/Emby.Server.Implementations/SystemEvents.cs index c1e6dc1da9..e529628332 100644 --- a/Emby.Server.Implementations/SystemEvents.cs +++ b/Emby.Server.Implementations/SystemEvents.cs @@ -1,6 +1,6 @@ using System; using MediaBrowser.Common.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace Emby.Server.Implementations diff --git a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs index ea87a95398..f30c181a0c 100644 --- a/Emby.Server.Implementations/TextEncoding/TextEncoding.cs +++ b/Emby.Server.Implementations/TextEncoding/TextEncoding.cs @@ -1,7 +1,7 @@ using System; using System.Text; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Text; using NLangDetect.Core; @@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.TextEncoding if (!string.IsNullOrWhiteSpace(language)) { - _logger.Debug("Text language detected as {0}", language); + _logger.LogDebug("Text language detected as {0}", language); } } @@ -165,7 +165,7 @@ namespace Emby.Server.Implementations.TextEncoding throw new ArgumentNullException("charset"); } - _logger.Debug("Getting encoding object for character set: {0}", charset); + _logger.LogDebug("Getting encoding object for character set: {0}", charset); try { @@ -174,7 +174,7 @@ namespace Emby.Server.Implementations.TextEncoding catch (ArgumentException) { charset = charset.Replace("-", string.Empty); - _logger.Debug("Getting encoding object for character set: {0}", charset); + _logger.LogDebug("Getting encoding object for character set: {0}", charset); return Encoding.GetEncoding(charset); } diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index f195ca7104..222ec7dd05 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller; using MediaBrowser.Model.ApiClient; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; @@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error in OnMessageReceived", ex); + _logger.LogError("Error in OnMessageReceived", ex); } } } @@ -127,7 +127,7 @@ namespace Emby.Server.Implementations.Udp } else { - _logger.Warn("Unable to respond to udp request because the local ip address could not be determined."); + _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined."); } } @@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error receiving udp message", ex); + _logger.LogError("Error receiving udp message", ex); } } @@ -193,7 +193,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error receiving udp message", ex); + _logger.LogError("Error receiving udp message", ex); } BeginReceive(); @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error handling UDP message", ex); + _logger.LogError("Error handling UDP message", ex); } } @@ -274,7 +274,7 @@ namespace Emby.Server.Implementations.Udp { await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false); - _logger.Info("Udp message sent to {0}", remoteEndPoint); + _logger.LogInformation("Udp message sent to {0}", remoteEndPoint); } catch (OperationCanceledException) { @@ -282,7 +282,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint); + _logger.LogError("Error sending message to {0}", ex, remoteEndPoint); } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index a23166647a..f864b079ab 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -16,7 +16,7 @@ using MediaBrowser.Common.Updates; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Events; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; using MediaBrowser.Controller.Configuration; @@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Updates /// The new version. private void OnPluginUpdated(IPlugin plugin, PackageVersionInfo newVersion) { - _logger.Info("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification); + _logger.LogInformation("Plugin updated: {0} {1} {2}", newVersion.name, newVersion.versionStr ?? string.Empty, newVersion.classification); EventHelper.FireEventIfNotNull(PluginUpdated, this, new GenericEventArgs> { Argument = new Tuple(plugin, newVersion) }, _logger); @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.Updates /// The package. private void OnPluginInstalled(PackageVersionInfo package) { - _logger.Info("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification); + _logger.LogInformation("New plugin installed: {0} {1} {2}", package.name, package.versionStr ?? string.Empty, package.classification); EventHelper.FireEventIfNotNull(PluginInstalled, this, new GenericEventArgs { Argument = package }, _logger); @@ -491,7 +491,7 @@ namespace Emby.Server.Implementations.Updates CurrentInstallations.Remove(tuple); } - _logger.Info("Package installation cancelled: {0} {1}", package.name, package.versionStr); + _logger.LogInformation("Package installation cancelled: {0} {1}", package.name, package.versionStr); EventHelper.FireEventIfNotNull(PackageInstallationCancelled, this, installationEventArgs, _logger); @@ -499,7 +499,7 @@ namespace Emby.Server.Implementations.Updates } catch (Exception ex) { - _logger.ErrorException("Package installation failed", ex); + _logger.LogError("Package installation failed", ex); lock (CurrentInstallations) { @@ -612,7 +612,7 @@ namespace Emby.Server.Implementations.Updates } catch (IOException e) { - _logger.ErrorException("Error attempting to move file from {0} to {1}", e, tempFile, target); + _logger.LogError("Error attempting to move file from {0} to {1}", e, tempFile, target); throw; } @@ -623,7 +623,7 @@ namespace Emby.Server.Implementations.Updates catch (IOException e) { // Don't fail because of this - _logger.ErrorException("Error deleting temp file {0]", e, tempFile); + _logger.LogError("Error deleting temp file {0]", e, tempFile); } } @@ -640,7 +640,7 @@ namespace Emby.Server.Implementations.Updates _applicationHost.RemovePlugin(plugin); var path = plugin.AssemblyFilePath; - _logger.Info("Deleting plugin file {0}", path); + _logger.LogInformation("Deleting plugin file {0}", path); // Make this case-insensitive to account for possible incorrect assembly naming var file = _fileSystem.GetFilePaths(_fileSystem.GetDirectoryName(path)) diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs index 32535b69ef..2817d9e8ce 100644 --- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs +++ b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs @@ -302,7 +302,7 @@ namespace Emby.XmlTv.Classes var results = new Dictionary(); //Loop through and parse out all elements and then lang= attributes - //Logger.Info("Loading file {0}", _fileName); + //logger.LogInformation("Loading file {0}", _fileName); using (var reader = CreateXmlTextReader(_fileName)) { while (reader.Read()) @@ -1062,7 +1062,7 @@ namespace Emby.XmlTv.Classes } else { - //Logger.Warn("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate); + //Logger.LogWarning("Unable to parse the date {0} from standardised form {1}", dateValue, standardDate); } } @@ -1091,4 +1091,4 @@ namespace Emby.XmlTv.Classes return String.Format("{0} {1}", dateComponent, dateOffset); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 5aa803b9b6..1e99b8c7a1 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index e243927a0c..07b8185c5c 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index c3b2e82e7c..28a4245123 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -21,6 +21,8 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.IO; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; + namespace MediaBrowser.Api.Images { /// @@ -360,7 +362,7 @@ namespace MediaBrowser.Api.Images } catch (Exception ex) { - Logger.ErrorException("Error getting image information for {0}", ex, info.Path); + Logger.LogError("Error getting image information for {0}", ex, info.Path); return null; } @@ -673,7 +675,7 @@ namespace MediaBrowser.Api.Images private ImageFormat[] GetClientSupportedFormats() { - //Logger.Debug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty())); + //logger.LogDebug("Request types: {0}", string.Join(",", Request.AcceptTypes ?? Array.Empty())); var supportedFormats = (Request.AcceptTypes ?? Array.Empty()).Select(i => i.Split(';')[0]).ToArray(); var acceptParam = Request.QueryString["accept"]; diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index 39a7904866..d7182c1b66 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -17,6 +17,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api { @@ -232,7 +233,7 @@ namespace MediaBrowser.Api // item.SetProviderId(key.Key, value); // } //} - Logger.Info("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds)); + Logger.LogInformation("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds)); // Since the refresh process won't erase provider Ids, we need to set this explicitly now. item.ProviderIds = request.ProviderIds; diff --git a/MediaBrowser.Api/ItemRefreshService.cs b/MediaBrowser.Api/ItemRefreshService.cs index ab083c207d..ba1c809fe5 100644 --- a/MediaBrowser.Api/ItemRefreshService.cs +++ b/MediaBrowser.Api/ItemRefreshService.cs @@ -6,7 +6,7 @@ using System.Threading; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; namespace MediaBrowser.Api diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index cc8c1251fe..cf5014328f 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -32,6 +32,7 @@ using MediaBrowser.Common.Progress; using MediaBrowser.Model.Extensions; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Library { @@ -1000,7 +1001,7 @@ namespace MediaBrowser.Api.Library } catch (Exception ex) { - Logger.ErrorException("Error refreshing library", ex); + Logger.LogError("Error refreshing library", ex); } }); } diff --git a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs index 0a6ccd4c5c..bf8aba8dfe 100644 --- a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs +++ b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs @@ -5,7 +5,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; using MediaBrowser.Controller.IO; @@ -95,7 +95,7 @@ namespace MediaBrowser.Api.LiveTv bytesRead = await _streamHelper.CopyToAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false); //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs index 1ee096a2e7..33e6b20207 100644 --- a/MediaBrowser.Api/PluginService.cs +++ b/MediaBrowser.Api/PluginService.cs @@ -232,7 +232,7 @@ namespace MediaBrowser.Api } catch { - //Logger.ErrorException("Error getting plugin list", ex); + //Logger.LogError("Error getting plugin list", ex); // Play it safe here if (requireAppStoreEnabled) { diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs index ff57b4dd15..fa5fa99d17 100644 --- a/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs +++ b/MediaBrowser.Api/ScheduledTasks/ScheduledTasksWebSocketListener.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Tasks; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs index ca2c381cf6..533e7d3072 100644 --- a/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs +++ b/MediaBrowser.Api/Session/SessionInfoWebSocketListener.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Session; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Api/SimilarItemsHelper.cs b/MediaBrowser.Api/SimilarItemsHelper.cs index db5908f769..db075e8f40 100644 --- a/MediaBrowser.Api/SimilarItemsHelper.cs +++ b/MediaBrowser.Api/SimilarItemsHelper.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index c8b0a32e95..3ea1d1beda 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -17,6 +17,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Model.Services; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Subtitles { @@ -277,7 +278,7 @@ namespace MediaBrowser.Api.Subtitles } catch (Exception ex) { - Logger.ErrorException("Error downloading subtitles", ex); + Logger.LogError("Error downloading subtitles", ex); } }); diff --git a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs index 6991244c6c..b61ff8d932 100644 --- a/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs +++ b/MediaBrowser.Api/System/ActivityLogWebSocketListener.cs @@ -1,6 +1,6 @@ using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Controller.Net; diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs index 2bb52f0ae5..96d0fcae89 100644 --- a/MediaBrowser.Common/Events/EventHelper.cs +++ b/MediaBrowser.Common/Events/EventHelper.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; @@ -28,7 +28,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError("Error in event handler", ex); } }); } @@ -54,7 +54,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError("Error in event handler", ex); } }); } @@ -77,7 +77,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError("Error in event handler", ex); } } } @@ -100,7 +100,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.ErrorException("Error in event handler", ex); + logger.LogError("Error in event handler", ex); } } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index e3b5b51178..9c05217539 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -12,7 +12,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Library; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Users; using System; using System.Collections.Generic; @@ -36,6 +35,7 @@ using MediaBrowser.Model.Providers; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.MediaInfo; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -798,7 +798,7 @@ namespace MediaBrowser.Controller.Entities builder.Append(chunkBuilder); } - //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString()); + //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString()); return builder.ToString().RemoveDiacritics(); } @@ -1414,7 +1414,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name); + Logger.LogError("Error refreshing owned items for {0}", ex, Path ?? Name); } } @@ -1802,7 +1802,7 @@ namespace MediaBrowser.Controller.Entities if (!isAllowed) { - Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating); + Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating); } return isAllowed; @@ -2058,7 +2058,7 @@ namespace MediaBrowser.Controller.Entities if (itemByPath == null) { - //Logger.Warn("Unable to find linked item at path {0}", info.Path); + //Logger.LogWarning("Unable to find linked item at path {0}", info.Path); } return itemByPath; @@ -2070,7 +2070,7 @@ namespace MediaBrowser.Controller.Entities if (item == null) { - //Logger.Warn("Unable to find linked item at path {0}", info.Path); + //Logger.LogWarning("Unable to find linked item at path {0}", info.Path); } return item; diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 19a8c24b8a..dbec03a212 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -1,13 +1,13 @@ -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.IO; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; @@ -15,6 +15,8 @@ using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; + namespace MediaBrowser.Controller.Entities { /// @@ -103,7 +105,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.ErrorException("Error loading library options", ex); + Logger.LogError("Error loading library options", ex); return new LibraryOptions(); } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 81072b6e77..3d830cbe62 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -10,7 +10,6 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities.Audio; @@ -23,6 +22,7 @@ using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -264,7 +264,7 @@ namespace MediaBrowser.Controller.Entities /// protected virtual List LoadChildren() { - //Logger.Debug("Loading children from {0} {1} {2}", GetType().Name, Id, Path); + //logger.LogDebug("Loading children from {0} {1} {2}", GetType().Name, Id, Path); //just load our children from the repo - the library will be validated and maintained in other processes return GetCachedChildren(); } @@ -303,7 +303,7 @@ namespace MediaBrowser.Controller.Entities var id = child.Id; if (dictionary.ContainsKey(id)) { - Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}", + Logger.LogError("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}", Path ?? Name, child.Path ?? child.Name); } @@ -425,7 +425,7 @@ namespace MediaBrowser.Controller.Entities else { - Logger.Debug("Removed item: " + item.Path); + Logger.LogDebug("Removed item: " + item.Path); item.SetParent(null); LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }, this, false); @@ -795,7 +795,7 @@ namespace MediaBrowser.Controller.Entities { if (!(this is ICollectionFolder)) { - Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name); + Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name); return true; } } @@ -846,7 +846,7 @@ namespace MediaBrowser.Controller.Entities if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager)) { - Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems"); + Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems"); return true; } @@ -1575,7 +1575,7 @@ namespace MediaBrowser.Controller.Entities { try { - Logger.Debug("Found shortcut at {0}", i.FullName); + Logger.LogDebug("Found shortcut at {0}", i.FullName); var resolvedPath = CollectionFolder.ApplicationHost.ExpandVirtualPath(FileSystem.ResolveShortcut(i.FullName)); @@ -1588,13 +1588,13 @@ namespace MediaBrowser.Controller.Entities }; } - Logger.Error("Error resolving shortcut {0}", i.FullName); + Logger.LogError("Error resolving shortcut {0}", i.FullName); return null; } catch (IOException ex) { - Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName); + Logger.LogError("Error resolving shortcut {0}", ex, i.FullName); return null; } }) @@ -1605,7 +1605,7 @@ namespace MediaBrowser.Controller.Entities if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem))) { - Logger.Info("Shortcut links have changed for {0}", Path); + Logger.LogInformation("Shortcut links have changed for {0}", Path); newShortcutLinks.AddRange(LinkedChildren.Where(i => i.Type == LinkedChildType.Manual)); LinkedChildren = newShortcutLinks.ToArray(); diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 201579731e..cdf0214d3d 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -363,7 +363,7 @@ namespace MediaBrowser.Controller.Entities.TV } catch (Exception ex) { - Logger.ErrorException("Error in FillMissingEpisodeNumbersFromPath. Episode: {0}", ex, Path ?? Name ?? Id.ToString()); + Logger.LogError(ex, "Error in FillMissingEpisodeNumbersFromPath. Episode: {Episode}", Path ?? Name ?? Id.ToString()); } } } diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 36035a2bbd..6d5126a445 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.TV; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; @@ -262,7 +262,7 @@ namespace MediaBrowser.Controller.Entities catch { // Full exception logged at lower levels - _logger.Error("Error getting genre"); + _logger.LogError("Error getting genre"); return null; } @@ -386,7 +386,7 @@ namespace MediaBrowser.Controller.Entities catch { // Full exception logged at lower levels - _logger.Error("Error getting genre"); + _logger.LogError("Error getting genre"); return null; } diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs index e1fabee4fe..37d507753c 100644 --- a/MediaBrowser.Controller/IO/FileData.cs +++ b/MediaBrowser.Controller/IO/FileData.cs @@ -1,6 +1,6 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using MediaBrowser.Model.IO; @@ -77,7 +77,7 @@ namespace MediaBrowser.Controller.IO if (string.IsNullOrEmpty(newPath)) { //invalid shortcut - could be old or target could just be unavailable - logger.Warn("Encountered invalid shortcut: " + fullName); + logger.LogWarning("Encountered invalid shortcut: " + fullName); continue; } @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.IO } catch (Exception ex) { - logger.ErrorException("Error resolving shortcut from {0}", ex, fullName); + logger.LogError("Error resolving shortcut from {0}", ex, fullName); } } else if (flattenFolderDepth > 0 && isDirectory) diff --git a/MediaBrowser.Controller/IResourceFileManager.cs b/MediaBrowser.Controller/IResourceFileManager.cs index ae73f4b4c0..64f1b9f7a4 100644 --- a/MediaBrowser.Controller/IResourceFileManager.cs +++ b/MediaBrowser.Controller/IResourceFileManager.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs index 3957c30208..745e49920e 100644 --- a/MediaBrowser.Controller/Library/Profiler.cs +++ b/MediaBrowser.Controller/Library/Profiler.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Diagnostics; @@ -67,7 +67,7 @@ namespace MediaBrowser.Controller.Library message = string.Format("{0} took {1} seconds.", _name, ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000")); } - _logger.Info(message); + _logger.LogInformation(message); } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 3d2871e650..e1762fbdad 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -8,7 +8,7 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Session; @@ -738,7 +738,7 @@ namespace MediaBrowser.Controller.MediaEncoding } catch (Exception ex) { - _logger.ErrorException("Error disposing iso mount", ex); + _logger.LogError(ex, "Error disposing iso mount"); } IsoMount = null; diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index 5f3f79d775..539aab7b3a 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -1,10 +1,10 @@ using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; +using Microsoft.Extension.Logging; namespace MediaBrowser.Controller.MediaEncoding { @@ -43,7 +43,7 @@ namespace MediaBrowser.Controller.MediaEncoding } catch (Exception ex) { - _logger.ErrorException("Error reading ffmpeg log", ex); + _logger.LogError(ex, "Error reading ffmpeg log"); } } diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index 7df96b7776..bac7e0184c 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -8,6 +8,9 @@ using System.Net.WebSockets; using System.Threading.Tasks; using System.Threading; using System; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Net; +using MediaBrowser.Model.Threading; namespace MediaBrowser.Controller.Net { @@ -114,7 +117,7 @@ namespace MediaBrowser.Controller.Net var cancellationTokenSource = new CancellationTokenSource(); - Logger.Debug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name); + Logger.LogDebug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name); var timer = SendOnTimer ? TimerFactory.Create(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) : @@ -229,7 +232,7 @@ namespace MediaBrowser.Controller.Net } catch (Exception ex) { - Logger.ErrorException("Error sending web socket message {0}", ex, Name); + Logger.LogError("Error sending web socket message {0}", ex, Name); DisposeConnection(tuple); } } @@ -257,7 +260,7 @@ namespace MediaBrowser.Controller.Net /// The connection. private void DisposeConnection(Tuple connection) { - Logger.Debug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name); + Logger.LogDebug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name); var timer = connection.Item3; diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 65192671ee..2d97e0b887 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -27,7 +27,7 @@ namespace MediaBrowser.Controller.Providers } public DirectoryService(IFileSystem fileSystem) - : this(new NullLogger(), fileSystem) + : this(null, fileSystem) // TODO change { } @@ -37,7 +37,7 @@ namespace MediaBrowser.Controller.Providers if (!_cache.TryGetValue(path, out entries)) { - //_logger.Debug("Getting files for " + path); + //_logger.LogDebug("Getting files for " + path); entries = _fileSystem.GetFileSystemEntries(path).ToArray(); diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 3e34075a6b..6e217ab4a5 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -4,7 +4,7 @@ using System.Linq; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; namespace MediaBrowser.Controller.Providers @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.Providers public bool EnableRemoteContentProbe { get; set; } public MetadataRefreshOptions(IFileSystem fileSystem) - : this(new DirectoryService(new NullLogger(), fileSystem)) + : this(new DirectoryService(null, fileSystem)) // TODO { } diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index 869d3fcb05..65ff43cf95 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -1,11 +1,11 @@ -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; +using System; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Threading; using System.Linq; -using System; namespace MediaBrowser.Controller.Session { @@ -231,7 +231,7 @@ namespace MediaBrowser.Controller.Session } var newController = factory(this); - _logger.Debug("Creating new {0}", newController.GetType().Name); + _logger.LogDebug("Creating new {0}", newController.GetType().Name); controllers.Add(newController); SessionControllers = controllers.ToArray(); @@ -337,7 +337,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.ErrorException("Error reporting playback progress", ex); + _logger.LogError("Error reporting playback progress", ex); } } @@ -371,7 +371,7 @@ namespace MediaBrowser.Controller.Session if (disposable != null) { - _logger.Debug("Disposing session controller {0}", disposable.GetType().Name); + _logger.LogDebug("Disposing session controller {0}", disposable.GetType().Name); try { @@ -379,7 +379,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.ErrorException("Error disposing session controller", ex); + _logger.LogError("Error disposing session controller", ex); } } } diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 05874ec2cf..c22ca4d604 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Parsers @@ -158,7 +158,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } else { - Logger.Warn("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: " + val); } } break; diff --git a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs index 891a3ad3fd..e5b4190a44 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Xml; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs index 3225603bf6..0139ce9179 100644 --- a/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/GameSystemXmlParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Threading; using System.Threading.Tasks; using System.Xml; diff --git a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs index f9b3343964..939e2d1df0 100644 --- a/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/GameXmlParser.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Parsers diff --git a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs index 8b25dd3bdb..dcf88e90e6 100644 --- a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs index 30576b5311..2629547f8f 100644 --- a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; diff --git a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs index 006376b41b..4ca7224caf 100644 --- a/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/GameSystemXmlProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Providers diff --git a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs index 3e7acc28de..0ba52f84df 100644 --- a/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/GameXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; diff --git a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs index 909daf2ddc..ce37adda3e 100644 --- a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.LocalMetadata.Parsers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.IO; using System.Threading; using MediaBrowser.LocalMetadata.Savers; diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 81622f54c5..4e7a7a1685 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -20,7 +20,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers @@ -135,7 +135,7 @@ namespace MediaBrowser.LocalMetadata.Savers } catch (Exception ex) { - Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + Logger.LogError("Error setting hidden attribute on {0} - {1}", path, ex.Message); } } diff --git a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs index 42a96588ac..1995d8c386 100644 --- a/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BoxSetXmlSaver.cs @@ -10,7 +10,7 @@ using System.Xml; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs index 109b21d358..da0d824901 100644 --- a/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/GameSystemXmlSaver.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs index 1a8e83e723..62d4993b32 100644 --- a/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/GameXmlSaver.cs @@ -6,7 +6,7 @@ using System.Globalization; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs index 8409e483d0..a84fcd57e7 100644 --- a/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/PersonXmlSaver.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs index 521a0b00e3..0c03bcacd4 100644 --- a/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/PlaylistXmlSaver.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.IO; using System.Xml; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.LocalMetadata.Savers diff --git a/MediaBrowser.Model/Activity/ActivityLogEntry.cs b/MediaBrowser.Model/Activity/ActivityLogEntry.cs index 1f4bff10d0..a61ebc2685 100644 --- a/MediaBrowser.Model/Activity/ActivityLogEntry.cs +++ b/MediaBrowser.Model/Activity/ActivityLogEntry.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; namespace MediaBrowser.Model.Activity @@ -63,6 +63,6 @@ namespace MediaBrowser.Model.Activity /// Gets or sets the log severity. /// /// The log severity. - public LogSeverity Severity { get; set; } + public LogLevel Severity { get; set; } } } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 840abf618c..41306b4c38 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1,7 +1,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Session; using System; @@ -528,7 +528,7 @@ namespace MediaBrowser.Model.Dlna { transcodeReasons.InsertRange(0, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles)); - _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}", + _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path"); } @@ -732,7 +732,7 @@ namespace MediaBrowser.Model.Dlna bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1); bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1); - _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}", + _logger.LogInformation("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}", options.Profile.Name ?? "Unknown Profile", item.Path ?? "Unknown path", isEligibleForDirectPlay, @@ -1022,7 +1022,7 @@ namespace MediaBrowser.Model.Dlna if (directPlay == null) { - _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}", + _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}", profile.Name ?? "Unknown Profile", mediaSource.Path ?? "Unknown path"); @@ -1188,7 +1188,7 @@ namespace MediaBrowser.Model.Dlna private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource) { - _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}", + _logger.LogInformation("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}", type, profile.Name ?? "Unknown Profile", condition.Property, @@ -1210,7 +1210,7 @@ namespace MediaBrowser.Model.Dlna if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed) { - _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod); + _logger.LogInformation("Not eligible for {0} due to unsupported subtitles", playMethod); return new ValueTuple(false, TranscodeReason.SubtitleCodecNotSupported); } } @@ -1397,7 +1397,7 @@ namespace MediaBrowser.Model.Dlna if (itemBitrate > requestedMaxBitrate) { - _logger.Info("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", itemBitrate.ToString(CultureInfo.InvariantCulture), requestedMaxBitrate.ToString(CultureInfo.InvariantCulture)); return false; } diff --git a/MediaBrowser.Model/Logging/IConsoleLogger.cs b/MediaBrowser.Model/Logging/IConsoleLogger.cs deleted file mode 100644 index a8c282d65c..0000000000 --- a/MediaBrowser.Model/Logging/IConsoleLogger.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace MediaBrowser.Model.Logging -{ - public interface IConsoleLogger - { - void WriteLine(string message); - } -} diff --git a/MediaBrowser.Model/Logging/ILogManager.cs b/MediaBrowser.Model/Logging/ILogManager.cs deleted file mode 100644 index e6a10cf181..0000000000 --- a/MediaBrowser.Model/Logging/ILogManager.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Interface ILogManager - /// - public interface ILogManager - { - /// - /// Gets or sets the log level. - /// - /// The log level. - LogSeverity LogSeverity { get; set; } - - /// - /// Gets or sets the exception message prefix. - /// - /// The exception message prefix. - string ExceptionMessagePrefix { get; set; } - - /// - /// Gets the logger. - /// - /// The name. - /// ILogger. - ILogger GetLogger(string name); - - /// - /// Reloads the logger. - /// - Task ReloadLogger(LogSeverity severity, CancellationToken cancellationToken); - - /// - /// Occurs when [logger loaded]. - /// - event EventHandler LoggerLoaded; - - /// - /// Flushes this instance. - /// - void Flush(); - - /// - /// Adds the console output. - /// - void AddConsoleOutput(); - - /// - /// Removes the console output. - /// - void RemoveConsoleOutput(); - } -} diff --git a/MediaBrowser.Model/Logging/ILogger.cs b/MediaBrowser.Model/Logging/ILogger.cs deleted file mode 100644 index be9d6fc503..0000000000 --- a/MediaBrowser.Model/Logging/ILogger.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Interface ILogger - /// - public interface ILogger - { - /// - /// Infoes the specified message. - /// - /// The message. - /// The param list. - void Info(string message, params object[] paramList); - - /// - /// Errors the specified message. - /// - /// The message. - /// The param list. - void Error(string message, params object[] paramList); - - /// - /// Warns the specified message. - /// - /// The message. - /// The param list. - void Warn(string message, params object[] paramList); - - /// - /// Debugs the specified message. - /// - /// The message. - /// The param list. - void Debug(string message, params object[] paramList); - - /// - /// Fatals the specified message. - /// - /// The message. - /// The param list. - void Fatal(string message, params object[] paramList); - - /// - /// Fatals the exception. - /// - /// The message. - /// The exception. - /// The param list. - void FatalException(string message, Exception exception, params object[] paramList); - - /// - /// Logs the exception. - /// - /// The message. - /// The exception. - /// The param list. - void ErrorException(string message, Exception exception, params object[] paramList); - - /// - /// Logs the multiline. - /// - /// The message. - /// The severity. - /// Content of the additional. - void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent); - - /// - /// Logs the specified severity. - /// - /// The severity. - /// The message. - /// The parameter list. - void Log(LogSeverity severity, string message, params object[] paramList); - } -} diff --git a/MediaBrowser.Model/Logging/LogHelper.cs b/MediaBrowser.Model/Logging/LogHelper.cs deleted file mode 100644 index cf1c021862..0000000000 --- a/MediaBrowser.Model/Logging/LogHelper.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - /// - /// Class LogHelper - /// - public static class LogHelper - { - /// - /// Gets the log message. - /// - /// The exception. - /// StringBuilder. - public static StringBuilder GetLogMessage(Exception exception) - { - if (exception == null) - { - throw new ArgumentNullException("exception"); - } - - var messageText = new StringBuilder(); - - messageText.AppendLine(exception.ToString()); - - messageText.AppendLine(exception.GetType().FullName); - - LogExceptionData(messageText, exception); - - messageText.AppendLine(exception.StackTrace ?? "No Stack Trace Available"); - - // Log the InnerExceptions, if any - AppendInnerExceptions(messageText, exception); - - messageText.AppendLine(string.Empty); - - return messageText; - } - - /// - /// Appends the inner exceptions. - /// - /// The message text. - /// The e. - private static void AppendInnerExceptions(StringBuilder messageText, Exception e) - { - var aggregate = e as AggregateException; - - if (aggregate != null && aggregate.InnerExceptions != null) - { - foreach (var ex in aggregate.InnerExceptions) - { - AppendInnerException(messageText, ex); - AppendInnerExceptions(messageText, ex); - } - } - - else if (e.InnerException != null) - { - AppendInnerException(messageText, e.InnerException); - AppendInnerExceptions(messageText, e.InnerException); - } - } - - /// - /// Appends the inner exception. - /// - /// The message text. - /// The e. - private static void AppendInnerException(StringBuilder messageText, Exception e) - { - messageText.AppendLine("InnerException: " + e.GetType().FullName); - messageText.AppendLine(e.ToString()); - - LogExceptionData(messageText, e); - - if (e.StackTrace != null) - { - messageText.AppendLine(e.StackTrace); - } - } - - /// - /// Logs the exception data. - /// - /// The message text. - /// The e. - private static void LogExceptionData(StringBuilder messageText, Exception e) - { - foreach (var key in e.Data.Keys) - { - messageText.AppendLine(key + ": " + e.Data[key]); - } - } - } -} diff --git a/MediaBrowser.Model/Logging/LogSeverity.cs b/MediaBrowser.Model/Logging/LogSeverity.cs deleted file mode 100644 index ae04872894..0000000000 --- a/MediaBrowser.Model/Logging/LogSeverity.cs +++ /dev/null @@ -1,30 +0,0 @@ - -namespace MediaBrowser.Model.Logging -{ - /// - /// Enum LogSeverity - /// - public enum LogSeverity - { - /// - /// The info - /// - Info, - /// - /// The debug - /// - Debug, - /// - /// The warn - /// - Warn, - /// - /// The error - /// - Error, - /// - /// The fatal - /// - Fatal - } -} diff --git a/MediaBrowser.Model/Logging/NullLogger.cs b/MediaBrowser.Model/Logging/NullLogger.cs deleted file mode 100644 index d211d2567d..0000000000 --- a/MediaBrowser.Model/Logging/NullLogger.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Text; - -namespace MediaBrowser.Model.Logging -{ - public class NullLogger : ILogger - { - public void Info(string message, params object[] paramList) - { - } - - public void Error(string message, params object[] paramList) - { - } - - public void Warn(string message, params object[] paramList) - { - } - - public void Debug(string message, params object[] paramList) - { - } - - public void Fatal(string message, params object[] paramList) - { - } - - public void FatalException(string message, Exception exception, params object[] paramList) - { - } - - public void Log(LogSeverity severity, string message, params object[] paramList) - { - } - - public void ErrorException(string message, Exception exception, params object[] paramList) - { - } - - public void LogMultiline(string message, LogSeverity severity, StringBuilder additionalContent) - { - } - } -} diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 1b1a24b686..a5b2f40833 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -5,6 +5,10 @@ false + + + + diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs index 7c804348a8..9db0041b4d 100644 --- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs +++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs @@ -1,6 +1,6 @@ using System; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Model.Tasks { @@ -29,4 +29,4 @@ namespace MediaBrowser.Model.Tasks /// void Stop(); } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs index 834ec6cd39..707e942f33 100644 --- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs +++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs index 68b96486af..a2143982a2 100644 --- a/MediaBrowser.Providers/Books/BookMetadataService.cs +++ b/MediaBrowser.Providers/Books/BookMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs index 78791906a0..7cfae3a12b 100644 --- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs +++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Linq; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs index 634329177f..0369e8ca10 100644 --- a/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs +++ b/MediaBrowser.Providers/BoxSets/MovieDbBoxSetProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs index b22db559eb..6b371fef93 100644 --- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs +++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Chapters/ChapterManager.cs b/MediaBrowser.Providers/Chapters/ChapterManager.cs index 3d0c7c964a..7eb650cca3 100644 --- a/MediaBrowser.Providers/Chapters/ChapterManager.cs +++ b/MediaBrowser.Providers/Chapters/ChapterManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs index e472a23c4b..bf35cd105e 100644 --- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; namespace MediaBrowser.Providers.Folders diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs index 687dac919f..5147882615 100644 --- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs index 951794961e..14e0c3de69 100644 --- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs +++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs index edde0f5e3f..8cc11701e4 100644 --- a/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs +++ b/MediaBrowser.Providers/GameGenres/GameGenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Games/GameMetadataService.cs b/MediaBrowser.Providers/Games/GameMetadataService.cs index 67becbf585..4a56cc03b7 100644 --- a/MediaBrowser.Providers/Games/GameMetadataService.cs +++ b/MediaBrowser.Providers/Games/GameMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs index 474dd2fcf4..25fdfb7130 100644 --- a/MediaBrowser.Providers/Games/GameSystemMetadataService.cs +++ b/MediaBrowser.Providers/Games/GameSystemMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs index 88fba18547..8d764dbb3e 100644 --- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs +++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs index dfb0c58ad0..722de4dee9 100644 --- a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs +++ b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index f50dcf1c50..c1cb07a0e7 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -164,7 +164,7 @@ namespace MediaBrowser.Providers.Manager { var currentPath = currentImagePath; - _logger.Info("Deleting previous image {0}", currentPath); + _logger.LogInformation("Deleting previous image {0}", currentPath); _libraryMonitor.ReportFileSystemChangeBeginning(currentPath); @@ -197,7 +197,7 @@ namespace MediaBrowser.Providers.Manager if (retry) { - _logger.Error("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath); + _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath); } else { @@ -211,7 +211,7 @@ namespace MediaBrowser.Providers.Manager if (retry) { - _logger.Error("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message); + _logger.LogError("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message); } else { @@ -233,7 +233,7 @@ namespace MediaBrowser.Providers.Manager /// Task. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken) { - _logger.Debug("Saving image to {0}", path); + _logger.LogDebug("Saving image to {0}", path); var parentFolder = _fileSystem.GetDirectoryName(path); @@ -271,7 +271,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + _logger.LogError("Error setting hidden attribute on {0} - {1}", path, ex.Message); } } diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index c80d438411..a11ccd6d6c 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using System; @@ -126,7 +126,7 @@ namespace MediaBrowser.Providers.Manager if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType))) { - _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); + _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false); @@ -136,7 +136,7 @@ namespace MediaBrowser.Providers.Manager { if (response.Protocol == MediaProtocol.Http) { - _logger.Debug("Setting image url into item {0}", item.Id); + _logger.LogDebug("Setting image url into item {0}", item.Id); item.SetImage(new ItemImageInfo { Path = response.Path, @@ -173,7 +173,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.ErrorException("Error in {0}", ex, provider.Name); + _logger.LogError("Error in {0}", ex, provider.Name); } } @@ -264,7 +264,7 @@ namespace MediaBrowser.Providers.Manager return; } - _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); + _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name); var images = await _providerManager.GetAvailableRemoteImages(item, new RemoteImageQuery { @@ -310,7 +310,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.ErrorException("Error in {0}", ex, provider.Name); + _logger.LogError("Error in {0}", ex, provider.Name); } } @@ -577,7 +577,7 @@ namespace MediaBrowser.Providers.Manager } catch (IOException ex) { - _logger.ErrorException("Error examining images", ex); + _logger.LogError("Error examining images", ex); } } @@ -596,4 +596,4 @@ namespace MediaBrowser.Providers.Manager } } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 57711d3b68..5d607f5d67 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.ErrorException("Error getting file {0}", ex, path); + Logger.LogError("Error getting file {0}", ex, path); return null; } } @@ -73,7 +73,7 @@ namespace MediaBrowser.Providers.Manager if (requiresRefresh) { - Logger.Debug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name); + Logger.LogDebug("Refreshing {0} {1} because item.RequiresRefresh() returned true", typeof(TItemType).Name, item.Path ?? item.Name); } } @@ -96,7 +96,7 @@ namespace MediaBrowser.Providers.Manager localImagesFailed = true; if (!(item is IItemByName)) { - Logger.ErrorException("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name"); + Logger.LogError("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name"); } } @@ -268,7 +268,7 @@ namespace MediaBrowser.Providers.Manager // } // catch (Exception ex) // { - // Logger.ErrorException("Error in AddPersonImage", ex); + // Logger.LogError("Error in AddPersonImage", ex); // } //} @@ -728,7 +728,7 @@ namespace MediaBrowser.Providers.Manager foreach (var provider in providers.OfType>().ToList()) { var providerName = provider.GetType().Name; - Logger.Debug("Running {0} for {1}", providerName, logName); + Logger.LogDebug("Running {0} for {1}", providerName, logName); var itemInfo = new ItemInfo(item); @@ -759,7 +759,7 @@ namespace MediaBrowser.Providers.Manager break; } - Logger.Debug("{0} returned no metadata for {1}", providerName, logName); + Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName); } catch (OperationCanceledException) { @@ -767,7 +767,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError("Error in {0}", ex, provider.Name); // If a local provider fails, consider that a failure refreshResult.ErrorMessage = ex.Message; @@ -826,7 +826,7 @@ namespace MediaBrowser.Providers.Manager private async Task RunCustomProvider(ICustomMetadataProvider provider, TItemType item, string logName, MetadataRefreshOptions options, RefreshResult refreshResult, CancellationToken cancellationToken) { - Logger.Debug("Running {0} for {1}", provider.GetType().Name, logName); + Logger.LogDebug("Running {0} for {1}", provider.GetType().Name, logName); try { @@ -839,7 +839,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { refreshResult.ErrorMessage = ex.Message; - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError("Error in {0}", ex, provider.Name); } } @@ -857,7 +857,7 @@ namespace MediaBrowser.Providers.Manager foreach (var provider in providers) { var providerName = provider.GetType().Name; - Logger.Debug("Running {0} for {1}", providerName, logName); + Logger.LogDebug("Running {0} for {1}", providerName, logName); if (id != null && !tmpDataMerged) { @@ -880,7 +880,7 @@ namespace MediaBrowser.Providers.Manager } else { - Logger.Debug("{0} returned no metadata for {1}", providerName, logName); + Logger.LogDebug("{0} returned no metadata for {1}", providerName, logName); } } catch (OperationCanceledException) @@ -891,7 +891,7 @@ namespace MediaBrowser.Providers.Manager { refreshResult.Failures++; refreshResult.ErrorMessage = ex.Message; - Logger.ErrorException("Error in {0}", ex, provider.Name); + Logger.LogError("Error in {0}", ex, provider.Name); } } @@ -944,14 +944,14 @@ namespace MediaBrowser.Providers.Manager //if (hasChanged) //{ - // Logger.Debug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name); + // logger.LogDebug("{0} reports change to {1}", changeMonitor.GetType().Name, item.Path ?? item.Name); //} return hasChanged; } catch (Exception ex) { - Logger.ErrorException("Error in {0}.HasChanged", ex, changeMonitor.GetType().Name); + Logger.LogError("Error in {0}.HasChanged", ex, changeMonitor.GetType().Name); return false; } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 8697c7c57a..d562676413 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -10,7 +10,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -79,9 +79,9 @@ namespace MediaBrowser.Providers.Manager /// /// Initializes a new instance of the class. /// - public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILogManager logManager, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func libraryManagerFactory, IJsonSerializer json) + public ProviderManager(IHttpClient httpClient, ISubtitleManager subtitleManager, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILoggerFactory loggerFactory, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func libraryManagerFactory, IJsonSerializer json) { - _logger = logManager.GetLogger("ProviderManager"); + _logger = loggerFactory.CreateLogger("ProviderManager"); _httpClient = httpClient; ConfigurationManager = configurationManager; _libraryMonitor = libraryMonitor; @@ -144,7 +144,7 @@ namespace MediaBrowser.Providers.Manager return service.RefreshMetadata(item, options, cancellationToken); } - _logger.Error("Unable to find a metadata service for item of type " + item.GetType().Name); + _logger.LogError("Unable to find a metadata service for item of type " + item.GetType().Name); return Task.FromResult(ItemUpdateType.None); } @@ -250,7 +250,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name); return new List(); } } @@ -396,7 +396,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name); return false; } } @@ -620,7 +620,7 @@ namespace MediaBrowser.Providers.Manager foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, updateType, false))) { - _logger.Debug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name); + _logger.LogDebug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name); var fileSaver = saver as IMetadataFileSaver; @@ -634,7 +634,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0} GetSavePath", ex, saver.Name); + _logger.LogError("Error in {0} GetSavePath", ex, saver.Name); continue; } @@ -645,7 +645,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in metadata saver", ex); + _logger.LogError("Error in metadata saver", ex); } finally { @@ -660,7 +660,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in metadata saver", ex); + _logger.LogError("Error in metadata saver", ex); } } } @@ -723,7 +723,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0}.IsEnabledFor", ex, saver.Name); + _logger.LogError("Error in {0}.IsEnabledFor", ex, saver.Name); return false; } } @@ -825,7 +825,7 @@ namespace MediaBrowser.Providers.Manager } } - //_logger.Debug("Returning search results {0}", _json.SerializeToString(resultList)); + //_logger.LogDebug("Returning search results {0}", _json.SerializeToString(resultList)); return resultList; } @@ -868,7 +868,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error in {0}.Suports", ex, i.GetType().Name); + _logger.LogError("Error in {0}.Suports", ex, i.GetType().Name); return false; } }); @@ -930,7 +930,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshStart(BaseItem item) { - //_logger.Info("OnRefreshStart {0}", item.Id.ToString("N")); + //_logger.LogInformation("OnRefreshStart {0}", item.Id.ToString("N")); var id = item.Id; lock (_activeRefreshes) @@ -946,7 +946,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshComplete(BaseItem item) { - //_logger.Info("OnRefreshComplete {0}", item.Id.ToString("N")); + //_logger.LogInformation("OnRefreshComplete {0}", item.Id.ToString("N")); lock (_activeRefreshes) { _activeRefreshes.Remove(item.Id); @@ -974,7 +974,7 @@ namespace MediaBrowser.Providers.Manager public void OnRefreshProgress(BaseItem item, double progress) { - //_logger.Info("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress); + //_logger.LogInformation("OnRefreshProgress {0} {1}", item.Id.ToString("N"), progress); var id = item.Id; lock (_activeRefreshes) @@ -1062,7 +1062,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error refreshing item", ex); + _logger.LogError("Error refreshing item", ex); } } @@ -1139,7 +1139,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.ErrorException("Error refreshing library", ex); + _logger.LogError("Error refreshing library", ex); } } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index f7cbf72116..2827a3cc73 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.MediaInfo var file = directoryService.GetFile(path); if (file != null && file.LastWriteTimeUtc != item.DateModified) { - _logger.Debug("Refreshing {0} due to date modified timestamp change.", path); + _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path); return true; } } @@ -84,7 +84,7 @@ namespace MediaBrowser.Providers.MediaInfo if (!video.SubtitleFiles .SequenceEqual(_subtitleResolver.GetExternalSubtitleFiles(video, directoryService, false), StringComparer.Ordinal)) { - _logger.Debug("Refreshing {0} due to external subtitles change.", item.Path); + _logger.LogDebug("Refreshing {0} due to external subtitles change.", item.Path); return true; } } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index c7fc086be2..4dc3849d9f 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -14,7 +14,7 @@ using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -86,7 +86,7 @@ namespace MediaBrowser.Providers.MediaInfo if (streamFileNames.Length == 0) { - _logger.Error("No playable vobs found in dvd structure, skipping ffprobe."); + _logger.LogError("No playable vobs found in dvd structure, skipping ffprobe."); return ItemUpdateType.MetadataImport; } } @@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.MediaInfo if (streamFileNames.Length == 0) { - _logger.Error("No playable vobs found in bluray structure, skipping ffprobe."); + _logger.LogError("No playable vobs found in bluray structure, skipping ffprobe."); return ItemUpdateType.MetadataImport; } } @@ -342,7 +342,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error getting BDInfo", ex); + _logger.LogError("Error getting BDInfo", ex); return null; } } @@ -611,4 +611,4 @@ namespace MediaBrowser.Providers.MediaInfo .Sum(); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs index 6b396967ec..8d5f203170 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; @@ -176,7 +176,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles", ex); + _logger.LogError("Error downloading subtitles", ex); } return false; diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs index 6b4181dfb5..4fa6a05219 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -148,7 +148,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles for {0}", ex, video.Path); + _logger.LogError("Error downloading subtitles for {0}", ex, video.Path); } // Update progress diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index 00ffe383f8..baf913a778 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -53,7 +53,7 @@ namespace MediaBrowser.Providers.MediaInfo // Can't extract if we didn't find a video stream in the file if (!video.DefaultVideoStreamIndex.HasValue) { - _logger.Info("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty); + _logger.LogInformation("Skipping image extraction due to missing DefaultVideoStreamIndex for {0}.", video.Path ?? string.Empty); return Task.FromResult(new DynamicImageResponse { HasImage = false }); } diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs index 12f78a950a..1fce01903f 100644 --- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs +++ b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index e16e6aa8ca..0a45c0b876 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; @@ -378,7 +378,7 @@ namespace MediaBrowser.Providers.Movies !string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase)) { - _logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English..."); + _logger.LogInformation("MovieDbProvider couldn't find meta for language " + language + ". Trying English..."); url = string.Format(GetMovieInfo3, id, ApiKey) + "&language=en"; @@ -424,7 +424,7 @@ namespace MediaBrowser.Providers.Movies if (delayMs > 0) { - _logger.Debug("Throttling Tmdb by {0} ms", delayMs); + _logger.LogDebug("Throttling Tmdb by {0} ms", delayMs); await Task.Delay(Convert.ToInt32(delayMs)).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Movies/MovieDbSearch.cs b/MediaBrowser.Providers/Movies/MovieDbSearch.cs index 3b4a385d4e..b332207e15 100644 --- a/MediaBrowser.Providers/Movies/MovieDbSearch.cs +++ b/MediaBrowser.Providers/Movies/MovieDbSearch.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; @@ -71,7 +71,7 @@ namespace MediaBrowser.Providers.Movies year = year ?? yearInName; } - _logger.Info("MovieDbProvider: Finding id for item: " + name); + _logger.LogInformation("MovieDbProvider: Finding id for item: " + name); var language = idInfo.MetadataLanguage.ToLower(); //nope - search for it diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs index f0674ac9b7..9581533345 100644 --- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs +++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs index 338fc1c6d7..ae81545a6b 100644 --- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs +++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/ArtistMetadataService.cs b/MediaBrowser.Providers/Music/ArtistMetadataService.cs index 7741a3f433..7dc4a8dfe6 100644 --- a/MediaBrowser.Providers/Music/ArtistMetadataService.cs +++ b/MediaBrowser.Providers/Music/ArtistMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Music/AudioMetadataService.cs b/MediaBrowser.Providers/Music/AudioMetadataService.cs index f02eae19fc..6952ee8563 100644 --- a/MediaBrowser.Providers/Music/AudioMetadataService.cs +++ b/MediaBrowser.Providers/Music/AudioMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs index d163764265..da0f40a5a1 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -774,7 +774,7 @@ namespace MediaBrowser.Providers.Music } catch (Exception ex) { - _logger.ErrorException("Error getting music brainz info", ex); + _logger.LogError("Error getting music brainz info", ex); } } } @@ -812,7 +812,7 @@ namespace MediaBrowser.Providers.Music if (throttleMs > 0) { // MusicBrainz is extremely adamant about limiting to one request per second - _logger.Debug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture)); + _logger.LogDebug("Throttling MusicBrainz by {0}ms", throttleMs.ToString(CultureInfo.InvariantCulture)); await Task.Delay(throttleMs, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs index 28504dbd74..54d68bfd50 100644 --- a/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs +++ b/MediaBrowser.Providers/Music/MusicVideoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs index 3828f8d274..6c9bc526d8 100644 --- a/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs +++ b/MediaBrowser.Providers/MusicGenres/MusicGenreMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs index 8c7ef71b61..39d9b39eee 100644 --- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using System; diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs index 7af058bcdc..dda1fc5117 100644 --- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs +++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace MediaBrowser.Providers.People diff --git a/MediaBrowser.Providers/People/PersonMetadataService.cs b/MediaBrowser.Providers/People/PersonMetadataService.cs index bbfaa43b40..e32ecaa640 100644 --- a/MediaBrowser.Providers/People/PersonMetadataService.cs +++ b/MediaBrowser.Providers/People/PersonMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs index bff933ccfa..f6d3724e9d 100644 --- a/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs +++ b/MediaBrowser.Providers/Photos/PhotoAlbumMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs index d7f4982e4b..87529f93a4 100644 --- a/MediaBrowser.Providers/Photos/PhotoMetadataService.cs +++ b/MediaBrowser.Providers/Photos/PhotoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs index da4873ca47..7bc2469a04 100644 --- a/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs +++ b/MediaBrowser.Providers/Playlists/PlaylistItemsProvider.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -169,7 +169,7 @@ namespace MediaBrowser.Providers.Playlists var file = directoryService.GetFile(path); if (file != null && file.LastWriteTimeUtc != item.DateModified) { - _logger.Debug("Refreshing {0} due to date modified timestamp change.", path); + _logger.LogDebug("Refreshing {0} due to date modified timestamp change.", path); return true; } } diff --git a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs index 1d65917921..9534a4759e 100644 --- a/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs +++ b/MediaBrowser.Providers/Playlists/PlaylistMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.Providers/Studios/StudioMetadataService.cs b/MediaBrowser.Providers/Studios/StudioMetadataService.cs index 23953b0d3e..0c07fb5415 100644 --- a/MediaBrowser.Providers/Studios/StudioMetadataService.cs +++ b/MediaBrowser.Providers/Studios/StudioMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 071687c0fa..2006067b31 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles from {0}", ex, provider.Name); + _logger.LogError("Error downloading subtitles from {0}", ex, provider.Name); } } return new RemoteSubtitleInfo[] { }; @@ -119,7 +119,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error downloading subtitles from {0}", ex, i.Name); + _logger.LogError("Error downloading subtitles from {0}", ex, i.Name); return new RemoteSubtitleInfo[] { }; } }); @@ -207,7 +207,7 @@ namespace MediaBrowser.Providers.Subtitles foreach (var savePath in savePaths) { - _logger.Info("Saving subtitles to {0}", savePath); + _logger.LogInformation("Saving subtitles to {0}", savePath); _monitor.ReportFileSystemChangeBeginning(savePath); diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs index 4f528086e0..3cf62e94e0 100644 --- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs +++ b/MediaBrowser.Providers/TV/DummySeasonProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Globalization; using System.Linq; using System.Threading; @@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV _libraryManager.GetLibraryOptions(series).SeasonZeroDisplayName : (seasonNumber.HasValue ? string.Format(_localization.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value.ToString(_usCulture)) : _localization.GetLocalizedString("NameSeasonUnknown")); - _logger.Info("Creating Season {0} entry for {1}", seasonName, series.Name); + _logger.LogInformation("Creating Season {0} entry for {1}", seasonName, series.Name); var season = new Season { @@ -192,7 +192,7 @@ namespace MediaBrowser.Providers.TV foreach (var seasonToRemove in seasonsToRemove) { - _logger.Info("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber); + _logger.LogInformation("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber); _libraryManager.DeleteItem(seasonToRemove, new DeleteOptions { diff --git a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs index cea907ca3e..6292d9cf2b 100644 --- a/MediaBrowser.Providers/TV/EpisodeMetadataService.cs +++ b/MediaBrowser.Providers/TV/EpisodeMetadataService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs index 6e469a0411..a8c1a68a65 100644 --- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -217,7 +217,7 @@ namespace MediaBrowser.Providers.TV if (addMissingEpisodes) { // tvdb has a lot of nearly blank episodes - _logger.Info("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); + _logger.LogInformation("Creating virtual missing episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; @@ -226,7 +226,7 @@ namespace MediaBrowser.Providers.TV else if (airDate.Value > now) { // tvdb has a lot of nearly blank episodes - _logger.Info("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); + _logger.LogInformation("Creating virtual unaired episode {0} {1}x{2}", series.Name, tuple.Item1, tuple.Item2); await AddEpisode(series, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; diff --git a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs index e65c36d981..c62f58eb45 100644 --- a/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/Omdb/OmdbEpisodeProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Omdb; diff --git a/MediaBrowser.Providers/TV/SeasonMetadataService.cs b/MediaBrowser.Providers/TV/SeasonMetadataService.cs index a9a026db9d..aad0e26a03 100644 --- a/MediaBrowser.Providers/TV/SeasonMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeasonMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs index 338e7b4ed6..a943e49c09 100644 --- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System; using System.Collections.Generic; @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.TV } catch (Exception ex) { - Logger.ErrorException("Error in DummySeasonProvider", ex); + Logger.LogError("Error in DummySeasonProvider", ex); } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs index f6568510d4..d9933ba2a2 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeImageProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; @@ -25,8 +25,8 @@ namespace MediaBrowser.Providers.TV IRemoteImageProvider, IHasOrder { - public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) - : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager) + public MovieDbEpisodeImageProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) + : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory) {} public IEnumerable GetSupportedImages(BaseItem item) diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs index 31785ca9c7..095ce0e175 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbEpisodeProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -27,8 +27,8 @@ namespace MediaBrowser.Providers.TV IRemoteMetadataProvider, IHasOrder { - public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) - : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, logManager) + public MovieDbEpisodeProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) + : base(httpClient, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory) { } public async Task> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken) diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs index 4d7cec79fc..facf5cadf8 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbProviderBase.cs @@ -1,7 +1,7 @@ using MediaBrowser.Model.IO; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; using System; @@ -26,14 +26,14 @@ namespace MediaBrowser.Providers.TV private readonly ILocalizationManager _localization; private readonly ILogger _logger; - public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILogManager logManager) + public MovieDbProviderBase(IHttpClient httpClient, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory) { _httpClient = httpClient; _configurationManager = configurationManager; _jsonSerializer = jsonSerializer; _fileSystem = fileSystem; _localization = localization; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } protected ILogger Logger diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs index 63484483f2..8b09ee2fcf 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -32,14 +32,14 @@ namespace MediaBrowser.Providers.TV private readonly ILocalizationManager _localization; private readonly ILogger _logger; - public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILogManager logManager) + public MovieDbSeasonProvider(IHttpClient httpClient, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory) { _httpClient = httpClient; _configurationManager = configurationManager; _fileSystem = fileSystem; _localization = localization; _jsonSerializer = jsonSerializer; - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); } public async Task> GetMetadata(SeasonInfo info, CancellationToken cancellationToken) @@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.Error("No metadata found for {0}", seasonNumber.Value); + _logger.LogError("No metadata found for {0}", seasonNumber.Value); if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs index 7f9465f1cb..c3981ae8f2 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeriesProvider.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Movies; @@ -412,7 +412,7 @@ namespace MediaBrowser.Providers.TV !string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase)) { - _logger.Info("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English..."); + _logger.LogInformation("MovieDbSeriesProvider couldn't find meta for language " + language + ". Trying English..."); url = string.Format(GetTvInfo3, id, MovieDbProvider.ApiKey) + "&language=en"; diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs index 41155aca16..d1d8e32c28 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbEpisodeProvider.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Providers; using System; using System.Collections.Generic; @@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.TV } else { - _logger.Debug("No series identity found for {0}", searchInfo.Name); + _logger.LogDebug("No series identity found for {0}", searchInfo.Name); } return result; diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs index 2839cb434f..6bad5b9257 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using System; using System.Collections.Generic; @@ -358,7 +358,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.ErrorException("Error updating tvdb series id {0}, language {1}", ex, seriesId, language); + _logger.LogError("Error updating tvdb series id {0}, language {1}", ex, seriesId, language); // Already logged at lower levels, but don't fail the whole operation, unless timed out // We have to fail this to make it run again otherwise new episode data could potentially be missing @@ -389,7 +389,7 @@ namespace MediaBrowser.Providers.TV /// Task. private Task UpdateSeries(string id, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken) { - _logger.Info("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage); + _logger.LogInformation("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage); seriesDataPath = Path.Combine(seriesDataPath, id); diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs index 8b7efc28b8..515f58c27b 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesProvider.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using System; diff --git a/MediaBrowser.Providers/Users/UserMetadataService.cs b/MediaBrowser.Providers/Users/UserMetadataService.cs index 694315c180..361d42f500 100644 --- a/MediaBrowser.Providers/Users/UserMetadataService.cs +++ b/MediaBrowser.Providers/Users/UserMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Videos/VideoMetadataService.cs b/MediaBrowser.Providers/Videos/VideoMetadataService.cs index f493eb31f9..b9868cea90 100644 --- a/MediaBrowser.Providers/Videos/VideoMetadataService.cs +++ b/MediaBrowser.Providers/Videos/VideoMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.Providers/Years/YearMetadataService.cs b/MediaBrowser.Providers/Years/YearMetadataService.cs index 7838336562..d62cb10b5a 100644 --- a/MediaBrowser.Providers/Years/YearMetadataService.cs +++ b/MediaBrowser.Providers/Years/YearMetadataService.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Providers.Manager; using System.Collections.Generic; diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj index 480b422bc2..038a26f9d1 100644 --- a/MediaBrowser.Server.Mono/EmbyServer.csproj +++ b/MediaBrowser.Server.Mono/EmbyServer.csproj @@ -18,6 +18,8 @@ + + diff --git a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs index 49955ad652..29760ec55b 100644 --- a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs +++ b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs @@ -6,7 +6,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Emby.Drawing.Skia; using MediaBrowser.Model.System; using MediaBrowser.Model.Globalization; @@ -16,7 +16,6 @@ namespace MediaBrowser.Server.Startup.Common public class ImageEncoderHelper { public static IImageEncoder GetImageEncoder(ILogger logger, - ILogManager logManager, IFileSystem fileSystem, StartupOptions startupOptions, Func httpClient, @@ -28,20 +27,20 @@ namespace MediaBrowser.Server.Startup.Common { try { - return new SkiaEncoder(logManager.GetLogger("Skia"), appPaths, httpClient, fileSystem, localizationManager); + return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); } catch (Exception ex) { - logger.Info("Skia not available. Will try next image processor. {0}", ex.Message); + logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message); } try { - return new ImageMagickEncoder(logManager.GetLogger("ImageMagick"), appPaths, httpClient, fileSystem, environment); + return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); } catch { - logger.Info("ImageMagick not available. Will try next image processor."); + logger.LogInformation("ImageMagick not available. Will try next image processor."); } } diff --git a/MediaBrowser.Server.Mono/MonoAppHost.cs b/MediaBrowser.Server.Mono/MonoAppHost.cs index 576eb5c681..c2ec423f84 100644 --- a/MediaBrowser.Server.Mono/MonoAppHost.cs +++ b/MediaBrowser.Server.Mono/MonoAppHost.cs @@ -13,7 +13,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Sync; using IsoMounter; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; @@ -21,7 +21,8 @@ namespace MediaBrowser.Server.Mono { public class MonoAppHost : ApplicationHost { - public MonoAppHost(ServerApplicationPaths applicationPaths, ILogManager logManager, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) : base(applicationPaths, logManager, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) + public MonoAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) + : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) { } @@ -86,7 +87,8 @@ namespace MediaBrowser.Server.Mono protected override IHttpListener CreateHttpListener() { - return new EmbyServer.SocketSharp.WebSocketSharpListener(LogManager.GetLogger("HttpServer"), + return new EmbyServer.SocketSharp.WebSocketSharpListener( + Logger, Certificate, StreamHelper, TextEncoding, diff --git a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs index 2fd95ab826..2499d8bb51 100644 --- a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs +++ b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs @@ -1,5 +1,5 @@ using Emby.Server.Implementations.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; using Mono.Unix.Native; @@ -15,7 +15,7 @@ namespace MediaBrowser.Server.Mono.Native public override void SetExecutable(string path) { // Linux: File permission to 666, and user's execute bit - Logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path); + Logger.LogInformation("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path); Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH); } diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 887a9545f5..21845d10e5 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -1,4 +1,3 @@ -using MediaBrowser.Model.Logging; using MediaBrowser.Server.Mono.Native; using MediaBrowser.Server.Startup.Common; using System; @@ -15,16 +14,18 @@ using Emby.Drawing; using Emby.Server.Implementations; using Emby.Server.Implementations.EnvironmentInfo; using Emby.Server.Implementations.IO; -using Emby.Server.Implementations.Logging; using Emby.Server.Implementations.Networking; using MediaBrowser.Controller; using MediaBrowser.Model.IO; using MediaBrowser.Model.System; using Mono.Unix.Native; -using ILogger = MediaBrowser.Model.Logging.ILogger; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; using System.Threading; using InteropServices = System.Runtime.InteropServices; +using Microsoft.Extensions.Logging; +using ILogger = Microsoft.Extensions.Logging.ILogger; +using Serilog; +using Serilog.AspNetCore; namespace MediaBrowser.Server.Mono { @@ -33,7 +34,7 @@ namespace MediaBrowser.Server.Mono private static ILogger _logger; private static IFileSystem FileSystem; private static IServerApplicationPaths _appPaths; - private static ILogManager _logManager; + private static ILoggerFactory _loggerFactory; private static readonly TaskCompletionSource ApplicationTaskCompletionSource = new TaskCompletionSource(); private static bool _restartOnShutdown; @@ -52,23 +53,24 @@ namespace MediaBrowser.Server.Mono var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath); _appPaths = appPaths; - using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server")) + var logger = new LoggerConfiguration() + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger(); + + using (var loggerFactory = new SerilogLoggerFactory(logger)) { - _logManager = logManager; + _loggerFactory = loggerFactory; - var task = logManager.ReloadLogger(LogSeverity.Debug, CancellationToken.None); - Task.WaitAll(task); - logManager.AddConsoleOutput(); + _logger = loggerFactory.CreateLogger("Main"); - var logger = _logger = logManager.GetLogger("Main"); - - ApplicationHost.LogEnvironmentInfo(logger, appPaths, true); + ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - RunApplication(appPaths, logManager, options); + RunApplication(appPaths, loggerFactory, options); - _logger.Info("Disposing app host"); + _logger.LogInformation("Disposing app host"); if (_restartOnShutdown) { @@ -109,27 +111,27 @@ namespace MediaBrowser.Server.Mono return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath); } - private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options) + private static void RunApplication(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory, StartupOptions options) { // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); var environmentInfo = GetEnvironmentInfo(); - var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); + var fileSystem = new ManagedFileSystem(loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); FileSystem = fileSystem; using (var appHost = new MonoAppHost(appPaths, - logManager, + loggerFactory, options, fileSystem, new PowerManagement(), "embyserver-mono_{version}.zip", environmentInfo, new NullImageEncoder(), - new SystemEvents(logManager.GetLogger("SystemEvents")), - new NetworkManager(logManager.GetLogger("NetworkManager"), environmentInfo))) + new SystemEvents(loggerFactory.CreateLogger("SystemEvents")), + new NetworkManager(loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) { if (options.ContainsOption("-v")) { @@ -141,7 +143,7 @@ namespace MediaBrowser.Server.Mono appHost.Init(); - appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); + appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); Console.WriteLine("Running startup tasks"); @@ -221,7 +223,7 @@ namespace MediaBrowser.Server.Mono } catch (Exception ex) { - _logger.ErrorException("Error getting unix name", ex); + _logger.LogError("Error getting unix name", ex); } _unixName = uname; } @@ -243,6 +245,8 @@ namespace MediaBrowser.Server.Mono { var exception = (Exception)e.ExceptionObject; + // TODO + /* new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); if (!Debugger.IsAttached) @@ -254,7 +258,7 @@ namespace MediaBrowser.Server.Mono { Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception)); } - } + }*/ } public static void Shutdown() @@ -271,7 +275,7 @@ namespace MediaBrowser.Server.Mono private static void StartNewInstance(StartupOptions startupOptions) { - _logger.Info("Starting new instance"); + _logger.LogInformation("Starting new instance"); string module = startupOptions.GetOption("-restartpath"); string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty; @@ -290,8 +294,8 @@ namespace MediaBrowser.Server.Mono commandLineArgsString = string.Join(" ", args); } - _logger.Info("Executable: {0}", module); - _logger.Info("Arguments: {0}", commandLineArgsString); + _logger.LogInformation("Executable: {0}", module); + _logger.LogInformation("Arguments: {0}", commandLineArgsString); Process.Start(module, commandLineArgsString); } diff --git a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs b/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs index 6c2dd0f76e..fd32640a25 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs @@ -1,5 +1,5 @@ using MediaBrowser.Common.Events; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; @@ -55,7 +55,7 @@ namespace EmbyServer.SocketSharp void socket_OnError(object sender, SocketHttpListener.ErrorEventArgs e) { - _logger.Error("Error in SharpWebSocket: {0}", e.Message ?? string.Empty); + _logger.LogError("Error in SharpWebSocket: {0}", e.Message ?? string.Empty); //EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger); } diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs index e75a38e385..e8557d1f99 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using SocketHttpListener.Net; using System; using System.Collections.Generic; @@ -74,7 +74,7 @@ namespace EmbyServer.SocketSharp foreach (var prefix in urlPrefixes) { - _logger.Info("Adding HttpListener prefix " + prefix); + _logger.LogInformation("Adding HttpListener prefix " + prefix); _listener.Prefixes.Add(prefix); } @@ -93,7 +93,7 @@ namespace EmbyServer.SocketSharp { var url = request.Url.ToString(); - logger.Info("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty); + logger.LogInformation("{0} {1}. UserAgent: {2}", request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty); } private Task InitTask(HttpListenerContext context, CancellationToken cancellationToken) @@ -114,7 +114,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error processing request", ex); + _logger.LogError("Error processing request", ex); httpReq = httpReq ?? GetRequest(context); return ErrorHandler(ex, httpReq, true, true); @@ -148,7 +148,7 @@ namespace EmbyServer.SocketSharp if (connectingArgs.AllowConnection) { - _logger.Debug("Web socket connection allowed"); + _logger.LogDebug("Web socket connection allowed"); var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false); @@ -169,14 +169,14 @@ namespace EmbyServer.SocketSharp } else { - _logger.Warn("Web socket connection not allowed"); + _logger.LogWarning("Web socket connection not allowed"); ctx.Response.StatusCode = 401; ctx.Response.Close(); } } catch (Exception ex) { - _logger.ErrorException("AcceptWebSocketAsync error", ex); + _logger.LogError("AcceptWebSocketAsync error", ex); ctx.Response.StatusCode = 500; ctx.Response.Close(); } @@ -206,7 +206,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error closing web socket response", ex); + _logger.LogError("Error closing web socket response", ex); } } @@ -259,4 +259,4 @@ namespace EmbyServer.SocketSharp } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs index 84e37a58c0..1e1c3db7c4 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs @@ -4,7 +4,7 @@ using System.IO; using System.Text; using Emby.Server.Implementations.HttpServer; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using SocketHttpListener.Net; using IHttpFile = MediaBrowser.Model.Services.IHttpFile; diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs index 15ff6675dc..d299c64ef0 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs @@ -6,7 +6,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse; using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse; @@ -112,7 +112,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.ErrorException("Error in HttpListenerResponseWrapper: " + ex.Message, ex); + _logger.LogError("Error in HttpListenerResponseWrapper: " + ex.Message, ex); } } } diff --git a/MediaBrowser.Tests/M3uParserTest.cs b/MediaBrowser.Tests/M3uParserTest.cs index 1b42a38238..b5b25b53df 100644 --- a/MediaBrowser.Tests/M3uParserTest.cs +++ b/MediaBrowser.Tests/M3uParserTest.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.LiveTv.TunerHosts; using MediaBrowser.Common.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MediaBrowser.Tests diff --git a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs index 8acc490e7a..f991034388 100644 --- a/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs +++ b/MediaBrowser.Tests/MediaEncoding/Subtitles/SrtParserTests.cs @@ -2,7 +2,7 @@ using System.IO; using System.Threading; using Emby.Server.MediaEncoding.Subtitles; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -111,4 +111,4 @@ namespace MediaBrowser.Tests.MediaEncoding.Subtitles } } -} \ No newline at end of file +} diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index f0c352157d..0327929a94 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; @@ -245,7 +245,7 @@ namespace MediaBrowser.WebDashboard.Api } catch (Exception ex) { - _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name); + _logger.LogError("Error getting plugin information from {0}", ex, p.GetType().Name); return null; } }) diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs index 619d0660f5..f510ed51f1 100644 --- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs +++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs @@ -1,5 +1,5 @@ using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index e4b11a6fc2..7461e952de 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using MediaBrowser.XbmcMetadata.Savers; using System; @@ -72,7 +72,7 @@ namespace MediaBrowser.XbmcMetadata } catch (Exception ex) { - _logger.ErrorException("Error saving metadata for {0}", ex, item.Path ?? item.Name); + _logger.LogError("Error saving metadata for {0}", ex, item.Path ?? item.Name); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 3b8d687765..0aaa0b3624 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using MediaBrowser.XbmcMetadata.Savers; using System; @@ -294,7 +294,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - Logger.Warn("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: " + val); } } break; diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index ce7b924eb8..ce56e080ab 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 94b4c30f2a..27f128fcec 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -7,7 +7,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Xml; using MediaBrowser.Model.IO; using MediaBrowser.Model.Xml; @@ -81,7 +81,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } catch (Exception ex) { - Logger.ErrorException("Error parsing set node", ex); + Logger.LogError("Error parsing set node", ex); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs index ef1b8ebb27..bcb70ee451 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Globalization; using System.Xml; using MediaBrowser.Model.IO; diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index 570a7fed80..3b46ff7d60 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Xml; using MediaBrowser.Model.IO; @@ -91,7 +91,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - Logger.Info("Unrecognized series status: " + status); + Logger.LogInformation("Unrecognized series status: " + status); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs index f56ceed898..e8028f6ad1 100644 --- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs index 4fcc222f8a..b6b61258b1 100644 --- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs index eeb55d8bcf..c7ff553238 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using MediaBrowser.XbmcMetadata.Savers; using System.Linq; @@ -54,4 +54,4 @@ namespace MediaBrowser.XbmcMetadata.Providers .FirstOrDefault(i => i != null); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs index 3bc10f35b9..6883048f67 100644 --- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.Collections.Generic; using System.IO; diff --git a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs index 031bdc8d20..1e4ccbe388 100644 --- a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Xml; namespace MediaBrowser.XbmcMetadata.Providers @@ -30,4 +30,4 @@ namespace MediaBrowser.XbmcMetadata.Providers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs index 0d214f58df..ddd32512a4 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs index 368d37e0a4..34a7a088e8 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs @@ -1,7 +1,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Parsers; using System.IO; using System.Threading; diff --git a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs index dcce00d69c..54d0b8baeb 100644 --- a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; diff --git a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs index f571dc2b73..cc0da1b368 100644 --- a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System.Collections.Generic; using System.Globalization; @@ -91,4 +91,4 @@ namespace MediaBrowser.XbmcMetadata.Savers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index f6ea9b4b23..74e7143625 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System; using System.Collections.Generic; @@ -230,7 +230,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - Logger.Error("Error setting hidden attribute on {0} - {1}", path, ex.Message); + Logger.LogError("Error setting hidden attribute on {path} - {ex}", path, ex.Message); } } @@ -283,7 +283,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (XmlException ex) { - Logger.ErrorException("Error reading existng nfo", ex); + Logger.LogError("Error reading existng nfo", ex); } writer.WriteEndElement(); @@ -774,9 +774,9 @@ namespace MediaBrowser.XbmcMetadata.Savers try { var tagName = GetTagForProviderKey(providerKey); - //Logger.Debug("Verifying custom provider tagname {0}", tagName); + //logger.LogDebug("Verifying custom provider tagname {0}", tagName); XmlConvert.VerifyName(tagName); - //Logger.Debug("Saving custom provider tagname {0}", tagName); + //logger.LogDebug("Saving custom provider tagname {0}", tagName); writer.WriteElementString(GetTagForProviderKey(providerKey), providerId); } @@ -1000,7 +1000,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - logger.ErrorException("Error reading existing xml tags from {0}.", ex, path); + logger.LogError("Error reading existing xml tags from {0}.", ex, path); return; } diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs index 33f96fc8fc..d1f30b1fe2 100644 --- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.XbmcMetadata.Configuration; using System.Collections.Generic; using System.Globalization; @@ -115,4 +115,4 @@ namespace MediaBrowser.XbmcMetadata.Savers { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs index 0fc74e66b3..c703a9ea67 100644 --- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.IO; using System.Xml; diff --git a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs index 5a626eef9c..50ae8d24e6 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs @@ -2,7 +2,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Globalization; using System.IO; diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs index 27bc5f038f..e0f08dbdbb 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Globalization; using System.IO; diff --git a/Mono.Nat/NatManager.cs b/Mono.Nat/NatManager.cs index 752fd04161..3ed01a6b3c 100644 --- a/Mono.Nat/NatManager.cs +++ b/Mono.Nat/NatManager.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Linq; namespace Mono.Nat diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs index dc0e2c89b5..99d030207b 100644 --- a/Mono.Nat/Pmp/PmpNatDevice.cs +++ b/Mono.Nat/Pmp/PmpNatDevice.cs @@ -32,7 +32,7 @@ using System.Threading; using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Mono.Nat.Pmp { @@ -132,7 +132,7 @@ namespace Mono.Nat.Pmp mapping.Protocol, mapping.PrivatePort, e.Message); - _logger.Debug(message); + _logger.LogDebug(message); throw e; } @@ -183,7 +183,7 @@ namespace Mono.Nat.Pmp }; var errorMsg = errors[resultCode]; - _logger.Debug("Error in CreatePortMapListen: " + errorMsg); + _logger.LogDebug("Error in CreatePortMapListen: " + errorMsg); return; } @@ -198,7 +198,7 @@ namespace Mono.Nat.Pmp } catch (Exception ex) { - _logger.ErrorException("Error in CreatePortMapListen", ex); + _logger.LogError("Error in CreatePortMapListen", ex); return; } } diff --git a/Mono.Nat/Pmp/PmpSearcher.cs b/Mono.Nat/Pmp/PmpSearcher.cs index 180fb48d71..98cf37f147 100644 --- a/Mono.Nat/Pmp/PmpSearcher.cs +++ b/Mono.Nat/Pmp/PmpSearcher.cs @@ -37,7 +37,7 @@ using Mono.Nat.Pmp; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading.Tasks; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System.Linq; namespace Mono.Nat @@ -208,7 +208,7 @@ namespace Mono.Nat return; int errorcode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, 2)); if (errorcode != 0) - _logger.Debug("Non zero error: {0}", errorcode); + _logger.LogDebug("Non zero error: {0}", errorcode); IPAddress publicIp = new IPAddress(new byte[] { response[8], response[9], response[10], response[11] }); nextSearch = DateTime.Now.AddMinutes(5); diff --git a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs index 3395b7596f..4b765fd421 100644 --- a/Mono.Nat/Upnp/Messages/GetServicesMessage.cs +++ b/Mono.Nat/Upnp/Messages/GetServicesMessage.cs @@ -28,7 +28,7 @@ using System; using System.Diagnostics; using System.Net; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Mono.Nat.Upnp { @@ -42,10 +42,10 @@ namespace Mono.Nat.Upnp : base(null) { if (string.IsNullOrEmpty(description)) - _logger.Warn("Description is null"); + _logger.LogWarning("Description is null"); if (hostAddress == null) - _logger.Warn("hostaddress is null"); + _logger.LogWarning("hostaddress is null"); this.servicesDescriptionUrl = description; this.hostAddress = hostAddress; diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs index 7c1e89d3ba..e9e47a91e9 100644 --- a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs +++ b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs @@ -37,7 +37,7 @@ using System.Diagnostics; using System.Net.Sockets; using System.Net.NetworkInformation; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Dlna; using System.Threading.Tasks; @@ -90,7 +90,7 @@ namespace Mono.Nat } catch (Exception ex) { - _logger.ErrorException("Error decoding device response", ex); + _logger.LogError("Error decoding device response", ex); } } diff --git a/Mono.Nat/Upnp/UpnpNatDevice.cs b/Mono.Nat/Upnp/UpnpNatDevice.cs index cae7f5fc82..62539103ac 100644 --- a/Mono.Nat/Upnp/UpnpNatDevice.cs +++ b/Mono.Nat/Upnp/UpnpNatDevice.cs @@ -34,7 +34,7 @@ using System.Text; using System.Diagnostics; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Dlna; namespace Mono.Nat.Upnp @@ -77,7 +77,7 @@ namespace Mono.Nat.Upnp // Are we going to get addresses with the "http://" attached? if (locationDetails.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { - _logger.Debug("Found device at: {0}", locationDetails); + _logger.LogDebug("Found device at: {0}", locationDetails); // This bit strings out the "http://" from the string locationDetails = locationDetails.Substring(7); @@ -89,7 +89,7 @@ namespace Mono.Nat.Upnp } else { - _logger.Debug("Couldn't decode address. Please send following string to the developer: "); + _logger.LogDebug("Couldn't decode address. Please send following string to the developer: "); } } @@ -116,7 +116,7 @@ namespace Mono.Nat.Upnp { if (response.StatusCode != HttpStatusCode.OK) { - _logger.Debug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); + _logger.LogDebug("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); return; // FIXME: This the best thing to do?? } @@ -139,7 +139,7 @@ namespace Mono.Nat.Upnp { return; } - _logger.Debug("{0}: Couldn't parse services list", HostEndPoint); + _logger.LogDebug("{0}: Couldn't parse services list", HostEndPoint); System.Threading.Thread.Sleep(10); } } @@ -155,14 +155,14 @@ namespace Mono.Nat.Upnp { //If the service is a WANIPConnection, then we have what we want string type = service["serviceType"].InnerText; - _logger.Debug("{0}: Found service: {1}", HostEndPoint, type); + _logger.LogDebug("{0}: Found service: {1}", HostEndPoint, type); // TODO: Add support for version 2 of UPnP. if (string.Equals(type, "urn:schemas-upnp-org:service:WANPPPConnection:1", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "urn:schemas-upnp-org:service:WANIPConnection:1", StringComparison.OrdinalIgnoreCase)) { this.controlUrl = service["controlURL"].InnerText; - _logger.Debug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); + _logger.LogDebug("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); Uri u; if (Uri.TryCreate(controlUrl, UriKind.RelativeOrAbsolute, out u)) @@ -174,15 +174,15 @@ namespace Mono.Nat.Upnp if (IPAddress.TryParse(u.Host, out parsedHostIpAddress)) { this.hostEndPoint = new IPEndPoint(parsedHostIpAddress, u.Port); - //_logger.Debug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); + //_logger.LogDebug("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length); - //_logger.Debug("{0}: New control url: {1}", HostEndPoint, controlUrl); + //_logger.LogDebug("{0}: New control url: {1}", HostEndPoint, controlUrl); } } } else { - _logger.Debug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); + _logger.LogDebug("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); } return; } @@ -266,4 +266,4 @@ namespace Mono.Nat.Upnp this.hostEndPoint, "Manually Check" /*this.GetExternalIP()*/, this.controlUrl, this.serviceDescriptionUrl, this.serviceType, this.LastSeen); } } -} \ No newline at end of file +} diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index bc85946496..921ef3e514 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace Rssdp.Infrastructure @@ -131,7 +131,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error in BeginListeningForBroadcasts", ex); + _logger.LogError("Error in BeginListeningForBroadcasts", ex); } } } @@ -148,7 +148,7 @@ namespace Rssdp.Infrastructure { if (_BroadcastListenSocket != null) { - _logger.Info("{0} disposing _BroadcastListenSocket.", GetType().Name); + _logger.LogInformation("{0} disposing _BroadcastListenSocket.", GetType().Name); _BroadcastListenSocket.Dispose(); _BroadcastListenSocket = null; } @@ -197,7 +197,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString()); + _logger.LogError("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString()); } } @@ -282,11 +282,11 @@ namespace Rssdp.Infrastructure var sockets = _sendSockets.ToList(); _sendSockets = null; - _logger.Info("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count); + _logger.LogInformation("{0} Disposing {1} sendSockets", GetType().Name, sockets.Count); foreach (var socket in sockets) { - _logger.Info("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); + _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); socket.Dispose(); } } @@ -376,7 +376,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.ErrorException("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address); + _logger.LogError("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address); } } } @@ -508,4 +508,4 @@ namespace Rssdp.Infrastructure #endregion } -} \ No newline at end of file +} diff --git a/SocketHttpListener/Net/HttpConnection.cs b/SocketHttpListener/Net/HttpConnection.cs index 9b4fb87059..4fc9a468c7 100644 --- a/SocketHttpListener/Net/HttpConnection.cs +++ b/SocketHttpListener/Net/HttpConnection.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading.Tasks; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -173,7 +173,7 @@ namespace SocketHttpListener.Net private void OnTimeout(object unused) { - //_logger.Info("HttpConnection timer fired"); + //_logger.LogInformation("HttpConnection timer fired"); CloseSocket(); Unbind(); } @@ -556,4 +556,4 @@ namespace SocketHttpListener.Net } } } -} \ No newline at end of file +} diff --git a/SocketHttpListener/Net/HttpEndPointListener.cs b/SocketHttpListener/Net/HttpEndPointListener.cs index 254e761403..867012d051 100644 --- a/SocketHttpListener/Net/HttpEndPointListener.cs +++ b/SocketHttpListener/Net/HttpEndPointListener.cs @@ -8,7 +8,7 @@ using System.Security.Cryptography.X509Certificates; using System.Threading; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -173,7 +173,7 @@ namespace SocketHttpListener.Net { HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken; - epl._logger.ErrorException("Error in socket.AcceptAsync", ex); + epl._logger.LogError("Error in socket.AcceptAsync", ex); } } @@ -204,7 +204,7 @@ namespace SocketHttpListener.Net if (socketError == SocketError.ConnectionReset) { - epl._logger.Error("SocketError.ConnectionReset reported. Attempting to re-accept."); + epl._logger.LogError("SocketError.ConnectionReset reported. Attempting to re-accept."); return; } @@ -223,13 +223,13 @@ namespace SocketHttpListener.Net { var remoteEndPointString = accepted.RemoteEndPoint == null ? string.Empty : accepted.RemoteEndPoint.ToString(); var localEndPointString = accepted.LocalEndPoint == null ? string.Empty : accepted.LocalEndPoint.ToString(); - //_logger.Info("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure); + //_logger.LogInformation("HttpEndPointListener Accepting connection from {0} to {1} secure connection requested: {2}", remoteEndPointString, localEndPointString, _secure); HttpConnection conn = new HttpConnection(epl._logger, accepted, epl, epl._secure, epl._cert, epl._cryptoProvider, epl._streamHelper, epl._textEncoding, epl._fileSystem, epl._environment); await conn.Init().ConfigureAwait(false); - //_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId); + //_logger.LogDebug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId); lock (epl._unregisteredConnections) { epl._unregisteredConnections[conn] = conn; @@ -238,7 +238,7 @@ namespace SocketHttpListener.Net } catch (Exception ex) { - epl._logger.ErrorException("Error in ProcessAccept", ex); + epl._logger.LogError("Error in ProcessAccept", ex); TryClose(accepted); epl.Accept(); diff --git a/SocketHttpListener/Net/HttpEndPointManager.cs b/SocketHttpListener/Net/HttpEndPointManager.cs index 45af92c01a..01b5ae9bd9 100644 --- a/SocketHttpListener/Net/HttpEndPointManager.cs +++ b/SocketHttpListener/Net/HttpEndPointManager.cs @@ -6,7 +6,7 @@ using System.Net.Sockets; using System.Reflection; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using SocketHttpListener.Primitives; diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs index 759be64c95..fffecae633 100644 --- a/SocketHttpListener/Net/HttpListener.cs +++ b/SocketHttpListener/Net/HttpListener.cs @@ -7,7 +7,7 @@ using System.Security.Cryptography.X509Certificates; using MediaBrowser.Common.Net; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; @@ -59,7 +59,7 @@ namespace SocketHttpListener.Net } public HttpListener(X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) - :this(new NullLogger(), certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) + :this(null, certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) { } diff --git a/SocketHttpListener/Net/HttpListenerContext.cs b/SocketHttpListener/Net/HttpListenerContext.cs index b90f075671..0aaac1ad51 100644 --- a/SocketHttpListener/Net/HttpListenerContext.cs +++ b/SocketHttpListener/Net/HttpListenerContext.cs @@ -1,6 +1,10 @@ using System; using System.Net; using System.Security.Principal; +using MediaBrowser.Model.Cryptography; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; +using MediaBrowser.Model.Text; using SocketHttpListener.Net.WebSockets; using System.Threading.Tasks; diff --git a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs index 53efcb0fad..ed99af1a65 100644 --- a/SocketHttpListener/Net/HttpListenerPrefixCollection.cs +++ b/SocketHttpListener/Net/HttpListenerPrefixCollection.cs @@ -1,7 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace SocketHttpListener.Net { diff --git a/SocketHttpListener/Net/HttpResponseStream.Managed.cs b/SocketHttpListener/Net/HttpResponseStream.Managed.cs index 1a8a195fb6..e727f1b4af 100644 --- a/SocketHttpListener/Net/HttpResponseStream.Managed.cs +++ b/SocketHttpListener/Net/HttpResponseStream.Managed.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; namespace SocketHttpListener.Net From 3d3ec3588b523bd6f47795886ef9bdaebc850f95 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 13 Dec 2018 18:40:51 +0100 Subject: [PATCH 013/125] Mark where ILogger is being set to null --- Emby.Dlna/Didl/DidlBuilder.cs | 6 +++--- Emby.Dlna/PlayTo/PlayToController.cs | 2 +- .../Emby.Server.Implementations.csproj | 4 ++-- Emby.Server.Implementations/Services/ServiceHandler.cs | 2 +- MediaBrowser.Controller/Providers/DirectoryService.cs | 2 +- MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs | 2 +- SocketHttpListener/Net/HttpListener.cs | 1 + 7 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 22845586f3..7ed249f4d0 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -180,7 +180,7 @@ namespace Emby.Dlna.Didl return _logger; } - return null; + return null; // TODO: @bond NullLogger } private string GetMimeType(string input) @@ -925,7 +925,7 @@ namespace Emby.Dlna.Didl } catch (XmlException) { - _logger?.LogError("Error adding xml value: {value}", name); + _logger.LogError("Error adding xml value: {value}", name); } } @@ -937,7 +937,7 @@ namespace Emby.Dlna.Didl } catch (XmlException) { - _logger?.LogError("Error adding xml value: {value}", value); + _logger.LogError("Error adding xml value: {value}", value); } } diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 272f2e1276..600c8ae50f 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -539,7 +539,7 @@ namespace Emby.Dlna.PlayTo return _logger; } - return null; + return null; // TODO: @bond NullLogger } private PlaylistItem GetPlaylistItem(BaseItem item, List mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index bf459defb2..2415050198 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -38,7 +38,7 @@ false - + @@ -46,6 +46,6 @@ - + diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs index 50965b4a97..0f9be1e648 100644 --- a/Emby.Server.Implementations/Services/ServiceHandler.cs +++ b/Emby.Server.Implementations/Services/ServiceHandler.cs @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Services if (this.RestPath == null) { string contentType; - // TODO: change null out + // TODO: @bond NullLogger this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, null, out contentType); if (contentType != null) diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 2d97e0b887..95f1e1c6cc 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -27,7 +27,7 @@ namespace MediaBrowser.Controller.Providers } public DirectoryService(IFileSystem fileSystem) - : this(null, fileSystem) // TODO change + : this(null, fileSystem) // TODO: @bond NullLogger { } diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 6e217ab4a5..b8d4a92c12 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.Providers public bool EnableRemoteContentProbe { get; set; } public MetadataRefreshOptions(IFileSystem fileSystem) - : this(new DirectoryService(null, fileSystem)) // TODO + : this(new DirectoryService(null, fileSystem)) // TODO: @bond NullLogger { } diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs index fffecae633..3b21387e00 100644 --- a/SocketHttpListener/Net/HttpListener.cs +++ b/SocketHttpListener/Net/HttpListener.cs @@ -58,6 +58,7 @@ namespace SocketHttpListener.Net auth_schemes = AuthenticationSchemes.Anonymous; } + // TODO: @bond NullLogger public HttpListener(X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) :this(null, certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) { From b7ebb67cbbad8c670215a3c24401a1047bbaea5e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 14 Dec 2018 20:17:29 +0100 Subject: [PATCH 014/125] Remove the need for NullLogger --- Emby.Dlna/Didl/DidlBuilder.cs | 14 ++------------ Emby.Dlna/PlayTo/PlayToController.cs | 14 ++------------ .../Channels/ChannelManager.cs | 5 ++--- .../Collections/CollectionManager.cs | 10 +++++----- .../EntryPoints/RefreshUsersMetadata.cs | 8 ++++++-- .../HttpServer/HttpListenerHost.cs | 2 +- .../Library/LibraryManager.cs | 14 +++++++------- .../Library/MediaSourceManager.cs | 3 ++- Emby.Server.Implementations/Library/UserManager.cs | 2 +- .../Library/Validators/PeopleValidator.cs | 2 +- .../LiveTv/EmbyTV/EmbyTV.cs | 2 +- .../LiveTv/LiveTvManager.cs | 2 +- .../Playlists/PlaylistManager.cs | 6 +++--- .../ScheduledTasks/ChapterImagesTask.cs | 2 +- .../Services/ServiceController.cs | 6 +++--- .../Services/ServiceHandler.cs | 7 +++---- .../Services/ServicePath.cs | 14 ++++---------- MediaBrowser.Api/ItemLookupService.cs | 2 +- MediaBrowser.Api/ItemUpdateService.cs | 2 +- MediaBrowser.Api/Subtitles/SubtitleService.cs | 2 +- MediaBrowser.Api/UserLibrary/UserLibraryService.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- .../Providers/DirectoryService.cs | 5 ----- .../Providers/MetadataRefreshOptions.cs | 5 ----- MediaBrowser.Providers/Manager/ProviderManager.cs | 12 ++++++++++-- MediaBrowser.Providers/TV/DummySeasonProvider.cs | 2 +- .../TV/MissingEpisodeProvider.cs | 2 +- SocketHttpListener/Net/HttpListener.cs | 6 ------ 28 files changed, 62 insertions(+), 93 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 7ed249f4d0..2cde379eaa 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -173,16 +173,6 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); } - private ILogger GetStreamBuilderLogger(DlnaOptions options) - { - if (options.EnableDebugLog) - { - return _logger; - } - - return null; // TODO: @bond NullLogger - } - private string GetMimeType(string input) { var mime = MimeTypes.GetMimeType(input); @@ -202,7 +192,7 @@ namespace Emby.Dlna.Didl { var sources = _mediaSourceManager.GetStaticMediaSources(video, true, _user); - streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildVideoItem(new VideoOptions + streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions { ItemId = video.Id, MediaSources = sources.ToArray(), @@ -509,7 +499,7 @@ namespace Emby.Dlna.Didl { var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user); - streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildAudioItem(new AudioOptions + streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions { ItemId = audio.Id, MediaSources = sources.ToArray(), diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 600c8ae50f..e722f83d81 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -532,23 +532,13 @@ namespace Emby.Dlna.PlayTo return null; } - private ILogger GetStreamBuilderLogger() - { - if (_config.GetDlnaConfiguration().EnableDebugLog) - { - return _logger; - } - - return null; // TODO: @bond NullLogger - } - private PlaylistItem GetPlaylistItem(BaseItem item, List mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) { if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase)) { return new PlaylistItem { - StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildVideoItem(new VideoOptions + StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions { ItemId = item.Id, MediaSources = mediaSources.ToArray(), @@ -568,7 +558,7 @@ namespace Emby.Dlna.PlayTo { return new PlaylistItem { - StreamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger()).BuildAudioItem(new AudioOptions + StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions { ItemId = item.Id, MediaSources = mediaSources.ToArray(), diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index aa04c98f09..88dfbd7c15 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -484,10 +484,9 @@ namespace Emby.Server.Implementations.Channels _libraryManager.CreateItem(item, null); } - await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) + await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = !isNew && forceUpdate - }, cancellationToken); return item; @@ -1178,7 +1177,7 @@ namespace Emby.Server.Implementations.Channels if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime)) { - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal); + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); } return item; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 155d7ed4a0..af7c70d7d8 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.Collections if (options.ItemIdList.Length > 0) { - AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(_fileSystem) + AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // The initial adding of items is going to create a local metadata file // This will cause internet metadata to be skipped as a result @@ -152,7 +152,7 @@ namespace Emby.Server.Implementations.Collections } else { - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High); + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High); } EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs @@ -173,12 +173,12 @@ namespace Emby.Server.Implementations.Collections public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(_fileSystem)); + AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); } public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(_fileSystem)); + AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); } private void AddToCollection(Guid collectionId, IEnumerable ids, bool fireEvent, MetadataRefreshOptions refreshOptions) @@ -283,7 +283,7 @@ namespace Emby.Server.Implementations.Collections } collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None); - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, RefreshPriority.High); diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index 4c16b1d39e..660ca3a941 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading.Tasks; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -15,10 +16,12 @@ namespace Emby.Server.Implementations.EntryPoints /// public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask { + private readonly ILogger _logger; /// /// The _user manager /// private readonly IUserManager _userManager; + private IFileSystem _fileSystem; public string Name => "Refresh Users"; @@ -41,8 +44,9 @@ namespace Emby.Server.Implementations.EntryPoints /// /// Initializes a new instance of the class. /// - public RefreshUsersMetadata(IUserManager userManager, IFileSystem fileSystem) + public RefreshUsersMetadata(ILogger logger, IUserManager userManager, IFileSystem fileSystem) { + _logger = logger; _userManager = userManager; _fileSystem = fileSystem; } @@ -55,7 +59,7 @@ namespace Emby.Server.Implementations.EntryPoints { cancellationToken.ThrowIfCancellationRequested(); - await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 2a353584ca..1d87d0e445 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -718,7 +718,7 @@ namespace Emby.Server.Implementations.HttpServer } string contentType; - var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, _logger, out contentType); + var restPath = ServiceHandler.FindMatchingRestPath(httpReq.HttpMethod, pathInfo, out contentType); if (restPath != null) { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 52fb8938a6..e1a725c936 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1065,11 +1065,11 @@ namespace Emby.Server.Implementations.Library await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); // Start by just validating the children of the root, but go no further - await RootFolder.ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false); + await RootFolder.ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false); await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false); - await GetUserRootFolder().ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false).ConfigureAwait(false); + await GetUserRootFolder().ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false); // Quickly scan CollectionFolders for changes foreach (var folder in GetUserRootFolder().Children.OfType().ToList()) @@ -1089,7 +1089,7 @@ namespace Emby.Server.Implementations.Library innerProgress.RegisterAction(pct => progress.Report(pct * .96)); // Now validate the entire media library - await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: true).ConfigureAwait(false); + await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: true).ConfigureAwait(false); progress.Report(96); @@ -2176,7 +2176,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None); - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.Normal); + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); } return item; @@ -2231,7 +2231,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2295,7 +2295,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2369,7 +2369,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 2f8a1aa5e0..15673d25d5 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -4,6 +4,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using Microsoft.Extensions.Logging; @@ -127,7 +128,7 @@ namespace Emby.Server.Implementations.Library if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video)) { - await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(_fileSystem) + await item.RefreshMetadata(new MediaBrowser.Controller.Providers.MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { EnableRemoteContentProbe = true, MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index 2e675ee7e7..35b0ca304e 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -613,7 +613,7 @@ namespace Emby.Server.Implementations.Library { foreach (var user in Users) { - await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index a4949099ab..80e3965830 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Validators { var item = _libraryManager.GetPerson(person); - var options = new MetadataRefreshOptions(_fileSystem) + var options = new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ImageRefreshMode = MetadataRefreshMode.ValidationOnly, MetadataRefreshMode = MetadataRefreshMode.ValidationOnly diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 11cb57ff78..b9b8802a82 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1526,7 +1526,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _logger.LogInformation("Refreshing recording parent {0}", item.Path); - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { RefreshPaths = new string[] { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 5c0f76ba19..d74636e8de 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1292,7 +1292,7 @@ namespace Emby.Server.Implementations.LiveTv } //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken); - await currentChannel.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) + await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index f5a429552e..470711b9e2 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.Playlists parentFolder.AddChild(playlist, CancellationToken.None); - await playlist.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) { ForceSave = true }, CancellationToken.None) + await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, CancellationToken.None) .ConfigureAwait(false); if (options.ItemIdList.Length > 0) @@ -217,7 +217,7 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true @@ -250,7 +250,7 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true diff --git a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs index f259b4d931..09dcc320ac 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ChapterImagesTask.cs @@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.ScheduledTasks previouslyFailedImages = new List(); } - var directoryService = new DirectoryService(_fileSystem); + var directoryService = new DirectoryService(_logger, _fileSystem); foreach (var video in videos) { diff --git a/Emby.Server.Implementations/Services/ServiceController.cs b/Emby.Server.Implementations/Services/ServiceController.cs index 84ca2d9d1e..46af831288 100644 --- a/Emby.Server.Implementations/Services/ServiceController.cs +++ b/Emby.Server.Implementations/Services/ServiceController.cs @@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.Services pathsAtFirstMatch.Add(restPath); } - public RestPath GetRestPathForRequest(string httpMethod, string pathInfo, ILogger logger) + public RestPath GetRestPathForRequest(string httpMethod, string pathInfo) { var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo); @@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.Services RestPath bestMatch = null; foreach (var restPath in firstMatches) { - var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + var score = restPath.MatchScore(httpMethod, matchUsingPathParts); if (score > bestScore) { bestScore = score; @@ -140,7 +140,7 @@ namespace Emby.Server.Implementations.Services RestPath bestMatch = null; foreach (var restPath in firstMatches) { - var score = restPath.MatchScore(httpMethod, matchUsingPathParts, logger); + var score = restPath.MatchScore(httpMethod, matchUsingPathParts); if (score > bestScore) { bestScore = score; diff --git a/Emby.Server.Implementations/Services/ServiceHandler.cs b/Emby.Server.Implementations/Services/ServiceHandler.cs index 0f9be1e648..f5fcb5fe6b 100644 --- a/Emby.Server.Implementations/Services/ServiceHandler.cs +++ b/Emby.Server.Implementations/Services/ServiceHandler.cs @@ -24,11 +24,11 @@ namespace Emby.Server.Implementations.Services return Task.FromResult(host.CreateInstance(requestType)); } - public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType) + public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, out string contentType) { pathInfo = GetSanitizedPathInfo(pathInfo, out contentType); - return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo, logger); + return ServiceController.Instance.GetRestPathForRequest(httpMethod, pathInfo); } public static string GetSanitizedPathInfo(string pathInfo, out string contentType) @@ -63,8 +63,7 @@ namespace Emby.Server.Implementations.Services if (this.RestPath == null) { string contentType; - // TODO: @bond NullLogger - this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, null, out contentType); + this.RestPath = FindMatchingRestPath(httpMethod, pathInfo, out contentType); if (contentType != null) ResponseContentType = contentType; diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs index ef64d20b4b..ac2af3eaf9 100644 --- a/Emby.Server.Implementations/Services/ServicePath.cs +++ b/Emby.Server.Implementations/Services/ServicePath.cs @@ -309,10 +309,10 @@ namespace Emby.Server.Implementations.Services private readonly Dictionary propertyNamesMap = new Dictionary(); - public int MatchScore(string httpMethod, string[] withPathInfoParts, ILogger logger) + public int MatchScore(string httpMethod, string[] withPathInfoParts) { int wildcardMatchCount; - var isMatch = IsMatch(httpMethod, withPathInfoParts, logger, out wildcardMatchCount); + var isMatch = IsMatch(httpMethod, withPathInfoParts, out wildcardMatchCount); if (!isMatch) { return -1; @@ -348,31 +348,27 @@ namespace Emby.Server.Implementations.Services /// For performance withPathInfoParts should already be a lower case string /// to minimize redundant matching operations. /// - public bool IsMatch(string httpMethod, string[] withPathInfoParts, ILogger logger, out int wildcardMatchCount) + public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount) { wildcardMatchCount = 0; if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) { - //logger.LogInformation("withPathInfoParts mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); - return false; + return false; } if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase)) { - //logger.LogInformation("allowsAllVerbs mismatch for {0} for {1} allowedverbs {2}", httpMethod, string.Join("/", withPathInfoParts), this.allowedVerbs); return false; } if (!ExplodeComponents(ref withPathInfoParts)) { - //logger.LogInformation("ExplodeComponents mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) { - //logger.LogInformation("TotalComponentsCount mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } @@ -393,7 +389,6 @@ namespace Emby.Server.Implementations.Services // Ensure there are still enough parts left to match the remainder if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1)) { - //logger.LogInformation("withPathInfoParts length mismatch for {0} for {1}", httpMethod, string.Join("/", withPathInfoParts)); return false; } } @@ -416,7 +411,6 @@ namespace Emby.Server.Implementations.Services if (withPathInfoParts.Length <= pathIx || !LiteralsEqual(withPathInfoParts[pathIx], literalToMatch)) { - //logger.LogInformation("withPathInfoParts2 length mismatch for {0} for {1}. not equals: {2} != {3}.", httpMethod, string.Join("/", withPathInfoParts), withPathInfoParts[pathIx], literalToMatch); return false; } pathIx++; diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index d7182c1b66..331fb711d6 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -240,7 +240,7 @@ namespace MediaBrowser.Api //item.ProductionYear = request.ProductionYear; //item.Name = request.Name; - return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(_fileSystem) + return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs index 22eb7ea099..d89750eae5 100644 --- a/MediaBrowser.Api/ItemUpdateService.cs +++ b/MediaBrowser.Api/ItemUpdateService.cs @@ -230,7 +230,7 @@ namespace MediaBrowser.Api if (displayOrderChanged) { - _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(_fileSystem) + _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index 3ea1d1beda..9a149dc923 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.Api.Subtitles await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None) .ConfigureAwait(false); - _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High); + _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High); } catch (Exception ex) { diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs index 30df0ad23c..d188d7f7e8 100644 --- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs +++ b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs @@ -404,7 +404,7 @@ namespace MediaBrowser.Api.UserLibrary if (!hasMetdata) { - var options = new MetadataRefreshOptions(_fileSystem) + var options = new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 9c05217539..9ba80da698 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -2213,7 +2213,7 @@ namespace MediaBrowser.Controller.Entities /// Task. public virtual void ChangedExternally() { - ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem) + ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)) { }, RefreshPriority.High); diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 95f1e1c6cc..27d65a3e25 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -26,11 +26,6 @@ namespace MediaBrowser.Controller.Providers _fileSystem = fileSystem; } - public DirectoryService(IFileSystem fileSystem) - : this(null, fileSystem) // TODO: @bond NullLogger - { - } - public FileSystemMetadata[] GetFileSystemEntries(string path) { FileSystemMetadata[] entries; diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index b8d4a92c12..2494be83a5 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -24,11 +24,6 @@ namespace MediaBrowser.Controller.Providers public bool ForceSave { get; set; } public bool EnableRemoteContentProbe { get; set; } - public MetadataRefreshOptions(IFileSystem fileSystem) - : this(new DirectoryService(null, fileSystem)) // TODO: @bond NullLogger - { - } - public MetadataRefreshOptions(IDirectoryService directoryService) : base(directoryService) { diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index d562676413..e3b23ce337 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -329,7 +329,11 @@ namespace MediaBrowser.Providers.Manager var options = GetMetadataOptions(item); var libraryOptions = _libraryManagerFactory().GetLibraryOptions(item); - return GetImageProviders(item, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), includeDisabled).OfType(); + return GetImageProviders(item, libraryOptions, options, + new ImageRefreshOptions( + new DirectoryService(_logger, _fileSystem)), + includeDisabled) + .OfType(); } private bool CanRefresh(IMetadataProvider provider, BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, bool includeDisabled, bool forceEnableInternetMetadata) @@ -506,7 +510,11 @@ namespace MediaBrowser.Providers.Manager var libraryOptions = new LibraryOptions(); - var imageProviders = GetImageProviders(dummy, libraryOptions, options, new ImageRefreshOptions(new DirectoryService(_logger, _fileSystem)), true).ToList(); + var imageProviders = GetImageProviders(dummy, libraryOptions, options, + new ImageRefreshOptions( + new DirectoryService(_logger, _fileSystem)), + true) + .ToList(); var pluginList = summary.Plugins.ToList(); diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs index 3cf62e94e0..797005c41c 100644 --- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs +++ b/MediaBrowser.Providers/TV/DummySeasonProvider.cs @@ -147,7 +147,7 @@ namespace MediaBrowser.Providers.TV series.AddChild(season, cancellationToken); - await season.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); return season; } diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs index a8c1a68a65..19f3c07d2e 100644 --- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs @@ -414,7 +414,7 @@ namespace MediaBrowser.Providers.TV season.AddChild(episode, cancellationToken); - await episode.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); } /// diff --git a/SocketHttpListener/Net/HttpListener.cs b/SocketHttpListener/Net/HttpListener.cs index 3b21387e00..941b99f35e 100644 --- a/SocketHttpListener/Net/HttpListener.cs +++ b/SocketHttpListener/Net/HttpListener.cs @@ -58,12 +58,6 @@ namespace SocketHttpListener.Net auth_schemes = AuthenticationSchemes.Anonymous; } - // TODO: @bond NullLogger - public HttpListener(X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) - :this(null, certificate, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) - { - } - public HttpListener(ILogger logger, X509Certificate certificate, ICryptoProvider cryptoProvider, ISocketFactory socketFactory, INetworkManager networkManager, ITextEncoding textEncoding, IStreamHelper streamHelper, IFileSystem fileSystem, IEnvironmentInfo environmentInfo) : this(logger, cryptoProvider, socketFactory, networkManager, textEncoding, streamHelper, fileSystem, environmentInfo) { From 88f5471fe35657f410ddb8a58c84505301bda121 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 14 Dec 2018 20:44:24 +0100 Subject: [PATCH 015/125] Pls stop crashing --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- MediaBrowser.Server.Mono/Program.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 455e4c311b..042e48e584 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -405,7 +405,7 @@ namespace Emby.Server.Implementations // hack alert, until common can target .net core BaseExtensions.CryptographyProvider = CryptographyProvider; - XmlSerializer = new MyXmlSerializer(fileSystem, LoggerFactory.CreateLogger("XmlSerializer")); + XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory.CreateLogger("XmlSerializer")); NetworkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 21845d10e5..0630df431a 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -53,12 +53,12 @@ namespace MediaBrowser.Server.Mono var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath); _appPaths = appPaths; - var logger = new LoggerConfiguration() - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - using (var loggerFactory = new SerilogLoggerFactory(logger)) + using (var loggerFactory = new SerilogLoggerFactory( + new LoggerConfiguration() + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger() + , true)) { _loggerFactory = loggerFactory; From a51798dd8d1fe71357c7926e9657f2c67cd40ed7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 14 Dec 2018 22:07:28 +0100 Subject: [PATCH 016/125] Added logging.json file --- MediaBrowser.Server.Mono/EmbyServer.csproj | 10 +++- MediaBrowser.Server.Mono/Program.cs | 51 ++++++++++++++++--- .../Resources/Configuration/logging.json | 19 +++++++ 3 files changed, 73 insertions(+), 7 deletions(-) create mode 100644 MediaBrowser.Server.Mono/Resources/Configuration/logging.json diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj index 038a26f9d1..da7883e6bf 100644 --- a/MediaBrowser.Server.Mono/EmbyServer.csproj +++ b/MediaBrowser.Server.Mono/EmbyServer.csproj @@ -17,9 +17,13 @@ + - + + + + @@ -50,6 +54,10 @@ + + + + diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 0630df431a..1e47322f1d 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -23,6 +23,7 @@ using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certif using System.Threading; using InteropServices = System.Runtime.InteropServices; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; using ILogger = Microsoft.Extensions.Logging.ILogger; using Serilog; using Serilog.AspNetCore; @@ -53,12 +54,9 @@ namespace MediaBrowser.Server.Mono var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath); _appPaths = appPaths; - using (var loggerFactory = new SerilogLoggerFactory( - new LoggerConfiguration() - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger() - , true)) + createLogger(); + + using (var loggerFactory = new SerilogLoggerFactory()) { _loggerFactory = loggerFactory; @@ -156,6 +154,47 @@ namespace MediaBrowser.Server.Mono } } + private static async Task createLogger() + { + try + { + string path = Path.Combine(_appPaths.ProgramDataPath, "logging.json"); + + if (!File.Exists(path)) + { + var assembly = typeof(MainClass).Assembly; + // For some reason the csproj name is used instead of the assembly name + var resourcePath = "EmbyServer.Resources.Configuration.logging.json"; + using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath)) + using (Stream fstr = File.Open(path, FileMode.CreateNew)) + { + await rscstr.CopyToAsync(fstr); + } + } + var configuration = new ConfigurationBuilder() + .AddJsonFile(path) + .Build(); + + Serilog.Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .CreateLogger(); + } + catch (Exception ex) + { + Serilog.Log.Logger = new LoggerConfiguration() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.File( + Path.Combine(AppContext.BaseDirectory, "logs", "log_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") + .Enrich.FromLogContext() + .CreateLogger(); + + Serilog.Log.Logger.Fatal(ex, "Failed to read logger config"); + } + } + private static MonoEnvironmentInfo GetEnvironmentInfo() { var info = new MonoEnvironmentInfo(); diff --git a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json new file mode 100644 index 0000000000..68b57b2761 --- /dev/null +++ b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json @@ -0,0 +1,19 @@ +{ + "Serilog": { + "MinimumLevel": "Information", + "WriteTo": [ + { "Name": "Console", + "Args": { + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message}{NewLine}{Exception}" + } + }, + { "Name": "File", + "Args": { + "path": "logs//log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" + } + } + ] + } +} From 6d9ee138d6191ba33ec77b28cbc3543d59770e67 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 14 Dec 2018 23:34:53 +0100 Subject: [PATCH 017/125] More log dir configurable --- CONTRIBUTORS.md | 1 + MediaBrowser.Server.Mono/EmbyServer.csproj | 1 + MediaBrowser.Server.Mono/Program.cs | 15 +++++++++++---- .../Resources/Configuration/logging.json | 4 ++-- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 467ba15229..3a2c229d11 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -7,6 +7,7 @@ - [EraYaN](https://github.com/EraYaN) - [flemse](https://github.com/flemse) - [bfayers](https://github.com/bfayers) + - [Bond_009](https://github.com/Bond-009) # Emby Contributors diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj index da7883e6bf..609af9674b 100644 --- a/MediaBrowser.Server.Mono/EmbyServer.csproj +++ b/MediaBrowser.Server.Mono/EmbyServer.csproj @@ -17,6 +17,7 @@ + diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 1e47322f1d..32953e89d0 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -154,8 +154,13 @@ namespace MediaBrowser.Server.Mono } } - private static async Task createLogger() + private static void createLogger() { + var logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); + if (string.IsNullOrEmpty(logDir)){ + logDir = Path.Combine(_appPaths.ProgramDataPath, "logs"); + Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); + } try { string path = Path.Combine(_appPaths.ProgramDataPath, "logging.json"); @@ -168,11 +173,13 @@ namespace MediaBrowser.Server.Mono using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath)) using (Stream fstr = File.Open(path, FileMode.CreateNew)) { - await rscstr.CopyToAsync(fstr); + rscstr.CopyTo(fstr); } } var configuration = new ConfigurationBuilder() - .AddJsonFile(path) + .SetBasePath(_appPaths.ProgramDataPath) + .AddJsonFile("logging.json") + .AddEnvironmentVariables("JELLYFIN_") .Build(); Serilog.Log.Logger = new LoggerConfiguration() @@ -185,7 +192,7 @@ namespace MediaBrowser.Server.Mono Serilog.Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.File( - Path.Combine(AppContext.BaseDirectory, "logs", "log_.log"), + Path.Combine(logDir, "logs", "log_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") .Enrich.FromLogContext() diff --git a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json index 68b57b2761..78f99b2ad9 100644 --- a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json +++ b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json @@ -4,12 +4,12 @@ "WriteTo": [ { "Name": "Console", "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" } }, { "Name": "File", "Args": { - "path": "logs//log_.log", + "path": "%JELLYFIN_LOG_DIR%//log_.log", "rollingInterval": "Day", "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" } From a8fde5e89c106c4601e0535218d8fe858c6a3908 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 15 Dec 2018 00:06:57 +0100 Subject: [PATCH 018/125] Readded some stuff --- .../AppBase/BaseConfigurationManager.cs | 2 +- Emby.Server.Implementations/ApplicationHost.cs | 16 ++++++---------- .../BaseApplicationConfiguration.cs | 2 ++ MediaBrowser.Server.Mono/Program.cs | 16 ++++++++++------ 4 files changed, 19 insertions(+), 17 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index f55da91a8c..fdf2a3b731 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -97,7 +97,7 @@ namespace Emby.Server.Implementations.AppBase /// Initializes a new instance of the class. /// /// The application paths. - /// The log manager. + /// The logger factory. /// The XML serializer. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 042e48e584..aa9b6e82a3 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -693,7 +693,7 @@ namespace Emby.Server.Implementations return parts; } - /*/ + /* private void SetBaseExceptionMessage() { var builder = GetBaseExceptionMessage(ApplicationPaths); @@ -799,13 +799,9 @@ namespace Emby.Server.Implementations } JsonSerializer = CreateJsonSerializer(); - /* - OnLoggerLoaded(true); - LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false); - LoggerFactory.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging - ? LogSeverity.Debug - : LogSeverity.Info;*/ + OnLoggerLoaded(true); + //LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false); DiscoverTypes(); @@ -815,7 +811,7 @@ namespace Emby.Server.Implementations FindParts(); } - /* + protected virtual void OnLoggerLoaded(bool isFirstLoad) { Logger.LogInformation("Application version: {0}", ApplicationVersion); @@ -834,9 +830,9 @@ namespace Emby.Server.Implementations pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version)); } - Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder); + Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString()); } - }*/ + } protected virtual IHttpClient CreateHttpClient() { diff --git a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs index b5b0101cb9..f84735bed6 100644 --- a/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs +++ b/MediaBrowser.Model/Configuration/BaseApplicationConfiguration.cs @@ -9,6 +9,7 @@ namespace MediaBrowser.Model.Configuration /// public class BaseApplicationConfiguration { + // TODO: @bond Remove? /// /// Gets or sets a value indicating whether [enable debug level logging]. /// @@ -21,6 +22,7 @@ namespace MediaBrowser.Model.Configuration /// true if [enable auto update]; otherwise, false. public bool EnableAutoUpdate { get; set; } + // TODO: @bond Remove? /// /// The number of days we should retain log files /// diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 32953e89d0..9c6ee4dd22 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -137,13 +137,14 @@ namespace MediaBrowser.Server.Mono return; } - Console.WriteLine("appHost.Init"); + //Console.WriteLine("appHost.Init"); appHost.Init(); appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); - Console.WriteLine("Running startup tasks"); + //Console.WriteLine("Running startup tasks"); + _logger.LogInformation("Running startup tasks"); var task = appHost.RunStartupTasks(); Task.WaitAll(task); @@ -291,10 +292,12 @@ namespace MediaBrowser.Server.Mono { var exception = (Exception)e.ExceptionObject; - // TODO - /* - new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); + //new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); + _logger.LogCritical(exception, "Unhandled Exception"); + + // TODO: @bond + /* if (!Debugger.IsAttached) { var message = LogHelper.GetLogMessage(exception).ToString(); @@ -304,7 +307,8 @@ namespace MediaBrowser.Server.Mono { Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception)); } - }*/ + } + */ } public static void Shutdown() From 0c1b9d3bff7041b7d3b875885b8745680afcee72 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 15 Dec 2018 00:48:06 +0100 Subject: [PATCH 019/125] Rebase --- .../HttpServer/WebSocketConnection.cs | 2 +- Emby.Server.Implementations/SystemEvents.cs | 1 - Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs | 4 +- MediaBrowser.Api/ApiEntryPoint.cs | 36 +++++++------- .../LiveTv/ProgressiveFileCopier.cs | 2 +- .../Playback/BaseStreamingService.cs | 13 ++--- .../Playback/Hls/BaseHlsService.cs | 7 +-- .../Playback/Hls/DynamicHlsService.cs | 19 ++++---- MediaBrowser.Api/Playback/MediaInfoService.cs | 7 +-- .../BaseProgressiveStreamingService.cs | 2 + .../Progressive/ProgressiveStreamWriter.cs | 7 ++- MediaBrowser.Api/Playback/StreamState.cs | 8 ++-- .../Playback/TranscodingThrottler.cs | 22 ++++----- .../MediaEncoding/EncodingJobInfo.cs | 2 +- .../MediaEncoding/JobLogger.cs | 2 +- .../Encoder/AudioEncoder.cs | 2 +- .../Encoder/BaseEncoder.cs | 16 +++---- .../Encoder/EncoderValidator.cs | 22 ++++----- .../Encoder/EncodingJob.cs | 6 +-- .../Encoder/EncodingJobFactory.cs | 2 +- .../Encoder/FontConfigLoader.cs | 14 +++--- .../Encoder/MediaEncoder.cs | 38 +++++++-------- .../Encoder/VideoEncoder.cs | 4 +- .../Probing/ProbeResultNormalizer.cs | 6 +-- .../Subtitles/OpenSubtitleDownloader.cs | 18 +++---- .../Subtitles/SrtParser.cs | 4 +- .../Subtitles/SubtitleEncoder.cs | 48 +++++++++---------- 27 files changed, 158 insertions(+), 156 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index ca8723dde6..037bdde771 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -180,7 +180,7 @@ namespace Emby.Server.Implementations.HttpServer if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase)) { // This info is useful sometimes but also clogs up the log - //_logger.Error("Received web socket message that is not a json structure: " + message); + //_lLogError("Received web socket message that is not a json structure: " + message); return; } diff --git a/Emby.Server.Implementations/SystemEvents.cs b/Emby.Server.Implementations/SystemEvents.cs index e529628332..f39d63002a 100644 --- a/Emby.Server.Implementations/SystemEvents.cs +++ b/Emby.Server.Implementations/SystemEvents.cs @@ -1,5 +1,4 @@ using System; -using MediaBrowser.Common.Events; using Microsoft.Extensions.Logging; using MediaBrowser.Model.System; diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs index 2817d9e8ce..bbcd1eed35 100644 --- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs +++ b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs @@ -87,7 +87,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(id)) { - //Logger.Error("No id found for channel row"); + //LLogError("No id found for channel row"); // Log.Error(" channel#{0} doesnt contain an id", iChannel); return null; } @@ -130,7 +130,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(result.DisplayName)) { - //Logger.Error("No display-name found for channel {0}", id); + //LLogError("No display-name found for channel {0}", id); return null; } diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 1e99b8c7a1..b51bdf6fd5 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -147,7 +147,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.ErrorException("Error deleting encoded media cache", ex); + Logger.LogError("Error deleting encoded media cache", ex); } } @@ -378,7 +378,7 @@ namespace MediaBrowser.Api public void OnTranscodeEndRequest(TranscodingJob job) { job.ActiveRequestCount--; - //Logger.Debug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount); + //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount); if (job.ActiveRequestCount <= 0) { PingTimer(job, false); @@ -391,7 +391,7 @@ namespace MediaBrowser.Api throw new ArgumentNullException("playSessionId"); } - //Logger.Debug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused); + //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused); List jobs; @@ -406,7 +406,7 @@ namespace MediaBrowser.Api { if (isUserPaused.HasValue) { - //Logger.Debug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id); + //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id); job.IsUserPaused = isUserPaused.Value; } PingTimer(job, true); @@ -461,7 +461,7 @@ namespace MediaBrowser.Api } } - Logger.Info("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); + Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); KillTranscodingJob(job, true, path => true); } @@ -525,7 +525,7 @@ namespace MediaBrowser.Api { job.DisposeKillTimer(); - Logger.Debug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); + Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); lock (_activeTranscodingJobs) { @@ -557,7 +557,7 @@ namespace MediaBrowser.Api { try { - Logger.Info("Stopping ffmpeg process with q command for {0}", job.Path); + Logger.LogInformation("Stopping ffmpeg process with q command for {0}", job.Path); //process.Kill(); process.StandardInput.WriteLine("q"); @@ -565,13 +565,13 @@ namespace MediaBrowser.Api // Need to wait because killing is asynchronous if (!process.WaitForExit(5000)) { - Logger.Info("Killing ffmpeg process for {0}", job.Path); + Logger.LogInformation("Killing ffmpeg process for {0}", job.Path); process.Kill(); } } catch (Exception ex) { - Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path); + Logger.LogError("Error killing transcoding job for {0}", ex, job.Path); } } } @@ -589,7 +589,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.ErrorException("Error closing live stream for {0}", ex, job.Path); + Logger.LogError("Error closing live stream for {0}", ex, job.Path); } } } @@ -601,7 +601,7 @@ namespace MediaBrowser.Api return; } - Logger.Info("Deleting partial stream file(s) {0}", path); + Logger.LogInformation("Deleting partial stream file(s) {0}", path); await Task.Delay(delayMs).ConfigureAwait(false); @@ -622,13 +622,13 @@ namespace MediaBrowser.Api } catch (IOException) { - //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + //Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); DeletePartialStreamFiles(path, jobType, retryCount + 1, 500); } catch { - //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + //Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); } } @@ -660,7 +660,7 @@ namespace MediaBrowser.Api { try { - //Logger.Debug("Deleting HLS file {0}", file); + //Logger.LogDebug("Deleting HLS file {0}", file); _fileSystem.DeleteFile(file); } catch (FileNotFoundException) @@ -670,7 +670,7 @@ namespace MediaBrowser.Api catch (IOException ex) { e = ex; - //Logger.ErrorException("Error deleting HLS file {0}", ex, file); + //Logger.LogError("Error deleting HLS file {0}", ex, file); } } @@ -802,12 +802,12 @@ namespace MediaBrowser.Api { if (KillTimer == null) { - //Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer = _timerFactory.Create(callback, this, intervalMs, Timeout.Infinite); } else { - //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer.Change(intervalMs, Timeout.Infinite); } } @@ -826,7 +826,7 @@ namespace MediaBrowser.Api { var intervalMs = PingTimeout; - //Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); + //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId); KillTimer.Change(intervalMs, Timeout.Infinite); } } diff --git a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs index bf8aba8dfe..07ac7f28d8 100644 --- a/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs +++ b/MediaBrowser.Api/LiveTv/ProgressiveFileCopier.cs @@ -5,10 +5,10 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; using MediaBrowser.Controller.IO; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.LiveTv { diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 9c2e0e9d8f..37cc8d2d76 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -24,6 +24,7 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Diagnostics; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -248,7 +249,7 @@ namespace MediaBrowser.Api.Playback cancellationTokenSource); var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - Logger.Info(commandLineLogMessage); + Logger.LogInformation(commandLineLogMessage); var logFilePrefix = "ffmpeg-transcode"; if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase)) @@ -277,7 +278,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - Logger.ErrorException("Error starting ffmpeg", ex); + Logger.LogError("Error starting ffmpeg", ex); ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state); @@ -351,16 +352,16 @@ namespace MediaBrowser.Api.Playback job.HasExited = true; } - Logger.Debug("Disposing stream resources"); + Logger.LogDebug("Disposing stream resources"); state.Dispose(); try { - Logger.Info("FFMpeg exited with code {0}", process.ExitCode); + Logger.LogInformation("FFMpeg exited with code {0}", process.ExitCode); } catch { - Logger.Error("FFMpeg exited with an error."); + Logger.LogError("FFMpeg exited with an error."); } // This causes on exited to be called twice: @@ -371,7 +372,7 @@ namespace MediaBrowser.Api.Playback //} //catch (Exception ex) //{ - // Logger.ErrorException("Error disposing ffmpeg.", ex); + // Logger.LogError("Error disposing ffmpeg.", ex); //} } diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index a0f4a2e715..7ef7b81e63 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -15,6 +15,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Configuration; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Hls { @@ -185,7 +186,7 @@ namespace MediaBrowser.Api.Playback.Hls protected virtual async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken) { - Logger.Debug("Waiting for {0} segments in {1}", segmentCount, playlist); + Logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist); while (!cancellationToken.IsCancellationRequested) { @@ -207,7 +208,7 @@ namespace MediaBrowser.Api.Playback.Hls count++; if (count >= segmentCount) { - Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist); + Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist); return; } } @@ -330,4 +331,4 @@ namespace MediaBrowser.Api.Playback.Hls { } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 0525c8cc48..7dda91e5a9 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -21,6 +21,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Services; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Hls { @@ -190,17 +191,17 @@ namespace MediaBrowser.Api.Playback.Hls if (currentTranscodingIndex == null) { - Logger.Debug("Starting transcoding because currentTranscodingIndex=null"); + Logger.LogDebug("Starting transcoding because currentTranscodingIndex=null"); startTranscoding = true; } else if (requestedIndex < currentTranscodingIndex.Value) { - Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex); + Logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex); startTranscoding = true; } else if (requestedIndex - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange) { - Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex); + Logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", requestedIndex - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, requestedIndex); startTranscoding = true; } if (startTranscoding) @@ -245,13 +246,13 @@ namespace MediaBrowser.Api.Playback.Hls } } - //Logger.Info("waiting for {0}", segmentPath); + //Logger.LogInformation("waiting for {0}", segmentPath); //while (!File.Exists(segmentPath)) //{ // await Task.Delay(50, cancellationToken).ConfigureAwait(false); //} - Logger.Info("returning {0}", segmentPath); + Logger.LogInformation("returning {0}", segmentPath); job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } @@ -358,7 +359,7 @@ namespace MediaBrowser.Api.Playback.Hls return; } - Logger.Debug("Deleting partial HLS file {0}", path); + Logger.LogDebug("Deleting partial HLS file {path}", path); try { @@ -366,7 +367,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (IOException ex) { - Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); var task = Task.Delay(100); Task.WaitAll(task); @@ -374,7 +375,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (Exception ex) { - Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); } } @@ -968,4 +969,4 @@ namespace MediaBrowser.Api.Playback.Hls ).Trim(); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 2db0f8f419..6dafe134ce 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -18,6 +18,7 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -381,11 +382,11 @@ namespace MediaBrowser.Api.Playback if (item is Audio) { - Logger.Info("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding); + Logger.LogInformation("User policy for {0}. EnableAudioPlaybackTranscoding: {1}", user.Name, user.Policy.EnableAudioPlaybackTranscoding); } else { - Logger.Info("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}", + Logger.LogInformation("User policy for {0}. EnablePlaybackRemuxing: {1} EnableVideoPlaybackTranscoding: {2} EnableAudioPlaybackTranscoding: {3}", user.Name, user.Policy.EnablePlaybackRemuxing, user.Policy.EnableVideoPlaybackTranscoding, @@ -525,7 +526,7 @@ namespace MediaBrowser.Api.Playback { var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp); - Logger.Info("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork); + Logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork); if (!isInLocalNetwork) { maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate); diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index 44261f2d55..cc59b1049f 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -17,6 +17,8 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; +using MediaBrowser.Api.LiveTv; namespace MediaBrowser.Api.Playback.Progressive { diff --git a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs index 9839a7a9aa..ed2930b4d4 100644 --- a/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs +++ b/MediaBrowser.Api/Playback/Progressive/ProgressiveStreamWriter.cs @@ -1,16 +1,15 @@ -using MediaBrowser.Model.Logging; -using System; +using System; using System.IO; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; using MediaBrowser.Controller.Net; using System.Collections.Generic; - using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback.Progressive { @@ -110,7 +109,7 @@ namespace MediaBrowser.Api.Playback.Progressive } //var position = fs.Position; - //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); + //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path); if (bytesRead == 0) { diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs index db5d256c47..981a4725d1 100644 --- a/MediaBrowser.Api/Playback/StreamState.cs +++ b/MediaBrowser.Api/Playback/StreamState.cs @@ -4,7 +4,6 @@ using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using System; @@ -14,6 +13,7 @@ using System.IO; using System.Linq; using System.Threading; using MediaBrowser.Controller.MediaEncoding; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -162,7 +162,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error disposing log stream", ex); + _logger.LogError("Error disposing log stream", ex); } LogFileStream = null; @@ -179,7 +179,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error disposing TranscodingThrottler", ex); + _logger.LogError("Error disposing TranscodingThrottler", ex); } TranscodingThrottler = null; @@ -196,7 +196,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error closing media source", ex); + _logger.LogError("Error closing media source", ex); } } } diff --git a/MediaBrowser.Api/Playback/TranscodingThrottler.cs b/MediaBrowser.Api/Playback/TranscodingThrottler.cs index c42d0c3e4c..47f1f777af 100644 --- a/MediaBrowser.Api/Playback/TranscodingThrottler.cs +++ b/MediaBrowser.Api/Playback/TranscodingThrottler.cs @@ -1,9 +1,9 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Logging; using System; using MediaBrowser.Model.IO; using MediaBrowser.Model.Threading; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.Playback { @@ -60,7 +60,7 @@ namespace MediaBrowser.Api.Playback { if (!_isPaused) { - _logger.Debug("Sending pause command to ffmpeg"); + _logger.LogDebug("Sending pause command to ffmpeg"); try { @@ -69,7 +69,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error pausing transcoding", ex); + _logger.LogError("Error pausing transcoding", ex); } } } @@ -78,7 +78,7 @@ namespace MediaBrowser.Api.Playback { if (_isPaused) { - _logger.Debug("Sending unpause command to ffmpeg"); + _logger.LogDebug("Sending unpause command to ffmpeg"); try { @@ -87,7 +87,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.ErrorException("Error unpausing transcoding", ex); + _logger.LogError("Error unpausing transcoding", ex); } } } @@ -110,11 +110,11 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.Debug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); + //_logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); return false; } - //_logger.Debug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); + //_logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); return true; } @@ -135,21 +135,21 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.Debug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + //_logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return false; } - //_logger.Debug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + //_logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return true; } catch { - //_logger.Error("Error getting output size"); + //_logger.LogError("Error getting output size"); return false; } } - //_logger.Debug("No throttle data for " + path); + //_logger.LogDebug("No throttle data for " + path); return false; } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index e1762fbdad..3ec4e3bb7b 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -8,10 +8,10 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Session; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.MediaEncoding { diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index 539aab7b3a..8bb826bd1e 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -4,7 +4,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Text; -using Microsoft.Extension.Logging; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.MediaEncoding { diff --git a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs index 566e7946d3..2a874eba16 100644 --- a/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs @@ -3,7 +3,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using MediaBrowser.Model.Diagnostics; diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs index 3383276bcb..1fd34c8fdf 100644 --- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs @@ -7,7 +7,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; @@ -105,7 +105,7 @@ namespace MediaBrowser.MediaEncoding.Encoder OnTranscodeBeginning(encodingJob); var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; - Logger.Info(commandLineLogMessage); + Logger.LogInformation(commandLineLogMessage); var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt"); FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath)); @@ -124,7 +124,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - Logger.ErrorException("Error starting ffmpeg", ex); + Logger.LogError("Error starting ffmpeg", ex); OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob); @@ -150,7 +150,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private void Cancel(IProcess process, EncodingJob job) { - Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath); + Logger.LogInformation("Killing ffmpeg process for {0}", job.OutputFilePath); //process.Kill(); process.StandardInput.WriteLine("q"); @@ -167,7 +167,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { job.HasExited = true; - Logger.Debug("Disposing stream resources"); + Logger.LogDebug("Disposing stream resources"); job.Dispose(); var isSuccesful = false; @@ -175,13 +175,13 @@ namespace MediaBrowser.MediaEncoding.Encoder try { var exitCode = process.ExitCode; - Logger.Info("FFMpeg exited with code {0}", exitCode); + Logger.LogInformation("FFMpeg exited with code {0}", exitCode); isSuccesful = exitCode == 0; } catch { - Logger.Error("FFMpeg exited with an error."); + Logger.LogError("FFMpeg exited with an error."); } if (isSuccesful && !job.IsCancelled) @@ -231,7 +231,7 @@ namespace MediaBrowser.MediaEncoding.Encoder //} //catch (Exception ex) //{ - // Logger.ErrorException("Error disposing ffmpeg.", ex); + // Logger.LogError("Error disposing ffmpeg.", ex); //} } diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 59f3576ec8..9653e561c0 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using MediaBrowser.Model.Diagnostics; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -20,12 +20,12 @@ namespace MediaBrowser.MediaEncoding.Encoder public Tuple, List> Validate(string encoderPath) { - _logger.Info("Validating media encoder at {0}", encoderPath); + _logger.LogInformation("Validating media encoder at {0}", encoderPath); var decoders = GetDecoders(encoderPath); var encoders = GetEncoders(encoderPath); - _logger.Info("Encoder validation complete"); + _logger.LogInformation("Encoder validation complete"); return new Tuple, List>(decoders, encoders); } @@ -41,7 +41,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (logOutput) { - _logger.ErrorException("Error validating encoder", ex); + _logger.LogError("Error validating encoder", ex); } } @@ -50,7 +50,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return false; } - _logger.Info("ffmpeg info: {0}", output); + _logger.LogInformation("ffmpeg info: {0}", output); if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1) { @@ -80,7 +80,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ) { - //_logger.ErrorException("Error detecting available decoders", ex); + //_logger.LogError("Error detecting available decoders", ex); } var found = new List(); @@ -107,7 +107,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) { - _logger.Info("Decoder available: " + codec); + _logger.LogInformation("Decoder available: " + codec); found.Add(codec); } } @@ -163,7 +163,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (index < required.Length - 1) { - _logger.Info("Encoder available: " + codec); + _logger.LogInformation("Encoder available: " + codec); } found.Add(codec); @@ -187,7 +187,7 @@ namespace MediaBrowser.MediaEncoding.Encoder RedirectStandardOutput = true }); - _logger.Info("Running {0} {1}", path, arguments); + _logger.LogInformation("Running {0} {1}", path, arguments); using (process) { @@ -199,7 +199,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - _logger.Info("Killing process {0} {1}", path, arguments); + _logger.LogInformation("Killing process {0} {1}", path, arguments); // Hate having to do this try @@ -208,7 +208,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex1) { - _logger.ErrorException("Error killing process", ex1); + _logger.LogError("Error killing process", ex1); } throw; diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs index 294181fccc..dcaf4a2b17 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs @@ -5,7 +5,6 @@ using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using System; @@ -14,6 +13,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -81,7 +81,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error disposing log stream", ex); + _logger.LogError("Error disposing log stream", ex); } LogFileStream = null; @@ -98,7 +98,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error closing media source", ex); + _logger.LogError("Error closing media source", ex); } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs index 8d8d05a16e..4e6ee89e1b 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs @@ -5,7 +5,7 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs index e21292cbd7..2f0161962e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs +++ b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs @@ -10,7 +10,7 @@ using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; namespace MediaBrowser.MediaEncoding.Encoder @@ -72,12 +72,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (HttpException ex) { // Don't let the server crash because of this - _logger.ErrorException("Error downloading ffmpeg font files", ex); + _logger.LogError("Error downloading ffmpeg font files", ex); } catch (Exception ex) { // Don't let the server crash because of this - _logger.ErrorException("Error writing ffmpeg font files", ex); + _logger.LogError("Error writing ffmpeg font files", ex); } } @@ -103,7 +103,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.ErrorException("Error copying file", ex); + _logger.LogError("Error copying file", ex); } } @@ -127,7 +127,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { // The core can function without the font file, so handle this - _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url); + _logger.LogError("Failed to download ffmpeg font file from {0}", ex, url); } } @@ -145,12 +145,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.ErrorException("Error deleting temp file {0}", ex, tempFile); + _logger.LogError("Error deleting temp file {0}", ex, tempFile); } } private void Extract7zArchive(string archivePath, string targetPath) { - _logger.Info("Extracting {0} to {1}", archivePath, targetPath); + _logger.LogInformation("Extracting {0} to {1}", archivePath, targetPath); _zipClient.ExtractAllFrom7z(archivePath, targetPath, true); } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 64372c0727..4cd66e5ced 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -9,7 +9,6 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -25,6 +24,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { @@ -117,7 +117,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); + _logger.LogError("Error setting FFREPORT environment variable", ex); } } } @@ -132,7 +132,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - //_logger.ErrorException("Error setting FFREPORT environment variable", ex); + //_logger.LogError("Error setting FFREPORT environment variable", ex); } } } @@ -145,7 +145,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); + _logger.LogError("Error setting FFREPORT environment variable", ex); } try { @@ -153,7 +153,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.ErrorException("Error setting FFREPORT environment variable", ex); + _logger.LogError("Error setting FFREPORT environment variable", ex); } } @@ -252,7 +252,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return; } - _logger.Info("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty); + _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty); Tuple newPaths; @@ -414,8 +414,8 @@ namespace MediaBrowser.MediaEncoding.Encoder private void LogPaths() { - _logger.Info("FFMpeg: {0}", FFMpegPath ?? "not found"); - _logger.Info("FFProbe: {0}", FFProbePath ?? "not found"); + _logger.LogInformation("FFMpeg: {0}", FFMpegPath ?? "not found"); + _logger.LogInformation("FFProbe: {0}", FFProbePath ?? "not found"); } private EncodingOptions GetEncodingOptions() @@ -557,11 +557,11 @@ namespace MediaBrowser.MediaEncoding.Encoder if (forceEnableLogging) { - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); } else { - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); } using (var processWrapper = new ProcessWrapper(process, this, _logger)) @@ -651,7 +651,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); + _logger.LogError("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); } } @@ -755,7 +755,7 @@ namespace MediaBrowser.MediaEncoding.Encoder ErrorDialog = false }); - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); using (var processWrapper = new ProcessWrapper(process, this, _logger)) { @@ -783,7 +783,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -877,7 +877,7 @@ namespace MediaBrowser.MediaEncoding.Encoder ErrorDialog = false }); - _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments); + _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments); await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -929,7 +929,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -961,7 +961,7 @@ namespace MediaBrowser.MediaEncoding.Encoder IProgress progress, CancellationToken cancellationToken) { - _logger.Error("EncodeVideo"); + _logger.LogError("EncodeVideo"); var job = await new VideoEncoder(this, _logger, ConfigurationManager, @@ -999,18 +999,18 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.Error("Error in WaitForExit", ex); + _logger.LogError("Error in WaitForExit", ex); } try { - _logger.Info("Killing ffmpeg process"); + _logger.LogInformation("Killing ffmpeg process"); process.Process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing process", ex); + _logger.LogError("Error killing process", ex); } } diff --git a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs index 96c1269236..732b5bf846 100644 --- a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs @@ -4,7 +4,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.IO; using System.Threading.Tasks; @@ -63,4 +63,4 @@ namespace MediaBrowser.MediaEncoding.Encoder } } -} \ No newline at end of file +} diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 0a3532b8cf..c3cf61dc1e 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -13,7 +13,7 @@ using MediaBrowser.Model.IO; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.MediaEncoding.Probing @@ -1351,11 +1351,11 @@ namespace MediaBrowser.MediaEncoding.Probing { video.Timestamp = GetMpegTimestamp(video.Path); - _logger.Debug("Video has {0} timestamp", video.Timestamp); + _logger.LogDebug("Video has {0} timestamp", video.Timestamp); } catch (Exception ex) { - _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path); + _logger.LogError("Error extracting timestamp info from {0}", ex, video.Path); video.Timestamp = null; } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs index 3954897cac..2d29f29e3d 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs @@ -15,9 +15,9 @@ using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; using OpenSubtitlesHandler; namespace MediaBrowser.MediaEncoding.Subtitles @@ -34,9 +34,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles private readonly IJsonSerializer _json; private readonly IFileSystem _fileSystem; - public OpenSubtitleDownloader(ILogManager logManager, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem) + public OpenSubtitleDownloader(ILoggerFactory loggerFactory, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem) { - _logger = logManager.GetLogger(GetType().Name); + _logger = loggerFactory.CreateLogger(GetType().Name); _httpClient = httpClient; _config = config; _encryption = encryption; @@ -208,7 +208,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var result = OpenSubtitles.GetSubLanguages("en"); if (!(result is MethodResponseGetSubLanguages)) { - _logger.Error("Invalid response type"); + _logger.LogError("Invalid response type"); return new List(); } @@ -243,19 +243,19 @@ namespace MediaBrowser.MediaEncoding.Subtitles case VideoContentType.Episode: if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName)) { - _logger.Debug("Episode information missing"); + _logger.LogDebug("Episode information missing"); return new List(); } break; case VideoContentType.Movie: if (string.IsNullOrEmpty(request.Name)) { - _logger.Debug("Movie name missing"); + _logger.LogDebug("Movie name missing"); return new List(); } if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId)) { - _logger.Debug("Imdb id missing"); + _logger.LogDebug("Imdb id missing"); return new List(); } break; @@ -263,7 +263,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (string.IsNullOrEmpty(request.MediaPath)) { - _logger.Debug("Path Missing"); + _logger.LogDebug("Path Missing"); return new List(); } @@ -300,7 +300,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false); if (!(result is MethodResponseSubtitleSearch)) { - _logger.Error("Invalid response type"); + _logger.LogError("Invalid response type"); return new List(); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index de6d7bc725..7ca8aa1fd8 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -1,5 +1,5 @@ using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; @@ -50,7 +50,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { // This occurs when subtitle text has an empty line as part of the text. // Need to adjust the break statement below to resolve this. - _logger.Warn("Unrecognized line in srt: {0}", line); + _logger.LogWarning("Unrecognized line in srt: {0}", line); continue; } subEvent.StartPositionTicks = GetTicks(time[0]); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index d565ff3e20..a3e0f89a97 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Serialization; using System; @@ -190,7 +190,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false); var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true); - _logger.Debug("charset {0} detected for {1}", charset ?? "null", path); + _logger.LogDebug("charset {0} detected for {1}", charset ?? "null", path); if (!string.IsNullOrEmpty(charset)) { @@ -423,7 +423,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }); - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); try { @@ -431,7 +431,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error starting ffmpeg", ex); + _logger.LogError("Error starting ffmpeg", ex); throw; } @@ -442,13 +442,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Killing ffmpeg subtitle conversion process"); + _logger.LogInformation("Killing ffmpeg subtitle conversion process"); process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing subtitle conversion process", ex); + _logger.LogError("Error killing subtitle conversion process", ex); } } @@ -466,12 +466,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Deleting converted subtitle due to failure: ", outputPath); + _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath); _fileSystem.DeleteFile(outputPath); } catch (IOException ex) { - _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath); + _logger.LogError("Error deleting converted subtitle {0}", ex, outputPath); } } } @@ -484,13 +484,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } await SetAssFont(outputPath).ConfigureAwait(false); - _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath); + _logger.LogInformation("ffmpeg subtitle conversion succeeded for {0}", inputPath); } /// @@ -553,7 +553,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles ErrorDialog = false }); - _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); try { @@ -561,7 +561,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.ErrorException("Error starting ffmpeg", ex); + _logger.LogError("Error starting ffmpeg", ex); throw; } @@ -572,13 +572,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles { try { - _logger.Info("Killing ffmpeg subtitle extraction process"); + _logger.LogInformation("Killing ffmpeg subtitle extraction process"); process.Kill(); } catch (Exception ex) { - _logger.ErrorException("Error killing subtitle extraction process", ex); + _logger.LogError("Error killing subtitle extraction process", ex); } } @@ -594,7 +594,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - _logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath); + _logger.LogInformation("Deleting extracted subtitle due to failure: {0}", outputPath); _fileSystem.DeleteFile(outputPath); } catch (FileNotFoundException) @@ -603,7 +603,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (IOException ex) { - _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath); + _logger.LogError("Error deleting extracted subtitle {0}", ex, outputPath); } } else if (!_fileSystem.FileExists(outputPath)) @@ -615,7 +615,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath); - _logger.Error(msg); + _logger.LogError(msg); throw new Exception(msg); } @@ -623,7 +623,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath); - _logger.Info(msg); + _logger.LogInformation(msg); } if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase)) @@ -639,7 +639,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Task. private async Task SetAssFont(string file) { - _logger.Info("Setting ass font within {0}", file); + _logger.LogInformation("Setting ass font within {0}", file); string text; Encoding encoding; @@ -659,11 +659,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!string.Equals(text, newText)) { using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) + using (var writer = new StreamWriter(fileStream, encoding)) { - using (var writer = new StreamWriter(fileStream, encoding)) - { - writer.Write(newText); - } + writer.Write(newText); } } } @@ -698,7 +696,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true); - _logger.Debug("charset {0} detected for {1}", charset ?? "null", path); + _logger.LogDebug("charset {0} detected for {1}", charset ?? "null", path); return charset; } @@ -730,4 +728,4 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } -} \ No newline at end of file +} From bf01918659986cc6cbaefaebb67f607aeb1b4400 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 20 Dec 2018 11:38:42 +0100 Subject: [PATCH 020/125] Clean up --- Emby.IsoMounting/IsoMounter/LinuxMount.cs | 2 - .../LiveTv/LiveTvManager.cs | 6 +-- MediaBrowser.Api/LiveTv/LiveTvService.cs | 1 - .../UserLibrary/PlaystateService.cs | 4 +- MediaBrowser.Controller/Entities/Folder.cs | 42 ++++++++----------- 5 files changed, 20 insertions(+), 35 deletions(-) diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs index a08a123921..edd26f08d4 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxMount.cs @@ -1,7 +1,5 @@ using System; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.System; namespace IsoMounter { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index d74636e8de..679f8668b4 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Common; -using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Configuration; @@ -18,9 +17,7 @@ using Microsoft.Extensions.Logging; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -29,7 +26,6 @@ using MediaBrowser.Common.Events; using MediaBrowser.Common.Security; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index 06c0c6862c..ef9ce9aec7 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -17,7 +17,6 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Api.UserLibrary; using MediaBrowser.Model.IO; -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Model.Services; diff --git a/MediaBrowser.Api/UserLibrary/PlaystateService.cs b/MediaBrowser.Api/UserLibrary/PlaystateService.cs index 2c514a1097..9b269542a8 100644 --- a/MediaBrowser.Api/UserLibrary/PlaystateService.cs +++ b/MediaBrowser.Api/UserLibrary/PlaystateService.cs @@ -6,9 +6,9 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Session; using System; using System.Globalization; -using System.Linq; using System.Threading.Tasks; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.UserLibrary { @@ -381,7 +381,7 @@ namespace MediaBrowser.Api.UserLibrary public void Post(ReportPlaybackStopped request) { - Logger.Debug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty); + Logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", request.PlaySessionId ?? string.Empty); if (!string.IsNullOrWhiteSpace(request.PlaySessionId)) { diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 3d830cbe62..e9352ce400 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -371,6 +371,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { + Logger.LogError(ex, "Error retrieving children folder"); return; } @@ -419,11 +420,7 @@ namespace MediaBrowser.Controller.Entities foreach (var item in itemsRemoved) { - if (!item.IsFileProtocol) - { - } - - else + if (item.IsFileProtocol) { Logger.LogDebug("Removed item: " + item.Path); @@ -571,14 +568,9 @@ namespace MediaBrowser.Controller.Entities await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); } - if (recursive) + if (recursive && child is Folder folder) { - var folder = child as Folder; - - if (folder != null) - { - await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken); - } + await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken); } } } @@ -782,7 +774,7 @@ namespace MediaBrowser.Controller.Entities { if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase)) { - Logger.Debug("Query requires post-filtering due to BoxSet query"); + Logger.LogDebug("Query requires post-filtering due to BoxSet query"); return true; } @@ -803,44 +795,44 @@ namespace MediaBrowser.Controller.Entities // Filter by Video3DFormat if (query.Is3D.HasValue) { - Logger.Debug("Query requires post-filtering due to Is3D"); + Logger.LogDebug("Query requires post-filtering due to Is3D"); return true; } if (query.HasOfficialRating.HasValue) { - Logger.Debug("Query requires post-filtering due to HasOfficialRating"); + Logger.LogDebug("Query requires post-filtering due to HasOfficialRating"); return true; } if (query.IsPlaceHolder.HasValue) { - Logger.Debug("Query requires post-filtering due to IsPlaceHolder"); + Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder"); return true; } if (query.HasSpecialFeature.HasValue) { - Logger.Debug("Query requires post-filtering due to HasSpecialFeature"); + Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature"); return true; } if (query.HasSubtitles.HasValue) { - Logger.Debug("Query requires post-filtering due to HasSubtitles"); + Logger.LogDebug("Query requires post-filtering due to HasSubtitles"); return true; } if (query.HasTrailer.HasValue) { - Logger.Debug("Query requires post-filtering due to HasTrailer"); + Logger.LogDebug("Query requires post-filtering due to HasTrailer"); return true; } // Filter by VideoType if (query.VideoTypes.Length > 0) { - Logger.Debug("Query requires post-filtering due to VideoTypes"); + Logger.LogDebug("Query requires post-filtering due to VideoTypes"); return true; } @@ -852,19 +844,19 @@ namespace MediaBrowser.Controller.Entities if (!string.IsNullOrEmpty(query.AdjacentTo)) { - Logger.Debug("Query requires post-filtering due to AdjacentTo"); + Logger.LogDebug("Query requires post-filtering due to AdjacentTo"); return true; } if (query.SeriesStatuses.Length > 0) { - Logger.Debug("Query requires post-filtering due to SeriesStatuses"); + Logger.LogDebug("Query requires post-filtering due to SeriesStatuses"); return true; } if (query.AiredDuringSeason.HasValue) { - Logger.Debug("Query requires post-filtering due to AiredDuringSeason"); + Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason"); return true; } @@ -872,7 +864,7 @@ namespace MediaBrowser.Controller.Entities { if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name)) { - Logger.Debug("Query requires post-filtering due to IsPlayed"); + Logger.LogDebug("Query requires post-filtering due to IsPlayed"); return true; } } @@ -1594,7 +1586,7 @@ namespace MediaBrowser.Controller.Entities } catch (IOException ex) { - Logger.LogError("Error resolving shortcut {0}", ex, i.FullName); + Logger.LogError(ex, "Error resolving shortcut {0}", i.FullName); return null; } }) From ea4c914123ba8279b9d9fcf7d5318e11f7a3da4c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 20 Dec 2018 13:11:26 +0100 Subject: [PATCH 021/125] Fix exception logging --- Emby.Dlna/Didl/DidlBuilder.cs | 8 +- Emby.Dlna/DlnaManager.cs | 6 +- Emby.Dlna/Main/DlnaEntryPoint.cs | 12 +- Emby.Dlna/PlayTo/Device.cs | 6 +- Emby.Dlna/PlayTo/PlayToController.cs | 10 +- Emby.Dlna/PlayTo/PlayToManager.cs | 2 +- Emby.Dlna/Service/BaseControlHandler.cs | 2 +- .../ImageMagickEncoder.cs | 4 +- Emby.Drawing.Net/GDIImageEncoder.cs | 2 +- Emby.Drawing.Skia/SkiaEncoder.cs | 2 +- Emby.Drawing/ImageProcessor.cs | 10 +- Emby.Notifications/NotificationManager.cs | 6 +- Emby.Notifications/Notifications.cs | 2 +- Emby.Photos/PhotoProvider.cs | 4 +- .../Activity/ActivityRepository.cs | 234 +++++++++--------- .../AppBase/BaseConfigurationManager.cs | 2 +- .../ApplicationHost.cs | 58 ++--- .../Channels/ChannelManager.cs | 6 +- .../Collections/CollectionManager.cs | 2 +- .../Data/BaseSqliteRepository.cs | 2 +- .../SqliteDisplayPreferencesRepository.cs | 2 +- .../Data/SqliteItemRepository.cs | 2 +- .../Data/SqliteUserRepository.cs | 2 +- .../Devices/DeviceId.cs | 4 +- .../Devices/DeviceManager.cs | 2 +- Emby.Server.Implementations/Dto/DtoService.cs | 12 +- .../EntryPoints/AutomaticRestartEntryPoint.cs | 4 +- .../EntryPoints/ExternalPortForwarding.cs | 6 +- .../EntryPoints/KeepServerAwake.cs | 2 +- .../EntryPoints/LibraryChangedNotifier.cs | 4 +- .../EntryPoints/RecordingNotifier.cs | 2 +- .../EntryPoints/ServerEventNotifier.cs | 12 +- .../EntryPoints/UdpServerEntryPoint.cs | 2 +- .../EntryPoints/UsageEntryPoint.cs | 4 +- .../HttpClientManager/HttpClientManager.cs | 4 +- .../HttpServer/HttpListenerHost.cs | 14 +- .../HttpServer/ResponseFilter.cs | 2 +- .../HttpServer/WebSocketConnection.cs | 4 +- .../IO/FileRefresher.cs | 8 +- .../IO/LibraryMonitor.cs | 16 +- .../IO/ManagedFileSystem.cs | 6 +- .../Library/LibraryManager.cs | 33 ++- .../Library/MediaSourceManager.cs | 4 +- .../Library/UserManager.cs | 14 +- .../Library/Validators/ArtistsValidator.cs | 2 +- .../Library/Validators/GameGenresValidator.cs | 2 +- .../Library/Validators/GenresValidator.cs | 2 +- .../Validators/MusicGenresValidator.cs | 2 +- .../Library/Validators/PeopleValidator.cs | 2 +- .../Library/Validators/StudiosValidator.cs | 2 +- .../LiveTv/EmbyTV/EmbyTV.cs | 52 ++-- .../LiveTv/EmbyTV/EncodedRecorder.cs | 24 +- .../LiveTv/EmbyTV/ItemDataProvider.cs | 2 +- .../LiveTv/EmbyTV/TimerManager.cs | 6 +- .../LiveTv/Listings/SchedulesDirect.cs | 34 ++- .../LiveTv/LiveTvDtoService.cs | 9 +- .../LiveTv/LiveTvManager.cs | 16 +- .../LiveTv/TunerHosts/BaseTunerHost.cs | 8 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- .../HdHomerun/HdHomerunUdpStream.cs | 86 +++---- .../LiveTv/TunerHosts/LiveStream.cs | 6 +- .../LiveTv/TunerHosts/SharedHttpStream.cs | 2 +- .../MediaEncoder/EncodingManager.cs | 6 +- .../Networking/NetworkManager.cs | 10 +- .../News/NewsEntryPoint.cs | 2 +- .../ResourceFileManager.cs | 2 +- .../ScheduledTasks/PluginUpdateTask.cs | 4 +- .../ScheduledTasks/ScheduledTaskWorker.cs | 10 +- .../Tasks/DeleteCacheFileTask.cs | 8 +- .../Security/AuthenticationRepository.cs | 2 +- .../Security/PluginSecurityManager.cs | 11 +- Emby.Server.Implementations/Udp/UdpServer.cs | 12 +- .../Updates/InstallationManager.cs | 10 +- Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs | 4 +- MediaBrowser.Api/ApiEntryPoint.cs | 20 +- MediaBrowser.Api/Images/ImageService.cs | 2 +- MediaBrowser.Api/Library/LibraryService.cs | 2 +- .../Playback/BaseStreamingService.cs | 4 +- .../Playback/Hls/DynamicHlsService.cs | 4 +- MediaBrowser.Api/Playback/StreamState.cs | 6 +- .../Playback/TranscodingThrottler.cs | 20 +- MediaBrowser.Api/PluginService.cs | 6 +- MediaBrowser.Api/Subtitles/SubtitleService.cs | 2 +- MediaBrowser.Common/Events/EventHelper.cs | 8 +- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- .../Entities/CollectionFolder.cs | 2 +- MediaBrowser.Controller/Entities/Folder.cs | 2 +- .../Entities/UserViewBuilder.cs | 10 +- MediaBrowser.Controller/IO/FileData.cs | 2 +- .../MediaEncoding/EncodingJobInfo.cs | 1 - .../Net/BasePeriodicWebSocketListener.cs | 2 +- .../Session/SessionInfo.cs | 4 +- .../Savers/BaseXmlSaver.cs | 2 +- .../Encoder/BaseEncoder.cs | 6 +- .../Encoder/EncoderValidator.cs | 14 +- .../Encoder/EncodingJob.cs | 4 +- .../Encoder/FontConfigLoader.cs | 12 +- .../Encoder/MediaEncoder.cs | 34 +-- .../Probing/ProbeResultNormalizer.cs | 4 +- .../Subtitles/SubtitleEncoder.cs | 12 +- MediaBrowser.Providers/Manager/ImageSaver.cs | 4 +- .../Manager/ItemImageProvider.cs | 8 +- .../Manager/MetadataService.cs | 14 +- .../Manager/ProviderManager.cs | 20 +- .../MediaInfo/FFProbeVideoInfo.cs | 2 +- .../MediaInfo/SubtitleDownloader.cs | 2 +- .../MediaInfo/SubtitleScheduledTask.cs | 2 +- .../Music/MusicBrainzAlbumProvider.cs | 2 +- .../Subtitles/SubtitleManager.cs | 4 +- .../TV/SeriesMetadataService.cs | 2 +- .../TV/TheMovieDb/MovieDbSeasonProvider.cs | 2 +- .../TV/TheTVDB/TvdbPrescanTask.cs | 2 +- MediaBrowser.Server.Mono/Program.cs | 2 +- .../SocketSharp/WebSocketSharpListener.cs | 6 +- .../SocketSharp/WebSocketSharpResponse.cs | 2 +- .../Api/DashboardService.cs | 2 +- MediaBrowser.XbmcMetadata/EntryPoint.cs | 2 +- .../Parsers/MovieNfoParser.cs | 2 +- .../Savers/BaseNfoSaver.cs | 6 +- Mono.Nat/Pmp/PmpNatDevice.cs | 2 +- Mono.Nat/Upnp/Searchers/UpnpSearcher.cs | 2 +- RSSDP/SsdpCommunicationsServer.cs | 6 +- .../Net/HttpEndPointListener.cs | 4 +- 123 files changed, 565 insertions(+), 607 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 2cde379eaa..6de35b8426 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -913,9 +913,9 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); } - catch (XmlException) + catch (XmlException ex) { - _logger.LogError("Error adding xml value: {value}", name); + _logger.LogError(ex, "Error adding xml value: {value}", name); } } @@ -925,9 +925,9 @@ namespace Emby.Dlna.Didl { writer.WriteElementString(prefix, name, namespaceUri, value); } - catch (XmlException) + catch (XmlException ex) { - _logger.LogError("Error adding xml value: {value}", value); + _logger.LogError(ex, "Error adding xml value: {value}", value); } } diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 4c5bde6cd4..eae4f32716 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -58,7 +58,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.LogError("Error extracting DLNA profiles.", ex); + _logger.LogError(ex, "Error extracting DLNA profiles."); } } @@ -198,7 +198,7 @@ namespace Emby.Dlna } catch (ArgumentException ex) { - _logger.LogError("Error evaluating regex pattern {0}", ex, pattern); + _logger.LogError(ex, "Error evaluating regex pattern {0}", pattern); return false; } } @@ -324,7 +324,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.LogError("Error parsing profile file: {0}", ex, path); + _logger.LogError(ex, "Error parsing profile file: {0}", path); return null; } diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 4697287e9b..6ab0767a5a 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -185,7 +185,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error starting ssdp handlers", ex); + _logger.LogError(ex, "Error starting ssdp handlers"); } } @@ -202,7 +202,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error starting device discovery", ex); + _logger.LogError(ex, "Error starting device discovery"); } } @@ -215,7 +215,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error stopping device discovery", ex); + _logger.LogError(ex, "Error stopping device discovery"); } } @@ -243,7 +243,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error registering endpoint", ex); + _logger.LogError(ex, "Error registering endpoint"); } } @@ -361,7 +361,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error starting PlayTo manager", ex); + _logger.LogError(ex, "Error starting PlayTo manager"); } } } @@ -379,7 +379,7 @@ namespace Emby.Dlna.Main } catch (Exception ex) { - _logger.LogError("Error disposing PlayTo manager", ex); + _logger.LogError(ex, "Error disposing PlayTo manager"); } _manager = null; } diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 1cbb69d1da..a1df90ec03 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -140,7 +140,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error updating device volume info for {0}", ex, Properties.Name); + _logger.LogError(ex, "Error updating device volume info for {0}", Properties.Name); } } @@ -507,7 +507,7 @@ namespace Emby.Dlna.PlayTo if (_disposed) return; - //_logger.LogError("Error updating device info for {0}", ex, Properties.Name); + //_logger.LogError(ex, "Error updating device info for {0}", Properties.Name); _connectFailureCount++; @@ -767,7 +767,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Unable to parse xml {0}", ex, trackString); + _logger.LogError(ex, "Unable to parse xml {0}", trackString); return new Tuple(true, null); } } diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index e722f83d81..c51f220ef5 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -156,7 +156,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -204,7 +204,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error reporting playback stopped", ex); + _logger.LogError(ex, "Error reporting playback stopped"); } } @@ -223,7 +223,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -247,7 +247,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } @@ -278,7 +278,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error reporting progress", ex); + _logger.LogError(ex, "Error reporting progress"); } } diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 0384d8f11c..47d00aad56 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -121,7 +121,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError("Error creating PlayTo device.", ex); + _logger.LogError(ex, "Error creating PlayTo device."); } finally { diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 55fe7fb80d..ae094cc2f6 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -52,7 +52,7 @@ namespace Emby.Dlna.Service } catch (Exception ex) { - _logger.LogError("Error processing control request", ex); + _logger.LogError(ex, "Error processing control request"); return new ControlErrorHandler().GetResponse(ex); } diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs index f5de730a10..6aac77cf4b 100644 --- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs @@ -103,7 +103,7 @@ namespace Emby.Drawing.ImageMagick } catch { - //_logger.LogError("Error loading webp: ", ex); + //_logger.LogError(ex, "Error loading webp: "); _webpAvailable = false; } } @@ -295,7 +295,7 @@ namespace Emby.Drawing.ImageMagick } catch (Exception ex) { - _logger.LogError("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing.Net/GDIImageEncoder.cs b/Emby.Drawing.Net/GDIImageEncoder.cs index 4391cc618e..1639125d37 100644 --- a/Emby.Drawing.Net/GDIImageEncoder.cs +++ b/Emby.Drawing.Net/GDIImageEncoder.cs @@ -214,7 +214,7 @@ namespace Emby.Drawing.Net } catch (Exception ex) { - _logger.LogError("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs index 185b11f45b..7a445a09ce 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing.Skia/SkiaEncoder.cs @@ -660,7 +660,7 @@ namespace Emby.Drawing.Skia } catch (Exception ex) { - _logger.LogError("Error drawing indicator overlay", ex); + _logger.LogError(ex, "Error drawing indicator overlay"); } } diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 8cbe5f96a3..c417f37854 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -302,7 +302,7 @@ namespace Emby.Drawing { // Decoder failed to decode it #if DEBUG - _logger.LogError("Error encoding image", ex); + _logger.LogError(ex, "Error encoding image"); #endif // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -310,7 +310,7 @@ namespace Emby.Drawing catch (Exception ex) { // If it fails for whatever reason, return the original image - _logger.LogError("Error encoding image", ex); + _logger.LogError(ex, "Error encoding image"); // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -603,7 +603,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.LogError("Image conversion failed for {0}", ex, originalImagePath); + _logger.LogError(ex, "Image conversion failed for {originalImagePath}", originalImagePath); } } @@ -660,7 +660,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.LogError("Error enhancing image", ex); + _logger.LogError(ex, "Error enhancing image"); } return new ValueTuple(originalImagePath, dateModified, inputImageSupportsTransparency); @@ -853,7 +853,7 @@ namespace Emby.Drawing } catch (Exception ex) { - _logger.LogError("Error in image enhancer: {0}", ex, i.GetType().Name); + _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name); } } diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index 209bc82aa7..fa8fdd9c15 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -134,7 +134,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.LogError("Error sending notification to {0}", ex, service.Name); + _logger.LogError(ex, "Error sending notification to {0}", service.Name); } } @@ -146,7 +146,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.LogError("Error in IsEnabledForUser", ex); + _logger.LogError(ex, "Error in IsEnabledForUser"); return false; } } @@ -177,7 +177,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.LogError("Error in GetNotificationTypes", ex); + _logger.LogError(ex, "Error in GetNotificationTypes"); return new List(); } diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs index ab78f9f917..c09c4d449a 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/Notifications.cs @@ -273,7 +273,7 @@ namespace Emby.Notifications } catch (Exception ex) { - _logger.LogError("Error sending notification", ex); + _logger.LogError(ex, "Error sending notification"); } } diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs index ace3b2afbf..726fd1d79d 100644 --- a/Emby.Photos/PhotoProvider.cs +++ b/Emby.Photos/PhotoProvider.cs @@ -170,9 +170,9 @@ namespace Emby.Photos } } } - catch (Exception e) + catch (Exception ex) { - _logger.LogError("Image Provider - Error reading image tag for {0}", e, item.Path); + _logger.LogError(ex, "Image Provider - Error reading image tag for {0}", item.Path); } } diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index a84d6d45fd..fcdcb0c2c2 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.LogError("Error loading database file. Will reset and retry.", ex); + Logger.LogError(ex, "Error loading database file. Will reset and retry."); FileSystem.DeleteFile(DbFilePath); @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.Activity } catch (Exception ex) { - Logger.LogError("Error migrating activity log database", ex); + Logger.LogError(ex, "Error migrating activity log database"); } } @@ -87,36 +87,34 @@ namespace Emby.Server.Implementations.Activity } using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + connection.RunInTransaction(db => { - connection.RunInTransaction(db => + using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)")) { - using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)")) + statement.TryBind("@Name", entry.Name); + + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) { - statement.TryBind("@Name", entry.Name); - - statement.TryBind("@Overview", entry.Overview); - statement.TryBind("@ShortOverview", entry.ShortOverview); - statement.TryBind("@Type", entry.Type); - statement.TryBind("@ItemId", entry.ItemId); - - if (entry.UserId.Equals(Guid.Empty)) - { - statement.TryBindNull("@UserId"); - } - else - { - statement.TryBind("@UserId", entry.UserId.ToString("N")); - } - - statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); - statement.TryBind("@LogSeverity", entry.Severity.ToString()); - - statement.MoveNext(); + statement.TryBindNull("@UserId"); } - }, TransactionMode); - } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); } } @@ -128,132 +126,128 @@ namespace Emby.Server.Implementations.Activity } using (WriteLock.Write()) + using (var connection = CreateConnection()) { - using (var connection = CreateConnection()) + connection.RunInTransaction(db => { - connection.RunInTransaction(db => + using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id")) { - using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id")) + statement.TryBind("@Id", entry.Id); + + statement.TryBind("@Name", entry.Name); + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) { - statement.TryBind("@Id", entry.Id); - - statement.TryBind("@Name", entry.Name); - statement.TryBind("@Overview", entry.Overview); - statement.TryBind("@ShortOverview", entry.ShortOverview); - statement.TryBind("@Type", entry.Type); - statement.TryBind("@ItemId", entry.ItemId); - - if (entry.UserId.Equals(Guid.Empty)) - { - statement.TryBindNull("@UserId"); - } - else - { - statement.TryBind("@UserId", entry.UserId.ToString("N")); - } - - statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); - statement.TryBind("@LogSeverity", entry.Severity.ToString()); - - statement.MoveNext(); + statement.TryBindNull("@UserId"); } - }, TransactionMode); - } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); } } public QueryResult GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) { using (WriteLock.Read()) + using (var connection = CreateConnection(true)) { - using (var connection = CreateConnection(true)) + var commandText = BaseActivitySelectText; + var whereClauses = new List(); + + if (minDate.HasValue) { - var commandText = BaseActivitySelectText; - var whereClauses = new List(); - - if (minDate.HasValue) + whereClauses.Add("DateCreated>=@DateCreated"); + } + if (hasUserId.HasValue) + { + if (hasUserId.Value) { - whereClauses.Add("DateCreated>=@DateCreated"); + whereClauses.Add("UserId not null"); } - if (hasUserId.HasValue) + else { - if (hasUserId.Value) - { - whereClauses.Add("UserId not null"); - } - else - { - whereClauses.Add("UserId is null"); - } + whereClauses.Add("UserId is null"); } + } - var whereTextWithoutPaging = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray()); + var whereTextWithoutPaging = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); - if (startIndex.HasValue && startIndex.Value > 0) - { - var pagingWhereText = whereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray()); - - whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", - pagingWhereText, - startIndex.Value.ToString(_usCulture))); - } - - var whereText = whereClauses.Count == 0 ? + if (startIndex.HasValue && startIndex.Value > 0) + { + var pagingWhereText = whereClauses.Count == 0 ? string.Empty : " where " + string.Join(" AND ", whereClauses.ToArray()); - commandText += whereText; + whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", + pagingWhereText, + startIndex.Value.ToString(_usCulture))); + } - commandText += " ORDER BY DateCreated DESC"; + var whereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); - if (limit.HasValue) + commandText += whereText; + + commandText += " ORDER BY DateCreated DESC"; + + if (limit.HasValue) + { + commandText += " LIMIT " + limit.Value.ToString(_usCulture); + } + + var statementTexts = new List(); + statementTexts.Add(commandText); + statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging); + + return connection.RunInTransaction(db => + { + var list = new List(); + var result = new QueryResult(); + + var statements = PrepareAllSafe(db, statementTexts).ToList(); + + using (var statement = statements[0]) { - commandText += " LIMIT " + limit.Value.ToString(_usCulture); + if (minDate.HasValue) + { + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); + } + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetEntry(row)); + } } - var statementTexts = new List(); - statementTexts.Add(commandText); - statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging); - - return connection.RunInTransaction(db => + using (var statement = statements[1]) { - var list = new List(); - var result = new QueryResult(); - - var statements = PrepareAllSafe(db, statementTexts).ToList(); - - using (var statement = statements[0]) + if (minDate.HasValue) { - if (minDate.HasValue) - { - statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); - } - - foreach (var row in statement.ExecuteQuery()) - { - list.Add(GetEntry(row)); - } + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); } - using (var statement = statements[1]) - { - if (minDate.HasValue) - { - statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); - } + result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + } - result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); - } + result.Items = list.ToArray(list.Count); + return result; - result.Items = list.ToArray(); - return result; - - }, ReadTransactionMode); - } + }, ReadTransactionMode); } } diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index fdf2a3b731..fddf19893f 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception ex) { - Logger.LogError("Error loading configuration file: {0}", ex, path); + Logger.LogError(ex, "Error loading configuration file: {path}", path); return Activator.CreateInstance(configurationType); } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index aa9b6e82a3..888635c9d8 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -545,7 +545,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error creating {0}", ex, type.FullName); + Logger.LogError(ex, "Error creating {type}", type.FullName); // Don't blow up in release mode return null; } @@ -625,7 +625,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error loading assembly {0}", ex, file); + Logger.LogError(ex, "Error loading assembly {file}", file); return null; } } @@ -648,7 +648,7 @@ namespace Emby.Server.Implementations /// /// if set to true [manage liftime]. /// IEnumerable{``0}. - public IEnumerable GetExports(bool manageLiftime = true) + public IEnumerable GetExports(bool manageLifetime = true) { var parts = GetExportTypes() .Select(CreateInstanceSafe) @@ -656,7 +656,7 @@ namespace Emby.Server.Implementations .Cast() .ToList(); - if (manageLiftime) + if (manageLifetime) { lock (DisposableParts) { @@ -667,7 +667,7 @@ namespace Emby.Server.Implementations return parts; } - public List> GetExportsWithInfo(bool manageLiftime = true) + public List> GetExportsWithInfo(bool manageLifetime = true) { var parts = GetExportTypes() .Select(i => @@ -683,7 +683,7 @@ namespace Emby.Server.Implementations .Where(i => i != null) .ToList(); - if (manageLiftime) + if (manageLifetime) { lock (DisposableParts) { @@ -693,6 +693,8 @@ namespace Emby.Server.Implementations return parts; } + + // TODO: @bond /* private void SetBaseExceptionMessage() { @@ -760,7 +762,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error in {0}", ex, name); + Logger.LogError(ex, "Error in {name}", name); } Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); } @@ -777,7 +779,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error configuring autorun", ex); + Logger.LogError(ex, "Error configuring autorun"); } } @@ -1119,7 +1121,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error setting http limit", ex); + Logger.LogError(ex, "Error setting http limit"); } } @@ -1186,7 +1188,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error loading cert from {0}", ex, certificateLocation); + Logger.LogError(ex, "Error loading cert from {certificateLocation}", certificateLocation); return null; } } @@ -1415,7 +1417,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error getting plugin Id from {0}.", ex, plugin.GetType().FullName); + Logger.LogError(ex, "Error getting plugin Id from {pluginName}.", plugin.GetType().FullName); } } @@ -1427,7 +1429,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error loading plugin {0}", ex, plugin.GetType().FullName); + Logger.LogError(ex, "Error loading plugin {pluginName}", plugin.GetType().FullName); return null; } @@ -1450,11 +1452,11 @@ namespace Emby.Server.Implementations if (path == null) { - Logger.LogInformation("Loading {0}", assembly.FullName); + Logger.LogInformation("Loading {assemblyName}", assembly.FullName); } else { - Logger.LogInformation("Loading {0} from {1}", assembly.FullName, path); + Logger.LogInformation("Loading {assemblyName} from {path}", assembly.FullName, path); } } @@ -1507,7 +1509,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error loading types from assembly", ex); + Logger.LogError(ex, "Error loading types from assembly"); return new List>(); } @@ -1554,7 +1556,7 @@ namespace Emby.Server.Implementations ? "The http server is unable to start due to a Socket error. This can occasionally happen when the operating system takes longer than usual to release the IP bindings from the previous session. This can take up to five minutes. Please try waiting or rebooting the system." : "Error starting Http Server"; - Logger.LogError(msg, ex); + Logger.LogError(ex, msg); if (HttpPort == ServerConfiguration.DefaultHttpPort) { @@ -1570,7 +1572,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error starting http server", ex); + Logger.LogError(ex, "Error starting http server"); throw; } @@ -1605,7 +1607,7 @@ namespace Emby.Server.Implementations // } // catch (Exception ex) // { - // Logger.LogError("Error creating ssl cert", ex); + // Logger.LogError(ex, "Error creating ssl cert"); // return null; // } // } @@ -1710,7 +1712,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error sending server restart notification", ex); + Logger.LogError(ex, "Error sending server restart notification"); } Logger.LogInformation("Calling RestartInternal"); @@ -1845,7 +1847,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error getting version number from {0}", ex, path); + Logger.LogError(ex, "Error getting version number from {path}", path); return new Version(1, 0); } @@ -1930,13 +1932,13 @@ namespace Emby.Server.Implementations if (version < minRequiredVersion) { - Logger.LogInformation("Not loading {0} {1} because the minimum supported version is {2}. Please update to the newer version", filename, version, minRequiredVersion); + Logger.LogInformation("Not loading {filename} {version} because the minimum supported version is {minRequiredVersion}. Please update to the newer version", filename, version, minRequiredVersion); return false; } } catch (Exception ex) { - Logger.LogError("Error getting version number from {0}", ex, path); + Logger.LogError(ex, "Error getting version number from {path}", path); return false; } @@ -2043,7 +2045,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error getting local Ip address information", ex); + Logger.LogError(ex, "Error getting local Ip address information"); } return null; @@ -2251,7 +2253,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error sending server shutdown notification", ex); + Logger.LogError(ex, "Error sending server shutdown notification"); } ShutdownInternal(); @@ -2276,7 +2278,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error authorizing server", ex); + Logger.LogError(ex, "Error authorizing server"); } } @@ -2443,9 +2445,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Console.WriteLine("Error launching url: {0}", url); - Logger.LogError("Error launching url: {0}", ex, url); - + Logger.LogError(ex, "Error launching url: {url}", url); throw; } } @@ -2516,7 +2516,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError("Error disposing {0}", ex, part.GetType().Name); + Logger.LogError(ex, "Error disposing {0}", part.GetType().Name); } } } diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 88dfbd7c15..00da46f303 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -300,7 +300,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.LogError("Error getting channel information for {0}", ex, channelInfo.Name); + _logger.LogError(ex, "Error getting channel information for {0}", channelInfo.Name); } numComplete++; @@ -848,7 +848,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.LogError("Error writing to channel cache file: {0}", ex, path); + _logger.LogError(ex, "Error writing to channel cache file: {path}", path); } } @@ -911,7 +911,7 @@ namespace Emby.Server.Implementations.Channels } catch (Exception ex) { - _logger.LogError("Error retrieving channel item from database", ex); + _logger.LogError(ex, "Error retrieving channel item from database"); } if (item == null) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index af7c70d7d8..d1afb0712a 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -365,7 +365,7 @@ namespace Emby.Server.Implementations.Collections } catch (Exception ex) { - _logger.LogError("Error creating camera uploads library", ex); + _logger.LogError(ex, "Error creating camera uploads library"); } _config.Configuration.CollectionsUpgraded = true; diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 8e59596dd3..59776c3736 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -323,7 +323,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.LogError("Error disposing database", ex); + Logger.LogError(ex, "Error disposing database"); } } diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 307342135e..00e1956cf8 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.LogError("Error loading database file. Will reset and retry.", ex); + Logger.LogError(ex, "Error loading database file. Will reset and retry."); FileSystem.DeleteFile(DbFilePath); diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 7239eec931..0f9770e8f7 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1364,7 +1364,7 @@ namespace Emby.Server.Implementations.Data } catch (SerializationException ex) { - Logger.LogError("Error deserializing item", ex); + Logger.LogError(ex, "Error deserializing item"); } } } diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index 9ac255ec44..d490a481e4 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.Data } catch (Exception ex) { - Logger.LogError("Error migrating users database", ex); + Logger.LogError(ex, "Error migrating users database"); } } diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index fe953bfb99..90cef5d06e 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.LogError("Error reading file", ex); + _logger.LogError(ex, "Error reading file"); } return null; @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.LogError("Error writing to file", ex); + _logger.LogError(ex, "Error writing to file"); } } diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index c5c86f5b9d..2503162118 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.Devices } catch (Exception ex) { - _logger.LogError("Error creating camera uploads library", ex); + _logger.LogError(ex, "Error creating camera uploads library"); } _config.Configuration.CameraUploadUpgraded = true; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 4243099950..e8d06ec002 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -225,7 +225,7 @@ namespace Emby.Server.Implementations.Dto catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.LogError("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name); + _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {itemName}", item.Name); } } @@ -547,7 +547,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError("Error getting {0} image info", ex, type); + _logger.LogError(ex, "Error getting {type} image info", type); return null; } } @@ -560,7 +560,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError(ex, "Error getting {imageType} image info for {path}", image.Type, image.Path); return null; } } @@ -619,7 +619,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError("Error getting person {0}", ex, c); + _logger.LogError(ex, "Error getting person {0}", c); return null; } @@ -1451,7 +1451,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - //_logger.LogError("Failed to determine primary image aspect ratio for {0}", ex, imageInfo.Path); + _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); return null; } } @@ -1464,7 +1464,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError("Error in image enhancer: {0}", ex, enhancer.GetType().Name); + _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name); } } diff --git a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs index cd5fca40d1..a0947c87d5 100644 --- a/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/AutomaticRestartEntryPoint.cs @@ -73,7 +73,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error restarting server", ex); + _logger.LogError(ex, "Error restarting server"); } } } @@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error getting timers", ex); + _logger.LogError(ex, "Error getting timers"); } } diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 46fbc94fdc..a95e21e1c5 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -216,7 +216,7 @@ namespace Emby.Server.Implementations.EntryPoints catch { // Commenting out because users are reporting problems out of our control - //_logger.LogError("Error creating port forwarding rules", ex); + //_logger.LogError(ex, "Error creating port forwarding rules"); } } @@ -253,6 +253,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error creating http port map"); return; } @@ -262,6 +263,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error creating https port map"); } } @@ -309,7 +311,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error stopping NAT Discovery", ex); + _logger.LogError(ex, "Error stopping NAT Discovery"); } } } diff --git a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs index a9121ba32d..a6dadcef0c 100644 --- a/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs +++ b/Emby.Server.Implementations/EntryPoints/KeepServerAwake.cs @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error resetting system standby timer", ex); + _logger.LogError(ex, "Error resetting system standby timer"); } } diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index ff283667bc..bb8ef52f18 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -331,7 +331,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error in GetLibraryUpdateInfo", ex); + _logger.LogError(ex, "Error in GetLibraryUpdateInfo"); return; } @@ -346,7 +346,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error sending LibraryChanged message", ex); + _logger.LogError(ex, "Error sending LibraryChanged message"); } } } diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index 24cd659e10..0b377dc682 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Error sending message", ex); + _logger.LogError(ex, "Error sending message"); } } diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs index f6a74c4ecf..72dcabab38 100644 --- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs @@ -156,14 +156,10 @@ namespace Emby.Server.Implementations.EntryPoints try { await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None); - } - catch (ObjectDisposedException) - { - } catch (Exception) { - //Logger.LogError("Error sending message", ex); + } } @@ -172,14 +168,10 @@ namespace Emby.Server.Implementations.EntryPoints try { await _sessionManager.SendMessageToUserSessions(new List { user.Id }, name, data, CancellationToken.None); - } - catch (ObjectDisposedException) - { - } catch (Exception) { - //Logger.LogError("Error sending message", ex); + } } diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 1bb11ce406..f8e2d32ddf 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - _logger.LogError("Failed to start UDP Server", ex); + _logger.LogError(ex, "Failed to start UDP Server"); } } diff --git a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs index ca79262b0b..f7542a5e92 100644 --- a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs @@ -91,7 +91,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.LogError("Error sending anonymous usage statistics.", ex); + _logger.LogError(ex, "Error sending anonymous usage statistics."); } } @@ -119,7 +119,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { - //_logger.LogError("Error sending anonymous usage statistics.", ex); + _logger.LogError(ex, "Error sending anonymous usage statistics."); } } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index b3f8ef8848..23dd55b183 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -685,7 +685,7 @@ namespace Emby.Server.Implementations.HttpClientManager { if (options.LogErrors) { - _logger.LogError("Error " + webException.Status + " getting response from " + options.Url, webException); + _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url); } var exception = new HttpException(webException.Message, webException); @@ -723,7 +723,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrors) { - _logger.LogError("Error getting response from " + options.Url, ex); + _logger.LogError(ex, "Error getting response from {url}", options.Url); } return ex; diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 1d87d0e445..704b7f8a6f 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -252,7 +252,7 @@ namespace Emby.Server.Implementations.HttpServer if (logExceptionStackTrace) { - _logger.LogError("Error processing request", ex); + _logger.LogError(ex, "Error processing request"); } else if (logExceptionMessage) { @@ -272,9 +272,9 @@ namespace Emby.Server.Implementations.HttpServer httpRes.ContentType = "text/html"; await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false); } - catch + catch (Exception errorEx) { - //_logger.LogError("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); + _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)"); } } @@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.HttpServer var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) { - _logger.LogError("Path parts empty for PathInfo: {0}, Url: {1}", pathInfo, httpReq.RawUrl); + _logger.LogError("Path parts empty for PathInfo: {pathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl); return null; } @@ -729,7 +729,7 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.LogError("Could not find handler for {0}", pathInfo); + _logger.LogError("Could not find handler for {pathInfo}", pathInfo); return null; } @@ -919,7 +919,7 @@ namespace Emby.Server.Implementations.HttpServer return Task.CompletedTask; } - //_logger.LogDebug("Websocket message received: {0}", result.MessageType); + _logger.LogDebug("Websocket message received: {0}", result.MessageType); var tasks = _webSocketListeners.Select(i => Task.Run(async () => { @@ -929,7 +929,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.LogError("{0} failed processing WebSocket message {1}", ex, i.GetType().Name, result.MessageType ?? string.Empty); + _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty); } })); diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index b1759069cc..f38aa5ea06 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.HttpServer if (exception != null) { - _logger.LogError("Error processing request for {0}", exception, req.RawUrl); + _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); if (!string.IsNullOrEmpty(exception.Message)) { diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index 037bdde771..8b5dfd4440 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -180,7 +180,7 @@ namespace Emby.Server.Implementations.HttpServer if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase)) { // This info is useful sometimes but also clogs up the log - //_lLogError("Received web socket message that is not a json structure: " + message); + _logger.LogDebug("Received web socket message that is not a json structure: {message}", message); return; } @@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.HttpServer } catch (Exception ex) { - _logger.LogError("Error processing web socket message", ex); + _logger.LogError(ex, "Error processing web socket message"); } } diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 6087f3cf27..df484d04c7 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Error processing directory changes", ex); + Logger.LogError(ex, "Error processing directory changes"); } } @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.IO continue; } - Logger.LogInformation(item.Name + " (" + item.Path + ") will be refreshed."); + Logger.LogInformation("{name} ({path}}) will be refreshed.", item.Name, item.Path); try { @@ -172,11 +172,11 @@ namespace Emby.Server.Implementations.IO // For now swallow and log. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable) // Should we remove it from it's parent? - Logger.LogError("Error refreshing {0}", ex, item.Name); + Logger.LogError(ex, "Error refreshing {name}", item.Name); } catch (Exception ex) { - Logger.LogError("Error refreshing {0}", ex, item.Name); + Logger.LogError(ex, "Error refreshing {name}", item.Name); } } } diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index 22d1783eda..ca5810fd6c 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Error in ReportFileSystemChanged for {0}", ex, path); + Logger.LogError(ex, "Error in ReportFileSystemChanged for {path}", path); } } } @@ -354,7 +354,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Error watching path: {0}", ex, path); + Logger.LogError(ex, "Error watching path: {path}", path); } }); } @@ -382,7 +382,7 @@ namespace Emby.Server.Implementations.IO { using (watcher) { - Logger.LogInformation("Stopping directory watching for path {0}", watcher.Path); + Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path); watcher.Created -= watcher_Changed; watcher.Deleted -= watcher_Changed; @@ -439,7 +439,7 @@ namespace Emby.Server.Implementations.IO var ex = e.GetException(); var dw = (FileSystemWatcher)sender; - Logger.LogError("Error in Directory watcher for: " + dw.Path, ex); + Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path); DisposeWatcher(dw, true); } @@ -461,7 +461,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath); + Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath); } } @@ -487,13 +487,13 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(i, path)) { - //logger.LogDebug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } if (_fileSystem.ContainsSubPath(i, path)) { - //logger.LogDebug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } @@ -503,7 +503,7 @@ namespace Emby.Server.Implementations.IO { if (_fileSystem.AreEqual(parent, path)) { - //logger.LogDebug("Ignoring change to {0}", path); + Logger.LogDebug("Ignoring change to {path}", path); return true; } } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 42b9ae23bc..8819449b5c 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -175,7 +175,7 @@ namespace Emby.Server.Implementations.IO path = System.IO.Path.GetFullPath(path); return path; } - catch (ArgumentException ex) + catch (ArgumentException) { return filePath; } @@ -395,7 +395,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Error determining CreationTimeUtc for {0}", ex, info.FullName); + Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName); return DateTime.MinValue; } } @@ -434,7 +434,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError("Error determining LastAccessTimeUtc for {0}", ex, info.FullName); + Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName); return DateTime.MinValue; } } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index e1a725c936..451f16bef8 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -384,7 +384,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error deleting {0}", ex, metadataPath); + _logger.LogError(ex, "Error deleting {metadataPath}", metadataPath); } } @@ -398,14 +398,13 @@ namespace Emby.Server.Implementations.Library { try { + _logger.LogDebug("Deleting path {path}", fileSystemInfo.FullName); if (fileSystemInfo.IsDirectory) { - _logger.LogDebug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteDirectory(fileSystemInfo.FullName, true); } else { - _logger.LogDebug("Deleting path {0}", fileSystemInfo.FullName); _fileSystem.DeleteFile(fileSystemInfo.FullName); } } @@ -489,7 +488,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path); + _logger.LogError(ex, "Error in {resolver} resolving {path}", resolver.GetType().Name, args.Path); return null; } } @@ -587,7 +586,7 @@ namespace Emby.Server.Implementations.Library { if (parent != null && parent.IsPhysicalRoot) { - _logger.LogError("Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", ex, isPhysicalRoot, isVf); + _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf); files = new FileSystemMetadata[] { }; } @@ -713,7 +712,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error resolving path {0}", ex, f.FullName); + _logger.LogError(ex, "Error resolving path {path}", f.FullName); return null; } }).Where(i => i != null); @@ -1148,7 +1147,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error running postscan task", ex); + _logger.LogError(ex, "Error running postscan task"); } numComplete++; @@ -1199,7 +1198,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error resolving shortcut file {0}", ex, i); + _logger.LogError(ex, "Error resolving shortcut file {file}", i); return null; } }) @@ -1650,7 +1649,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error getting intros", ex); + _logger.LogError(ex, "Error getting intros"); return new List(); } @@ -1670,7 +1669,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error getting intro files", ex); + _logger.LogError(ex, "Error getting intro files"); return new List(); } @@ -1693,7 +1692,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.LogError("Unable to locate item with Id {0}.", info.ItemId.Value); + _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value); } } else if (!string.IsNullOrEmpty(info.Path)) @@ -1705,7 +1704,7 @@ namespace Emby.Server.Implementations.Library if (video == null) { - _logger.LogError("Intro resolver returned null for {0}.", info.Path); + _logger.LogError("Intro resolver returned null for {path}.", info.Path); } else { @@ -1724,7 +1723,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error resolving path {0}.", ex, info.Path); + _logger.LogError(ex, "Error resolving path {path}.", info.Path); } } else @@ -1873,7 +1872,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error in ItemAdded event handler", ex); + _logger.LogError(ex, "Error in ItemAdded event handler"); } } } @@ -1929,7 +1928,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error in ItemUpdated event handler", ex); + _logger.LogError(ex, "Error in ItemUpdated event handler"); } } } @@ -1965,7 +1964,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error in ItemRemoved event handler", ex); + _logger.LogError(ex, "Error in ItemRemoved event handler"); } } } @@ -2808,7 +2807,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error getting person", ex); + _logger.LogError(ex, "Error getting person"); return null; } diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 15673d25d5..e5fd289979 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -256,7 +256,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error getting media sources", ex); + _logger.LogError(ex, "Error getting media sources"); return new List(); } } @@ -477,7 +477,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error probing live tv stream", ex); + _logger.LogError(ex, "Error probing live tv stream"); AddMediaInfo(mediaSource, isAudio); } diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index 35b0ca304e..ae3577b7d0 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -392,7 +392,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error authenticating with provider {0}", ex, provider.Name); + _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name); return false; } @@ -575,7 +575,7 @@ namespace Emby.Server.Implementations.Library catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.LogError("Error generating PrimaryImageAspectRatio for {0}", ex, user.Name); + _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name); } } @@ -599,7 +599,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error getting {0} image info for {1}", ex, image.Type, image.Path); + _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path); return null; } } @@ -775,7 +775,7 @@ namespace Emby.Server.Implementations.Library } catch (IOException ex) { - _logger.LogError("Error deleting file {0}", ex, configPath); + _logger.LogError(ex, "Error deleting file {path}", configPath); } DeleteUserPolicy(user); @@ -1045,7 +1045,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error reading policy file: {0}", ex, path); + _logger.LogError(ex, "Error reading policy file: {path}", path); return GetDefaultPolicy(user); } @@ -1109,7 +1109,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error deleting policy file", ex); + _logger.LogError(ex, "Error deleting policy file"); } } @@ -1144,7 +1144,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError("Error reading policy file: {0}", ex, path); + _logger.LogError(ex, "Error reading policy file: {path}", path); return new UserConfiguration(); } diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs index 593a9a1ef4..1686dc23c1 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs @@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {ArtistName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs index ffa5608ddd..070777475c 100644 --- a/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GameGenresValidator.cs @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs index e59b747de4..775cde299b 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresValidator.cs @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs index ec8568afcc..b5ed1c0e6e 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresValidator.cs @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {GenreName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index 80e3965830..50c7cfbc61 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error validating IBN entry {0}", ex, person); + _logger.LogError(ex, "Error validating IBN entry {person}", person); } // Update progress diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs index fec9890328..1a5ebac54e 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Library.Validators } catch (Exception ex) { - _logger.LogError("Error refreshing {0}", ex, name); + _logger.LogError(ex, "Error refreshing {StudioName}", name); } numComplete++; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index b9b8802a82..ef96510bda 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -170,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error creating virtual folder", ex); + _logger.LogError(ex, "Error creating virtual folder"); } pathsAdded.AddRange(pathsToCreate); @@ -196,7 +196,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error creating recording folders", ex); + _logger.LogError(ex, "Error creating recording folders"); } } @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error removing virtual folder", ex); + _logger.LogError(ex, "Error removing virtual folder"); } } else @@ -236,14 +236,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error removing media path", ex); + _logger.LogError(ex, "Error removing media path"); } } } if (requiresRefresh) { - _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); + await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); } } @@ -342,7 +342,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -364,7 +364,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error adding metadata", ex); + _logger.LogError(ex, "Error adding metadata"); } } } @@ -595,7 +595,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error getting channels", ex); + _logger.LogError(ex, "Error getting channels"); } } @@ -1217,7 +1217,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error recording stream", ex); + _logger.LogError(ex, "Error recording stream"); } } @@ -1414,16 +1414,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false); recordingStatus = RecordingStatus.Completed; - _logger.LogInformation("Recording completed: {0}", recordPath); + _logger.LogInformation("Recording completed: {recordPath}", recordPath); } catch (OperationCanceledException) { - _logger.LogInformation("Recording stopped: {0}", recordPath); + _logger.LogInformation("Recording stopped: {recordPath}", recordPath); recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { - _logger.LogError("Error recording to {0}", ex, recordPath); + _logger.LogError(ex, "Error recording to {recordPath}", recordPath); recordingStatus = RecordingStatus.Error; } @@ -1435,7 +1435,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error closing live stream", ex); + _logger.LogError(ex, "Error closing live stream"); } } @@ -1511,20 +1511,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error deleting 0-byte failed recording file {0}", ex, path); + _logger.LogError(ex, "Error deleting 0-byte failed recording file {path}", path); } } } private void TriggerRefresh(string path) { - _logger.LogInformation("Triggering refresh on {0}", path); + _logger.LogInformation("Triggering refresh on {path}", path); var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); if (item != null) { - _logger.LogInformation("Refreshing recording parent {0}", item.Path); + _logger.LogInformation("Refreshing recording parent {path}", item.Path); _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { @@ -1642,7 +1642,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error deleting item", ex); + _logger.LogError(ex, "Error deleting item"); } } } @@ -1668,7 +1668,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error deleting recording", ex); + _logger.LogError(ex, "Error deleting recording"); } } } @@ -1780,7 +1780,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error running recording post processor", ex); + _logger.LogError(ex, "Error running recording post processor"); } } @@ -1794,7 +1794,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var process = (IProcess)sender; try { - _logger.LogInformation("Recording post-processing script completed with exit code {0}", process.ExitCode); + _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode); } catch { @@ -1875,7 +1875,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1890,7 +1890,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1903,7 +1903,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } @@ -1916,7 +1916,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error saving recording image", ex); + _logger.LogError(ex, "Error saving recording image"); } } } @@ -1984,7 +1984,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error saving nfo", ex); + _logger.LogError(ex, "Error saving nfo"); } } @@ -2814,7 +2814,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error discovering tuner devices", ex); + _logger.LogError(ex, "Error discovering tuner devices"); return new List(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index af5e96c057..4ea83b7acd 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -269,14 +269,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { try { - _logger.LogInformation("Stopping ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath); //process.Kill(); _process.StandardInput.WriteLine("q"); } catch (Exception ex) { - _logger.LogError("Error stopping recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath); } if (_hasExited) @@ -286,7 +286,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.LogInformation("Calling recording process.WaitForExit for {0}", _targetPath); + _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath); if (_process.WaitForExit(10000)) { @@ -295,7 +295,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error waiting for recording process to exit for {0}", ex, _targetPath); + _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath); } if (_hasExited) @@ -305,13 +305,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _logger.LogInformation("Killing ffmpeg recording process for {0}", _targetPath); + _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath); _process.Kill(); } catch (Exception ex) { - _logger.LogError("Error killing recording transcoding job for {0}", ex, _targetPath); + _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath); } } } @@ -329,7 +329,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { var exitCode = process.ExitCode; - _logger.LogInformation("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath); + _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath); if (exitCode == 0) { @@ -337,13 +337,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode))); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode))); } } catch { - _logger.LogError("FFMpeg recording exited with an error for {0}.", _targetPath); - _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath))); + _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath); + _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath))); } } @@ -357,7 +357,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error disposing recording log stream", ex); + _logger.LogError(ex, "Error disposing recording log stream"); } _logFileStream = null; @@ -387,7 +387,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error reading ffmpeg recording log", ex); + _logger.LogError(ex, "Error reading ffmpeg recording log"); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 813a7a5f9a..9f179dc2ce 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - Logger.LogError("Error deserializing {0}", ex, jsonFile); + Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile); } return new List(); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index f00a54c7f3..5618579f6f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } catch (Exception ex) { - _logger.LogError("Error scheduling wake timer", ex); + _logger.LogError(ex, "Error scheduling wake timer"); } } @@ -153,12 +153,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (_timers.TryAdd(item.Id, timer)) { - _logger.LogInformation("Creating recording timer for {0}, {1}. Timer will fire in {2} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture)); } else { timer.Dispose(); - _logger.LogWarning("Timer already exists for item {0}", item.Id); + _logger.LogWarning("Timer already exists for item {id}", item.Id); } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 48b4e58339..8fb3af2113 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -527,7 +527,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.LogError("Error getting image info from schedules direct", ex); + _logger.LogError(ex, "Error getting image info from schedules direct"); return new List(); } @@ -557,35 +557,33 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using (var httpResponse = await Get(options, false, info).ConfigureAwait(false)) + using (Stream responce = httpResponse.Content) { - using (Stream responce = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync>(responce).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync>(responce).ConfigureAwait(false); - if (root != null) + if (root != null) + { + foreach (ScheduleDirect.Headends headend in root) { - foreach (ScheduleDirect.Headends headend in root) + foreach (ScheduleDirect.Lineup lineup in headend.lineups) { - foreach (ScheduleDirect.Lineup lineup in headend.lineups) + lineups.Add(new NameIdPair { - lineups.Add(new NameIdPair - { - Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, - Id = lineup.uri.Substring(18) - }); - } + Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name, + Id = lineup.uri.Substring(18) + }); } } - else - { - _logger.LogInformation("No lineups available"); - } + } + else + { + _logger.LogInformation("No lineups available"); } } } catch (Exception ex) { - _logger.LogError("Error getting headends", ex); + _logger.LogError(ex, "Error getting headends"); } return lineups; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index cc8840e14a..6fe5787158 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -170,6 +170,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -185,6 +186,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -212,6 +214,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } @@ -230,6 +233,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -260,6 +264,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } image = librarySeries.GetImageInfo(ImageType.Backdrop, 0); @@ -275,6 +280,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -333,6 +339,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { + _logger.LogError(ex, "Error"); } } } @@ -376,7 +383,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting image info for {0}", ex, info.Name); + _logger.LogError(ex, "Error getting image info for {name}", info.Name); } return null; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 679f8668b4..ee2a9fe4b3 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1089,7 +1089,7 @@ namespace Emby.Server.Implementations.LiveTv { cancellationToken.ThrowIfCancellationRequested(); - _logger.LogDebug("Refreshing guide from {0}", service.Name); + _logger.LogDebug("Refreshing guide from {name}", service.Name); try { @@ -1108,7 +1108,7 @@ namespace Emby.Server.Implementations.LiveTv catch (Exception ex) { cleanDatabase = false; - _logger.LogError("Error refreshing channels for service", ex); + _logger.LogError(ex, "Error refreshing channels for service"); } numComplete++; @@ -1171,7 +1171,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting channel information for {0}", ex, channelInfo.Item2.Name); + _logger.LogError(ex, "Error getting channel information for {name}", channelInfo.Item2.Name); } numComplete++; @@ -1300,7 +1300,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting programs for channel {0}", ex, currentChannel.Name); + _logger.LogError(ex, "Error getting programs for channel {name}", currentChannel.Name); } numComplete++; @@ -1645,7 +1645,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1721,7 +1721,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1876,7 +1876,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); @@ -1922,7 +1922,7 @@ namespace Emby.Server.Implementations.LiveTv } catch (Exception ex) { - _logger.LogError("Error getting recordings", ex); + _logger.LogError(ex, "Error getting recordings"); return new List>(); } }); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index 97c33f1fa8..ef2010ba64 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error getting channel list", ex); + Logger.LogError(ex, "Error getting channel list"); if (enableCache) { @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } } @@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error getting channels", ex); + Logger.LogError(ex, "Error getting channels"); } } @@ -221,7 +221,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error opening tuner", ex); + Logger.LogError(ex, "Error opening tuner"); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index a8d1dcaa31..be090df0c9 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -303,7 +303,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } catch (Exception ex) { - Logger.LogError("Error getting tuner info", ex); + Logger.LogError(ex, "Error getting tuner info"); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 933c341242..c781bccbb7 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun FileSystem.CreateDirectory(FileSystem.GetDirectoryName(TempFilePath)); - Logger.LogInformation("Opening HDHR UDP Live stream from {0}", uri.Host); + Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host); var remoteAddress = IPAddress.Parse(uri.Host); var embyRemoteAddress = _networkManager.ParseIpAddress(uri.Host); @@ -69,9 +69,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun localAddress = ((IPEndPoint)tcpSocket.LocalEndPoint).Address; tcpSocket.Close(); } - catch (Exception) + catch (Exception ex) { - Logger.LogError("Unable to determine local ip address for Legacy HDHomerun stream."); + Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream."); return; } } @@ -87,21 +87,19 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun catch (Exception ex) { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + if (!(ex is OperationCanceledException)) { - if (!(ex is OperationCanceledException)) - { - Logger.LogError("Error opening live stream:", ex); - } - throw; + Logger.LogError(ex, "Error opening live stream:"); } + throw; } } var taskCompletionSource = new TaskCompletionSource(); - StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); + await StartStreaming(udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, LiveStreamCancellationTokenSource.Token); //OpenedMediaSource.Protocol = MediaProtocol.File; //OpenedMediaSource.Path = tempFile; @@ -122,26 +120,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return Task.Run(async () => { using (udpClient) + using (hdHomerunManager) { - using (hdHomerunManager) + try { - try - { - await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException ex) - { - Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); - openTaskCompletionSource.TrySetException(ex); - } - catch (Exception ex) - { - Logger.LogError("Error opening live stream:", ex); - openTaskCompletionSource.TrySetException(ex); - } - - EnableStreamSharing = false; + await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException ex) + { + Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); + openTaskCompletionSource.TrySetException(ex); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error opening live stream:"); + openTaskCompletionSource.TrySetException(ex); + } + + EnableStreamSharing = false; } await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); @@ -166,30 +162,28 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var resolved = false; using (var source = _socketFactory.CreateNetworkStream(udpClient, false)) + using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) { - using (var fileStream = FileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None)) + var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; + + while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) { - var currentCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token).Token; + cancellationToken.ThrowIfCancellationRequested(); - while ((read = await source.ReadAsync(buffer, 0, buffer.Length, currentCancellationToken).ConfigureAwait(false)) != 0) + currentCancellationToken = cancellationToken; + + read -= RtpHeaderBytes; + + if (read > 0) { - cancellationToken.ThrowIfCancellationRequested(); + fileStream.Write(buffer, RtpHeaderBytes, read); + } - currentCancellationToken = cancellationToken; - - read -= RtpHeaderBytes; - - if (read > 0) - { - fileStream.Write(buffer, RtpHeaderBytes, read); - } - - if (!resolved) - { - resolved = true; - DateOpened = DateTime.UtcNow; - Resolve(openTaskCompletionSource); - } + if (!resolved) + { + resolved = true; + DateOpened = DateTime.UtcNow; + Resolve(openTaskCompletionSource); } } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index b1eda3b7f2..4a2b4ebb22 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error closing live stream", ex); + Logger.LogError(ex, "Error closing live stream"); } } @@ -139,7 +139,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - //Logger.LogError("Error deleting file {0}", ex, path); + Logger.LogError(ex, "Error deleting file {path}", path); failedFiles.Add(path); } } @@ -242,7 +242,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error seeking stream", ex); + Logger.LogError(ex, "Error seeking stream"); } } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index ca53036a41..9b10daba0d 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -138,7 +138,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } catch (Exception ex) { - Logger.LogError("Error copying live stream.", ex); + Logger.LogError(ex, "Error copying live stream."); } EnableStreamSharing = false; await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index 3c72635817..792ffb3c4f 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -166,7 +166,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (Exception ex) { - _logger.LogError("Error extracting chapter images for {0}", ex, string.Join(",", video.Path)); + _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path)); success = false; break; } @@ -226,7 +226,7 @@ namespace Emby.Server.Implementations.MediaEncoder foreach (var image in deadImages) { - _logger.LogDebug("Deleting dead chapter image {0}", image); + _logger.LogDebug("Deleting dead chapter image {path}", image); try { @@ -234,7 +234,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (IOException ex) { - _logger.LogError("Error deleting {0}.", ex, image); + _logger.LogError(ex, "Error deleting {path}.", image); } } } diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs index 7945680b36..260d20e35b 100644 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ b/Emby.Server.Implementations/Networking/NetworkManager.cs @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.LogError("Error binding to NetworkAddressChanged event", ex); + Logger.LogError(ex, "Error binding to NetworkAddressChanged event"); } try @@ -45,7 +45,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.LogError("Error binding to NetworkChange_NetworkAvailabilityChanged event", ex); + Logger.LogError(ex, "Error binding to NetworkChange_NetworkAvailabilityChanged event"); } } } @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.LogError("Error resovling hostname", ex); + Logger.LogError(ex, "Error resolving hostname"); } } } @@ -399,7 +399,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.LogError("Error in GetAllNetworkInterfaces", ex); + Logger.LogError(ex, "Error in GetAllNetworkInterfaces"); return new List(); } @@ -428,7 +428,7 @@ namespace Emby.Server.Implementations.Networking } catch (Exception ex) { - Logger.LogError("Error querying network interface", ex); + Logger.LogError(ex, "Error querying network interface"); return new List(); } diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs index 95ec2a672c..ce6fe6630b 100644 --- a/Emby.Server.Implementations/News/NewsEntryPoint.cs +++ b/Emby.Server.Implementations/News/NewsEntryPoint.cs @@ -67,7 +67,7 @@ namespace Emby.Server.Implementations.News } catch (Exception ex) { - _logger.LogError("Error downloading news", ex); + _logger.LogError(ex, "Error downloading news"); } } diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs index b268e00db9..04cf0632c3 100644 --- a/Emby.Server.Implementations/ResourceFileManager.cs +++ b/Emby.Server.Implementations/ResourceFileManager.cs @@ -59,7 +59,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - _logger.LogError("Error in Path.GetFullPath", ex); + _logger.LogError(ex, "Error in Path.GetFullPath"); } // Don't allow file system access outside of the source folder diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs index c77efb5cdb..46a7f1f277 100644 --- a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -89,11 +89,11 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (HttpException ex) { - _logger.LogError("Error downloading {0}", ex, package.name); + _logger.LogError(ex, "Error downloading {name}", package.name); } catch (IOException ex) { - _logger.LogError("Error updating {0}", ex, package.name); + _logger.LogError(ex, "Error updating {name}", package.name); } // Update progress diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 93e02063b7..7c2ce4af3a 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.LogError("Error deserializing {0}", ex, path); + Logger.LogError(ex, "Error deserializing {path}", path); } _readFromFile = true; } @@ -436,7 +436,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.LogError("Error", ex); + Logger.LogError(ex, "Error"); failureException = ex; @@ -669,7 +669,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.LogError("Error calling CancellationToken.Cancel();", ex); + Logger.LogError(ex, "Error calling CancellationToken.Cancel();"); } } var task = _currentTask; @@ -691,7 +691,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.LogError("Error calling Task.WaitAll();", ex); + Logger.LogError(ex, "Error calling Task.WaitAll();"); } } @@ -704,7 +704,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } catch (Exception ex) { - Logger.LogError("Error calling CancellationToken.Dispose();", ex); + Logger.LogError(ex, "Error calling CancellationToken.Dispose();"); } } if (wassRunning) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs index efadd71111..c60f59ce47 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteCacheFileTask.cs @@ -132,11 +132,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError("Error deleting directory {0}", ex, directory); + _logger.LogError(ex, "Error deleting directory {path}", directory); } catch (IOException ex) { - _logger.LogError("Error deleting directory {0}", ex, directory); + _logger.LogError(ex, "Error deleting directory {path}", directory); } } } @@ -150,11 +150,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } catch (UnauthorizedAccessException ex) { - _logger.LogError("Error deleting file {0}", ex, path); + _logger.LogError(ex, "Error deleting file {path}", path); } catch (IOException ex) { - _logger.LogError("Error deleting file {0}", ex, path); + _logger.LogError(ex, "Error deleting file {path}", path); } } diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index d2c6ed33ba..228d511ce6 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Security } catch (Exception ex) { - Logger.LogError("Error migrating authentication database", ex); + Logger.LogError(ex, "Error migrating authentication database"); } } diff --git a/Emby.Server.Implementations/Security/PluginSecurityManager.cs b/Emby.Server.Implementations/Security/PluginSecurityManager.cs index aa0f390307..2b1494c397 100644 --- a/Emby.Server.Implementations/Security/PluginSecurityManager.cs +++ b/Emby.Server.Implementations/Security/PluginSecurityManager.cs @@ -150,18 +150,15 @@ namespace Emby.Server.Implementations.Security SaveAppStoreInfo(parameters); throw; } - catch (HttpException e) + catch (HttpException ex) { - _logger.LogError("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT"); - if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired) - { - } throw new Exception("Error registering store sale"); } - catch (Exception e) + catch (Exception ex) { - _logger.LogError("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT"); + _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT"); SaveAppStoreInfo(parameters); //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually. throw new Exception("Error registering store sale"); diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 222ec7dd05..8cacc1124d 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.LogError("Error in OnMessageReceived", ex); + _logger.LogError(ex, "Error in OnMessageReceived"); } } } @@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.LogError("Error receiving udp message", ex); + _logger.LogError(ex, "Error receiving udp message"); } } @@ -193,7 +193,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.LogError("Error receiving udp message", ex); + _logger.LogError(ex, "Error receiving udp message"); } BeginReceive(); @@ -224,7 +224,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.LogError("Error handling UDP message", ex); + _logger.LogError(ex, "Error handling UDP message"); } } @@ -274,7 +274,7 @@ namespace Emby.Server.Implementations.Udp { await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false); - _logger.LogInformation("Udp message sent to {0}", remoteEndPoint); + _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint); } catch (OperationCanceledException) { @@ -282,7 +282,7 @@ namespace Emby.Server.Implementations.Udp } catch (Exception ex) { - _logger.LogError("Error sending message to {0}", ex, remoteEndPoint); + _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint); } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index f864b079ab..b4d18b69cf 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -499,7 +499,7 @@ namespace Emby.Server.Implementations.Updates } catch (Exception ex) { - _logger.LogError("Package installation failed", ex); + _logger.LogError(ex, "Package installation failed"); lock (CurrentInstallations) { @@ -610,9 +610,9 @@ namespace Emby.Server.Implementations.Updates _fileSystem.WriteAllText(target + ".ver", package.versionStr); } } - catch (IOException e) + catch (IOException ex) { - _logger.LogError("Error attempting to move file from {0} to {1}", e, tempFile, target); + _logger.LogError(ex, "Error attempting to move file from {TempFile} to {TargetFile}", tempFile, target); throw; } @@ -620,10 +620,10 @@ namespace Emby.Server.Implementations.Updates { _fileSystem.DeleteFile(tempFile); } - catch (IOException e) + catch (IOException ex) { // Don't fail because of this - _logger.LogError("Error deleting temp file {0]", e, tempFile); + _logger.LogError(ex, "Error deleting temp file {TempFile}", tempFile); } } diff --git a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs index bbcd1eed35..d96c391fb0 100644 --- a/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs +++ b/Emby.XmlTv/Emby.XmlTv/Classes/XmlTvReader.cs @@ -87,7 +87,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(id)) { - //LLogError("No id found for channel row"); + // LogError("No id found for channel row"); // Log.Error(" channel#{0} doesnt contain an id", iChannel); return null; } @@ -130,7 +130,7 @@ namespace Emby.XmlTv.Classes if (string.IsNullOrEmpty(result.DisplayName)) { - //LLogError("No display-name found for channel {0}", id); + // LogError("No display-name found for channel {0}", id); return null; } diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index b51bdf6fd5..ed0a0c81a9 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -147,7 +147,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.LogError("Error deleting encoded media cache", ex); + Logger.LogError(ex, "Error deleting encoded media cache"); } } @@ -557,7 +557,7 @@ namespace MediaBrowser.Api { try { - Logger.LogInformation("Stopping ffmpeg process with q command for {0}", job.Path); + Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path); //process.Kill(); process.StandardInput.WriteLine("q"); @@ -565,13 +565,13 @@ namespace MediaBrowser.Api // Need to wait because killing is asynchronous if (!process.WaitForExit(5000)) { - Logger.LogInformation("Killing ffmpeg process for {0}", job.Path); + Logger.LogInformation("Killing ffmpeg process for {path}", job.Path); process.Kill(); } } catch (Exception ex) { - Logger.LogError("Error killing transcoding job for {0}", ex, job.Path); + Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path); } } } @@ -589,7 +589,7 @@ namespace MediaBrowser.Api } catch (Exception ex) { - Logger.LogError("Error closing live stream for {0}", ex, job.Path); + Logger.LogError(ex, "Error closing live stream for {path}", job.Path); } } } @@ -620,15 +620,15 @@ namespace MediaBrowser.Api { } - catch (IOException) + catch (IOException ex) { - //Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); DeletePartialStreamFiles(path, jobType, retryCount + 1, 500); } - catch + catch (Exception ex) { - //Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); } } @@ -670,7 +670,7 @@ namespace MediaBrowser.Api catch (IOException ex) { e = ex; - //Logger.LogError("Error deleting HLS file {0}", ex, file); + Logger.LogError(ex, "Error deleting HLS file {path}", file); } } diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index 28a4245123..17c6d5dc5e 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -362,7 +362,7 @@ namespace MediaBrowser.Api.Images } catch (Exception ex) { - Logger.LogError("Error getting image information for {0}", ex, info.Path); + Logger.LogError(ex, "Error getting image information for {path}", info.Path); return null; } diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index cf5014328f..ecf3eb7dbd 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -1001,7 +1001,7 @@ namespace MediaBrowser.Api.Library } catch (Exception ex) { - Logger.LogError("Error refreshing library", ex); + Logger.LogError(ex, "Error refreshing library"); } }); } diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 37cc8d2d76..af56f63826 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -278,7 +278,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - Logger.LogError("Error starting ffmpeg", ex); + Logger.LogError(ex, "Error starting ffmpeg"); ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state); @@ -372,7 +372,7 @@ namespace MediaBrowser.Api.Playback //} //catch (Exception ex) //{ - // Logger.LogError("Error disposing ffmpeg.", ex); + // Logger.LogError(ex, "Error disposing ffmpeg."); //} } diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 7dda91e5a9..5361e313cb 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -367,7 +367,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (IOException ex) { - Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); var task = Task.Delay(100); Task.WaitAll(task); @@ -375,7 +375,7 @@ namespace MediaBrowser.Api.Playback.Hls } catch (Exception ex) { - Logger.LogError("Error deleting partial stream file(s) {0}", ex, path); + Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); } } diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs index 981a4725d1..67fb04d0c2 100644 --- a/MediaBrowser.Api/Playback/StreamState.cs +++ b/MediaBrowser.Api/Playback/StreamState.cs @@ -162,7 +162,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.LogError("Error disposing log stream", ex); + _logger.LogError(ex, "Error disposing log stream"); } LogFileStream = null; @@ -179,7 +179,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.LogError("Error disposing TranscodingThrottler", ex); + _logger.LogError(ex, "Error disposing TranscodingThrottler"); } TranscodingThrottler = null; @@ -196,7 +196,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.LogError("Error closing media source", ex); + _logger.LogError(ex, "Error closing media source"); } } } diff --git a/MediaBrowser.Api/Playback/TranscodingThrottler.cs b/MediaBrowser.Api/Playback/TranscodingThrottler.cs index 47f1f777af..5852852f69 100644 --- a/MediaBrowser.Api/Playback/TranscodingThrottler.cs +++ b/MediaBrowser.Api/Playback/TranscodingThrottler.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.LogError("Error pausing transcoding", ex); + _logger.LogError(ex, "Error pausing transcoding"); } } } @@ -78,7 +78,7 @@ namespace MediaBrowser.Api.Playback { if (_isPaused) { - _logger.LogDebug("Sending unpause command to ffmpeg"); + _logger.LogDebug("Sending resume command to ffmpeg"); try { @@ -87,7 +87,7 @@ namespace MediaBrowser.Api.Playback } catch (Exception ex) { - _logger.LogError("Error unpausing transcoding", ex); + _logger.LogError(ex, "Error resuming transcoding"); } } } @@ -110,11 +110,11 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); + _logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap); return false; } - //_logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); + _logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap); return true; } @@ -135,21 +135,21 @@ namespace MediaBrowser.Api.Playback if (gap < targetGap) { - //_logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + _logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return false; } - //_logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); + _logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded); return true; } - catch + catch (Exception ex) { - //_logger.LogError("Error getting output size"); + _logger.LogError(ex, "Error getting output size"); return false; } } - //_logger.LogDebug("No throttle data for " + path); + _logger.LogDebug("No throttle data for " + path); return false; } diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs index 33e6b20207..1f1bb36144 100644 --- a/MediaBrowser.Api/PluginService.cs +++ b/MediaBrowser.Api/PluginService.cs @@ -8,13 +8,13 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Services; using MediaBrowser.Common.Plugins; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api { @@ -230,9 +230,9 @@ namespace MediaBrowser.Api .ToArray(); } } - catch + catch (Exception ex) { - //Logger.LogError("Error getting plugin list", ex); + Logger.LogError(ex, "Error getting plugin list"); // Play it safe here if (requireAppStoreEnabled) { diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index 9a149dc923..0e5b0a9640 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -278,7 +278,7 @@ namespace MediaBrowser.Api.Subtitles } catch (Exception ex) { - Logger.LogError("Error downloading subtitles", ex); + Logger.LogError(ex, "Error downloading subtitles"); } }); diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs index 96d0fcae89..04a2270e3d 100644 --- a/MediaBrowser.Common/Events/EventHelper.cs +++ b/MediaBrowser.Common/Events/EventHelper.cs @@ -28,7 +28,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.LogError("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } }); } @@ -54,7 +54,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.LogError("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } }); } @@ -77,7 +77,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.LogError("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } } } @@ -100,7 +100,7 @@ namespace MediaBrowser.Common.Events } catch (Exception ex) { - logger.LogError("Error in event handler", ex); + logger.LogError(ex, "Error in event handler"); } } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 9ba80da698..6393a9f193 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1414,7 +1414,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.LogError("Error refreshing owned items for {0}", ex, Path ?? Name); + Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name); } } diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index dbec03a212..7292b166a0 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -105,7 +105,7 @@ namespace MediaBrowser.Controller.Entities } catch (Exception ex) { - Logger.LogError("Error loading library options", ex); + Logger.LogError(ex, "Error loading library options"); return new LibraryOptions(); } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index e9352ce400..dbe30f9a51 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -303,7 +303,7 @@ namespace MediaBrowser.Controller.Entities var id = child.Id; if (dictionary.ContainsKey(id)) { - Logger.LogError("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}", + Logger.LogError("Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}", Path ?? Name, child.Path ?? child.Name); } diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 6d5126a445..b50a12d520 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -259,10 +259,9 @@ namespace MediaBrowser.Controller.Entities { return _libraryManager.GetGenre(i); } - catch + catch (Exception ex) { - // Full exception logged at lower levels - _logger.LogError("Error getting genre"); + _logger.LogError(ex, "Error getting genre"); return null; } @@ -383,10 +382,9 @@ namespace MediaBrowser.Controller.Entities { return _libraryManager.GetGenre(i); } - catch + catch (Exception ex) { - // Full exception logged at lower levels - _logger.LogError("Error getting genre"); + _logger.LogError(ex, "Error getting genre"); return null; } diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs index 37d507753c..c0cf51ab24 100644 --- a/MediaBrowser.Controller/IO/FileData.cs +++ b/MediaBrowser.Controller/IO/FileData.cs @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.IO } catch (Exception ex) { - logger.LogError("Error resolving shortcut from {0}", ex, fullName); + logger.LogError(ex, "Error resolving shortcut from {path}", fullName); } } else if (flattenFolderDepth > 0 && isDirectory) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 3ec4e3bb7b..c8c2367e68 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -727,7 +727,6 @@ namespace MediaBrowser.Controller.MediaEncoding return count; } - protected void DisposeIsoMount() { if (IsoMount != null) diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index bac7e0184c..5abbadcc72 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -232,7 +232,7 @@ namespace MediaBrowser.Controller.Net } catch (Exception ex) { - Logger.LogError("Error sending web socket message {0}", ex, Name); + Logger.LogError(ex, "Error sending web socket message {Name}", Name); DisposeConnection(tuple); } } diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index 65ff43cf95..98848a4402 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -337,7 +337,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.LogError("Error reporting playback progress", ex); + _logger.LogError(ex, "Error reporting playback progress"); } } @@ -379,7 +379,7 @@ namespace MediaBrowser.Controller.Session } catch (Exception ex) { - _logger.LogError("Error disposing session controller", ex); + _logger.LogError(ex, "Error disposing session controller"); } } } diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 4e7a7a1685..9666c82661 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -135,7 +135,7 @@ namespace MediaBrowser.LocalMetadata.Savers } catch (Exception ex) { - Logger.LogError("Error setting hidden attribute on {0} - {1}", path, ex.Message); + Logger.LogError(ex, "Error setting hidden attribute on {path}", path); } } diff --git a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs index 1fd34c8fdf..187f350b8e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs @@ -124,7 +124,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - Logger.LogError("Error starting ffmpeg", ex); + Logger.LogError(ex, "Error starting ffmpeg"); OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob); @@ -179,9 +179,9 @@ namespace MediaBrowser.MediaEncoding.Encoder isSuccesful = exitCode == 0; } - catch + catch (Exception ex) { - Logger.LogError("FFMpeg exited with an error."); + Logger.LogError(ex, "FFMpeg exited with an error."); } if (isSuccesful && !job.IsCancelled) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 9653e561c0..fb131f304c 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { if (logOutput) { - _logger.LogError("Error validating encoder", ex); + _logger.LogError(ex, "Error validating encoder"); } } @@ -78,9 +78,9 @@ namespace MediaBrowser.MediaEncoding.Encoder { output = GetProcessOutput(encoderAppPath, "-decoders"); } - catch (Exception ) + catch (Exception ex) { - //_logger.LogError("Error detecting available decoders", ex); + _logger.LogError(ex, "Error detecting available decoders"); } var found = new List(); @@ -187,7 +187,7 @@ namespace MediaBrowser.MediaEncoding.Encoder RedirectStandardOutput = true }); - _logger.LogInformation("Running {0} {1}", path, arguments); + _logger.LogInformation("Running {path} {arguments}", path, arguments); using (process) { @@ -199,16 +199,16 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch { - _logger.LogInformation("Killing process {0} {1}", path, arguments); + _logger.LogInformation("Killing process {path} {arguments}", path, arguments); // Hate having to do this try { process.Kill(); } - catch (Exception ex1) + catch (Exception ex) { - _logger.LogError("Error killing process", ex1); + _logger.LogError(ex, "Error killing process"); } throw; diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs index dcaf4a2b17..e97898ac53 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs @@ -81,7 +81,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.LogError("Error disposing log stream", ex); + _logger.LogError(ex, "Error disposing log stream"); } LogFileStream = null; @@ -98,7 +98,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.LogError("Error closing media source", ex); + _logger.LogError(ex, "Error closing media source"); } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs index 2f0161962e..d2cf7f3950 100644 --- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs +++ b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs @@ -72,12 +72,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (HttpException ex) { // Don't let the server crash because of this - _logger.LogError("Error downloading ffmpeg font files", ex); + _logger.LogError(ex, "Error downloading ffmpeg font files"); } catch (Exception ex) { // Don't let the server crash because of this - _logger.LogError("Error writing ffmpeg font files", ex); + _logger.LogError(ex, "Error writing ffmpeg font files"); } } @@ -103,7 +103,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.LogError("Error copying file", ex); + _logger.LogError(ex, "Error copying file"); } } @@ -127,7 +127,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { // The core can function without the font file, so handle this - _logger.LogError("Failed to download ffmpeg font file from {0}", ex, url); + _logger.LogError(ex, "Failed to download ffmpeg font file from {url}", url); } } @@ -145,12 +145,12 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (IOException ex) { // Log this, but don't let it fail the operation - _logger.LogError("Error deleting temp file {0}", ex, tempFile); + _logger.LogError(ex, "Error deleting temp file {path}", tempFile); } } private void Extract7zArchive(string archivePath, string targetPath) { - _logger.LogInformation("Extracting {0} to {1}", archivePath, targetPath); + _logger.LogInformation("Extracting {ArchivePath} to {TargetPath}", archivePath, targetPath); _zipClient.ExtractAllFrom7z(archivePath, targetPath, true); } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 4cd66e5ced..a661d76917 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -102,8 +102,6 @@ namespace MediaBrowser.MediaEncoding.Encoder _originalFFMpegPath = ffMpegPath; _hasExternalEncoder = hasExternalEncoder; - - SetEnvironmentVariable(); } private readonly object _logLock = new object(); @@ -117,7 +115,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.LogError("Error setting FFREPORT environment variable", ex); + _logger.LogError(ex, "Error setting FFREPORT environment variable"); } } } @@ -132,31 +130,11 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - //_logger.LogError("Error setting FFREPORT environment variable", ex); + _logger.LogError(ex, "Error setting FFREPORT environment variable"); } } } - private void SetEnvironmentVariable() - { - try - { - //_environmentInfo.SetProcessEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32"); - } - catch (Exception ex) - { - _logger.LogError("Error setting FFREPORT environment variable", ex); - } - try - { - //_environmentInfo.SetUserEnvironmentVariable("FFREPORT", "file=program-YYYYMMDD-HHMMSS.txt:level=32"); - } - catch (Exception ex) - { - _logger.LogError("Error setting FFREPORT environment variable", ex); - } - } - public string EncoderLocationType { get @@ -649,9 +627,9 @@ namespace MediaBrowser.MediaEncoding.Encoder { throw; } - catch + catch (Exception ex) { - _logger.LogError("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); + _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument); } } @@ -999,7 +977,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.LogError("Error in WaitForExit", ex); + _logger.LogError(ex, "Error in WaitForExit"); } try @@ -1010,7 +988,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } catch (Exception ex) { - _logger.LogError("Error killing process", ex); + _logger.LogError(ex, "Error killing process"); } } diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index c3cf61dc1e..d0ccef2f80 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1351,11 +1351,11 @@ namespace MediaBrowser.MediaEncoding.Probing { video.Timestamp = GetMpegTimestamp(video.Path); - _logger.LogDebug("Video has {0} timestamp", video.Timestamp); + _logger.LogDebug("Video has {timestamp} timestamp", video.Timestamp); } catch (Exception ex) { - _logger.LogError("Error extracting timestamp info from {0}", ex, video.Path); + _logger.LogError(ex, "Error extracting timestamp info from {path}", video.Path); video.Timestamp = null; } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index a3e0f89a97..43f7753927 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -431,7 +431,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.LogError("Error starting ffmpeg", ex); + _logger.LogError(ex, "Error starting ffmpeg"); throw; } @@ -448,7 +448,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.LogError("Error killing subtitle conversion process", ex); + _logger.LogError(ex, "Error killing subtitle conversion process"); } } @@ -471,7 +471,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (IOException ex) { - _logger.LogError("Error deleting converted subtitle {0}", ex, outputPath); + _logger.LogError(ex, "Error deleting converted subtitle {0}", outputPath); } } } @@ -561,7 +561,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.LogError("Error starting ffmpeg", ex); + _logger.LogError(ex, "Error starting ffmpeg"); throw; } @@ -578,7 +578,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (Exception ex) { - _logger.LogError("Error killing subtitle extraction process", ex); + _logger.LogError(ex, "Error killing subtitle extraction process"); } } @@ -603,7 +603,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } catch (IOException ex) { - _logger.LogError("Error deleting extracted subtitle {0}", ex, outputPath); + _logger.LogError(ex, "Error deleting extracted subtitle {0}", outputPath); } } else if (!_fileSystem.FileExists(outputPath)) diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index c1cb07a0e7..6790f9b331 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -211,7 +211,7 @@ namespace MediaBrowser.Providers.Manager if (retry) { - _logger.LogError("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message); + _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath); } else { @@ -271,7 +271,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error setting hidden attribute on {0} - {1}", path, ex.Message); + _logger.LogError(ex, "Error setting hidden attribute on {0}", path); } } diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index a11ccd6d6c..fc30374b3a 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -173,7 +173,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.LogError("Error in {0}", ex, provider.Name); + _logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -310,7 +310,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { result.ErrorMessage = ex.Message; - _logger.LogError("Error in {0}", ex, provider.Name); + _logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -577,7 +577,7 @@ namespace MediaBrowser.Providers.Manager } catch (IOException ex) { - _logger.LogError("Error examining images", ex); + _logger.LogError(ex, "Error examining images"); } } @@ -586,7 +586,7 @@ namespace MediaBrowser.Providers.Manager } catch (HttpException ex) { - // Sometimes providers send back bad url's. Just move onto the next image + // Sometimes providers send back bad urls. Just move onto the next image if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { continue; diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 5d607f5d67..e26004923d 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.LogError("Error getting file {0}", ex, path); + Logger.LogError(ex, "Error getting file {path}", path); return null; } } @@ -96,7 +96,7 @@ namespace MediaBrowser.Providers.Manager localImagesFailed = true; if (!(item is IItemByName)) { - Logger.LogError("Error validating images for {0}", ex, item.Path ?? item.Name ?? "Unknown name"); + Logger.LogError(ex, "Error validating images for {0}", item.Path ?? item.Name ?? "Unknown name"); } } @@ -268,7 +268,7 @@ namespace MediaBrowser.Providers.Manager // } // catch (Exception ex) // { - // Logger.LogError("Error in AddPersonImage", ex); + // Logger.LogError(ex, "Error in AddPersonImage"); // } //} @@ -767,7 +767,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.LogError("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); // If a local provider fails, consider that a failure refreshResult.ErrorMessage = ex.Message; @@ -839,7 +839,7 @@ namespace MediaBrowser.Providers.Manager catch (Exception ex) { refreshResult.ErrorMessage = ex.Message; - Logger.LogError("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -891,7 +891,7 @@ namespace MediaBrowser.Providers.Manager { refreshResult.Failures++; refreshResult.ErrorMessage = ex.Message; - Logger.LogError("Error in {0}", ex, provider.Name); + Logger.LogError(ex, "Error in {provider}", provider.Name); } } @@ -951,7 +951,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.LogError("Error in {0}.HasChanged", ex, changeMonitor.GetType().Name); + Logger.LogError(ex, "Error in {0}.HasChanged", changeMonitor.GetType().Name); return false; } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index e3b23ce337..8a9aae1175 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -144,7 +144,7 @@ namespace MediaBrowser.Providers.Manager return service.RefreshMetadata(item, options, cancellationToken); } - _logger.LogError("Unable to find a metadata service for item of type " + item.GetType().Name); + _logger.LogError("Unable to find a metadata service for item of type {TypeName}", item.GetType().Name); return Task.FromResult(ItemUpdateType.None); } @@ -250,7 +250,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError(ex, "{0} failed in GetImageInfos for type {1}", provider.GetType().Name, item.GetType().Name); return new List(); } } @@ -400,7 +400,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name); + _logger.LogError(ex, "{0} failed in Supports for type {1}", provider.GetType().Name, item.GetType().Name); return false; } } @@ -642,7 +642,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error in {0} GetSavePath", ex, saver.Name); + _logger.LogError(ex, "Error in {0} GetSavePath", saver.Name); continue; } @@ -653,7 +653,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error in metadata saver", ex); + _logger.LogError(ex, "Error in metadata saver"); } finally { @@ -668,7 +668,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error in metadata saver", ex); + _logger.LogError(ex, "Error in metadata saver"); } } } @@ -731,7 +731,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error in {0}.IsEnabledFor", ex, saver.Name); + _logger.LogError(ex, "Error in {0}.IsEnabledFor", saver.Name); return false; } } @@ -876,7 +876,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error in {0}.Suports", ex, i.GetType().Name); + _logger.LogError(ex, "Error in {0}.Suports", i.GetType().Name); return false; } }); @@ -1070,7 +1070,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error refreshing item", ex); + _logger.LogError(ex, "Error refreshing item"); } } @@ -1147,7 +1147,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - _logger.LogError("Error refreshing library", ex); + _logger.LogError(ex, "Error refreshing library"); } } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 4dc3849d9f..c2fe392ab2 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -342,7 +342,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.LogError("Error getting BDInfo", ex); + _logger.LogError(ex, "Error getting BDInfo"); return null; } } diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs index 8d5f203170..4c66f2b0af 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs @@ -176,7 +176,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.LogError("Error downloading subtitles", ex); + _logger.LogError(ex, "Error downloading subtitles"); } return false; diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs index 4fa6a05219..81abedeb95 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs @@ -148,7 +148,7 @@ namespace MediaBrowser.Providers.MediaInfo } catch (Exception ex) { - _logger.LogError("Error downloading subtitles for {0}", ex, video.Path); + _logger.LogError(ex, "Error downloading subtitles for {Path}", video.Path); } // Update progress diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs index da0f40a5a1..0dbc433136 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs @@ -774,7 +774,7 @@ namespace MediaBrowser.Providers.Music } catch (Exception ex) { - _logger.LogError("Error getting music brainz info", ex); + _logger.LogError(ex, "Error getting music brainz info"); } } } diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 2006067b31..2cf737511d 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -101,7 +101,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.LogError("Error downloading subtitles from {0}", ex, provider.Name); + _logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name); } } return new RemoteSubtitleInfo[] { }; @@ -119,7 +119,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - _logger.LogError("Error downloading subtitles from {0}", ex, i.Name); + _logger.LogError(ex, "Error downloading subtitles from {0}", i.Name); return new RemoteSubtitleInfo[] { }; } }); diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs index a943e49c09..1cb06efdfe 100644 --- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Providers.TV } catch (Exception ex) { - Logger.LogError("Error in DummySeasonProvider", ex); + Logger.LogError(ex, "Error in DummySeasonProvider"); } } diff --git a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs index 8b09ee2fcf..217dab663c 100644 --- a/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs +++ b/MediaBrowser.Providers/TV/TheMovieDb/MovieDbSeasonProvider.cs @@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.LogError("No metadata found for {0}", seasonNumber.Value); + _logger.LogError(ex, "No metadata found for {0}", seasonNumber.Value); if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs index 6bad5b9257..8bab595958 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbPrescanTask.cs @@ -358,7 +358,7 @@ namespace MediaBrowser.Providers.TV } catch (HttpException ex) { - _logger.LogError("Error updating tvdb series id {0}, language {1}", ex, seriesId, language); + _logger.LogError(ex, "Error updating tvdb series id {ID}, language {Language}", seriesId, language); // Already logged at lower levels, but don't fail the whole operation, unless timed out // We have to fail this to make it run again otherwise new episode data could potentially be missing diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index 9c6ee4dd22..cf61b79fe8 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -270,7 +270,7 @@ namespace MediaBrowser.Server.Mono } catch (Exception ex) { - _logger.LogError("Error getting unix name", ex); + _logger.LogError(ex, "Error getting unix name"); } _unixName = uname; } diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs index e8557d1f99..993863e8c8 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs @@ -114,7 +114,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.LogError("Error processing request", ex); + _logger.LogError(ex, "Error processing request"); httpReq = httpReq ?? GetRequest(context); return ErrorHandler(ex, httpReq, true, true); @@ -176,7 +176,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.LogError("AcceptWebSocketAsync error", ex); + _logger.LogError(ex, "AcceptWebSocketAsync error"); ctx.Response.StatusCode = 500; ctx.Response.Close(); } @@ -206,7 +206,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.LogError("Error closing web socket response", ex); + _logger.LogError(ex, "Error closing web socket response"); } } diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs index d299c64ef0..08fa4cbd62 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs +++ b/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs @@ -112,7 +112,7 @@ namespace EmbyServer.SocketSharp } catch (Exception ex) { - _logger.LogError("Error in HttpListenerResponseWrapper: " + ex.Message, ex); + _logger.LogError(ex, "Error in HttpListenerResponseWrapper"); } } } diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index 0327929a94..58d02ef044 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -245,7 +245,7 @@ namespace MediaBrowser.WebDashboard.Api } catch (Exception ex) { - _logger.LogError("Error getting plugin information from {0}", ex, p.GetType().Name); + _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name); return null; } }) diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index 7461e952de..dac3f49676 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -72,7 +72,7 @@ namespace MediaBrowser.XbmcMetadata } catch (Exception ex) { - _logger.LogError("Error saving metadata for {0}", ex, item.Path ?? item.Name); + _logger.LogError(ex, "Error saving metadata for {path}", item.Path ?? item.Name); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 27f128fcec..e6b4eea1c6 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -81,7 +81,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } catch (Exception ex) { - Logger.LogError("Error parsing set node", ex); + Logger.LogError(ex, "Error parsing set node"); } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 74e7143625..131ce80d55 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -230,7 +230,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - Logger.LogError("Error setting hidden attribute on {path} - {ex}", path, ex.Message); + Logger.LogError(ex, "Error setting hidden attribute on {path}", path); } } @@ -283,7 +283,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (XmlException ex) { - Logger.LogError("Error reading existng nfo", ex); + Logger.LogError(ex, "Error reading existing nfo"); } writer.WriteEndElement(); @@ -1000,7 +1000,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } catch (Exception ex) { - logger.LogError("Error reading existing xml tags from {0}.", ex, path); + logger.LogError(ex, "Error reading existing xml tags from {path}.", path); return; } diff --git a/Mono.Nat/Pmp/PmpNatDevice.cs b/Mono.Nat/Pmp/PmpNatDevice.cs index 99d030207b..fbf3032d47 100644 --- a/Mono.Nat/Pmp/PmpNatDevice.cs +++ b/Mono.Nat/Pmp/PmpNatDevice.cs @@ -198,7 +198,7 @@ namespace Mono.Nat.Pmp } catch (Exception ex) { - _logger.LogError("Error in CreatePortMapListen", ex); + _logger.LogError(ex, "Error in CreatePortMapListen"); return; } } diff --git a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs index e9e47a91e9..bcf358d1ca 100644 --- a/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs +++ b/Mono.Nat/Upnp/Searchers/UpnpSearcher.cs @@ -90,7 +90,7 @@ namespace Mono.Nat } catch (Exception ex) { - _logger.LogError("Error decoding device response", ex); + _logger.LogError(ex, "Error decoding device response"); } } diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 921ef3e514..65ec0ca714 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -131,7 +131,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError("Error in BeginListeningForBroadcasts", ex); + _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); } } } @@ -197,7 +197,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString()); + _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString()); } } @@ -376,7 +376,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address); + _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address); } } } diff --git a/SocketHttpListener/Net/HttpEndPointListener.cs b/SocketHttpListener/Net/HttpEndPointListener.cs index 867012d051..fb093314c8 100644 --- a/SocketHttpListener/Net/HttpEndPointListener.cs +++ b/SocketHttpListener/Net/HttpEndPointListener.cs @@ -173,7 +173,7 @@ namespace SocketHttpListener.Net { HttpEndPointListener epl = (HttpEndPointListener)acceptEventArg.UserToken; - epl._logger.LogError("Error in socket.AcceptAsync", ex); + epl._logger.LogError(ex, "Error in socket.AcceptAsync"); } } @@ -238,7 +238,7 @@ namespace SocketHttpListener.Net } catch (Exception ex) { - epl._logger.LogError("Error in ProcessAccept", ex); + epl._logger.LogError(ex, "Error in ProcessAccept"); TryClose(accepted); epl.Accept(); From 79d18cf5a5fde7594eb17247f920a54d8978a81c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 20 Dec 2018 13:39:58 +0100 Subject: [PATCH 022/125] Clean up some catch statements --- Emby.Dlna/Didl/DidlBuilder.cs | 4 +- Emby.Dlna/DlnaManager.cs | 4 +- Emby.Dlna/PlayTo/Device.cs | 4 +- .../ImageMagickEncoder.cs | 4 +- Emby.Drawing/ImageProcessor.cs | 10 +-- .../IsoMounter/LinuxIsoManager.cs | 72 ++++++++----------- .../ApplicationHost.cs | 2 +- Emby.Server.Implementations/Dto/DtoService.cs | 2 +- .../EntryPoints/ExternalPortForwarding.cs | 1 + .../IO/SharpCifs/Config.cs | 2 +- .../IO/SharpCifs/Dcerpc/DcerpcHandle.cs | 2 +- .../IO/SharpCifs/Netbios/Name.cs | 2 +- .../IO/SharpCifs/Netbios/NameServiceClient.cs | 8 ++- .../IO/SharpCifs/Smb/NtlmContext.cs | 2 +- 14 files changed, 56 insertions(+), 63 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 6de35b8426..7af48ae17e 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -1070,9 +1070,9 @@ namespace Emby.Dlna.Didl { tag = _imageProcessor.GetImageCacheTag(item, type); } - catch + catch (Exception ex) { - + _logger.LogError(ex, "Error getting image cache tag"); } int? width = imageInfo.Width; diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index eae4f32716..48a33757be 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -198,7 +198,7 @@ namespace Emby.Dlna } catch (ArgumentException ex) { - _logger.LogError(ex, "Error evaluating regex pattern {0}", pattern); + _logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern); return false; } } @@ -324,7 +324,7 @@ namespace Emby.Dlna } catch (Exception ex) { - _logger.LogError(ex, "Error parsing profile file: {0}", path); + _logger.LogError(ex, "Error parsing profile file: {Path}", path); return null; } diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index a1df90ec03..13bed6b2fd 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -140,7 +140,7 @@ namespace Emby.Dlna.PlayTo } catch (Exception ex) { - _logger.LogError(ex, "Error updating device volume info for {0}", Properties.Name); + _logger.LogError(ex, "Error updating device volume info for {DeviceName}", Properties.Name); } } @@ -507,7 +507,7 @@ namespace Emby.Dlna.PlayTo if (_disposed) return; - //_logger.LogError(ex, "Error updating device info for {0}", Properties.Name); + _logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name); _connectFailureCount++; diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs index 6aac77cf4b..5de8ac383e 100644 --- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs +++ b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs @@ -101,9 +101,9 @@ namespace Emby.Drawing.ImageMagick wand.SaveImage(tmpPath); } } - catch + catch (Exception ex) { - //_logger.LogError(ex, "Error loading webp: "); + _logger.LogError(ex, "Error loading webp"); _webpAvailable = false; } } diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index c417f37854..6a67be56d1 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -646,16 +646,16 @@ namespace Emby.Drawing var cacheGuid = GetImageCacheTag(item, image, enhancers); // Enhance if we have enhancers - var ehnancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); + var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); - var ehnancedImagePath = ehnancedImageInfo.Item1; + var enhancedImagePath = enhancedImageInfo.Item1; // If the path changed update dateModified - if (!string.Equals(ehnancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { - var treatmentRequiresTransparency = ehnancedImageInfo.Item2; + var treatmentRequiresTransparency = enhancedImageInfo.Item2; - return new ValueTuple(ehnancedImagePath, _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath), treatmentRequiresTransparency); + return new ValueTuple(enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); } } catch (Exception ex) diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs index e6986ddcbe..faaed482a0 100644 --- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs +++ b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs @@ -260,35 +260,29 @@ namespace IsoMounter } ); - try { - + try + { process.Start(); //StreamReader outputReader = process.StandardOutput.; //StreamReader errorReader = process.StandardError; _logger.LogDebug( - "[{0}] Standard output from process is [{1}].", + "[{Name}] Standard output from process is [{Error}].", Name, process.StandardOutput.ReadToEnd() ); _logger.LogDebug( - "[{0}] Standard error from process is [{1}].", + "[{Name}] Standard error from process is [{Error}].", Name, process.StandardError.ReadToEnd() ); - - } catch (Exception ex) { - + } + catch (Exception ex) + { processFailed = true; - - _logger.LogDebug( - "[{0}] Unhandled exception executing command, exception is [{1}].", - Name, - ex.Message - ); - + _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name); } if (!processFailed && process.ExitCode == 0) { @@ -309,13 +303,13 @@ namespace IsoMounter if (!string.IsNullOrEmpty(isoPath)) { _logger.LogInformation( - "[{0}] Attempting to mount [{1}].", + "[{Name}] Attempting to mount [{Path}].", Name, isoPath ); _logger.LogDebug( - "[{0}] ISO will be mounted at [{1}].", + "[{Name}] ISO will be mounted at [{Path}].", Name, mountPoint ); @@ -326,11 +320,16 @@ namespace IsoMounter } - try { + try + { FileSystem.CreateDirectory(mountPoint); - } catch (UnauthorizedAccessException) { + } + catch (UnauthorizedAccessException) + { throw new IOException("Unable to create mount point(Permission denied) for " + isoPath); - } catch (Exception) { + } + catch (Exception) + { throw new IOException("Unable to create mount point for " + isoPath); } @@ -365,18 +364,13 @@ namespace IsoMounter Name ); - try { - + try + { FileSystem.DeleteDirectory(mountPoint, false); - - } catch (Exception ex) { - - _logger.LogInformation( - "[{0}] Unhandled exception removing mount point, exception is [{1}].", - Name, - ex.Message - ); - + } + catch (Exception ex) + { + _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name); } mountedISO = null; @@ -439,20 +433,14 @@ namespace IsoMounter } - try { - + try + { FileSystem.DeleteDirectory(mount.MountedPath, false); - - } catch (Exception ex) { - - _logger.LogInformation( - "[{0}] Unhandled exception removing mount point, exception is [{1}].", - Name, - ex.Message - ); - } - + catch (Exception ex) + { + _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name); + } } #endregion diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 888635c9d8..d4b740d712 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -2214,7 +2214,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogDebug("Ping test result to {0}. Success: {1} {2}", apiUrl, false, ex.Message); + Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false); _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); return false; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index e8d06ec002..7871d3fb3b 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -619,7 +619,7 @@ namespace Emby.Server.Implementations.Dto } catch (Exception ex) { - _logger.LogError(ex, "Error getting person {0}", c); + _logger.LogError(ex, "Error getting person {Name}", c); return null; } diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index a95e21e1c5..6cd867921f 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -166,6 +166,7 @@ namespace Emby.Server.Implementations.EntryPoints } catch (Exception ex) { + _logger.LogError(ex, "Error"); return; } diff --git a/Emby.Server.Implementations/IO/SharpCifs/Config.cs b/Emby.Server.Implementations/IO/SharpCifs/Config.cs index 3fd0e5bd64..324a9c494d 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Config.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Config.cs @@ -89,7 +89,7 @@ namespace SharpCifs { Runtime.GetBytesForString(string.Empty, DefaultOemEncoding); } - catch (Exception ex) + catch (Exception) { if (_log.Level >= 2) { diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs index 786b0ac122..e82af2b0cf 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs @@ -153,7 +153,7 @@ namespace SharpCifs.Dcerpc DcerpcMessage bind = new DcerpcBind(Binding, this); Sendrecv(bind); } - catch (IOException ioe) + catch (IOException) { State = 0; throw; diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs index 6c37d57a46..15ae494bea 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs @@ -130,7 +130,7 @@ namespace SharpCifs.Netbios { name = Runtime.GetStringForBytes(tmp, 0, length).Trim(); } - catch (Exception ex) + catch (Exception) { } diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs index 01700e64a5..0d7840a643 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs @@ -117,8 +117,9 @@ namespace SharpCifs.Netbios { Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255")); } - catch (Exception ex) + catch (Exception) { + } _sndBuf = new byte[SndBufSize]; @@ -302,7 +303,10 @@ namespace SharpCifs.Netbios } } - catch (TimeoutException) { } + catch (TimeoutException) + { + + } catch (Exception ex) { if (_log.Level > 2) diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs index 44266f9740..aa52ee1db8 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs @@ -192,7 +192,7 @@ namespace SharpCifs.Smb catch (Exception e) { throw new SmbException(e.Message, e); - } + } } default: From b1ccd6bad9904ab4fb2de02d71db0a7540b98479 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 28 Dec 2018 01:11:04 +0100 Subject: [PATCH 023/125] Fix build post GPL change --- .../ApplicationHost.cs | 10 +--- .../Library/ConnectManager.cs | 46 ------------------- .../Entities/Audio/MusicArtist.cs | 8 ++-- .../Entities/Audio/MusicGenre.cs | 5 +- MediaBrowser.Controller/Entities/BaseItem.cs | 9 ---- MediaBrowser.Controller/Entities/GameGenre.cs | 5 +- MediaBrowser.Controller/Entities/Genre.cs | 5 +- MediaBrowser.Controller/Entities/Person.cs | 5 +- MediaBrowser.Controller/Entities/Studio.cs | 5 +- .../Entities/TV/Episode.cs | 1 + MediaBrowser.Controller/Entities/Year.cs | 3 +- .../Net/BasePeriodicWebSocketListener.cs | 5 +- .../Providers/DirectoryService.cs | 3 -- 13 files changed, 19 insertions(+), 91 deletions(-) delete mode 100644 Emby.Server.Implementations/Library/ConnectManager.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d4b740d712..77edc8ea1a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -48,13 +48,11 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Chapters; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Connect; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; @@ -80,7 +78,6 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.News; @@ -117,6 +114,7 @@ using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certif using MediaBrowser.Controller.Authentication; using System.Diagnostics; using ServiceStack.Text.Jsv; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations { @@ -942,11 +940,7 @@ namespace Emby.Server.Implementations AuthenticationRepository = GetAuthenticationRepository(); RegisterSingleInstance(AuthenticationRepository); -<<<<<<< HEAD - UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); -======= - UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, () => ConnectManager, this, JsonSerializer, FileSystemManager, CryptographyProvider); ->>>>>>> Use Microsoft.Extensions.Logging abstraction + UserManager = new UserManager(LoggerFactory.CreateLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager, CryptographyProvider); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(this, Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager); diff --git a/Emby.Server.Implementations/Library/ConnectManager.cs b/Emby.Server.Implementations/Library/ConnectManager.cs deleted file mode 100644 index c05385673a..0000000000 --- a/Emby.Server.Implementations/Library/ConnectManager.cs +++ /dev/null @@ -1,46 +0,0 @@ -using MediaBrowser.Common.Events; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Connect; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Connect; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Events; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.Users; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Cryptography; -using MediaBrowser.Model.IO; -using MediaBrowser.Controller.Authentication; -using MediaBrowser.Controller.Security; -using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Session; -using MediaBrowser.Controller.Plugins; - -namespace Emby.Server.Implementations.Library -{ - public class ConnectManager : IConnectManager - { - public ConnectManager() - { - } - - } -} diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 82dece84b9..2774dc9443 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Users; @@ -9,9 +8,8 @@ using System.Linq; using MediaBrowser.Model.Serialization; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.Audio { @@ -245,7 +243,7 @@ namespace MediaBrowser.Controller.Entities.Audio var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index d60ce83ad4..ec68eaf8b9 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.Audio { @@ -119,7 +118,7 @@ namespace MediaBrowser.Controller.Entities.Audio var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 6393a9f193..e80fe33875 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1,11 +1,8 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Channels; -using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; @@ -16,23 +13,17 @@ using MediaBrowser.Model.Users; using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; - -using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Controller.IO; -using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging; diff --git a/MediaBrowser.Controller/Entities/GameGenre.cs b/MediaBrowser.Controller/Entities/GameGenre.cs index 63493ad4a4..ba178d3c32 100644 --- a/MediaBrowser.Controller/Entities/GameGenre.cs +++ b/MediaBrowser.Controller/Entities/GameGenre.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -102,7 +101,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 94a5984dfd..57ffe2744c 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -2,9 +2,8 @@ using MediaBrowser.Controller.Entities.Audio; using System; using System.Collections.Generic; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -114,7 +113,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index 64d7750942..5c35a7411b 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -1,11 +1,10 @@ using MediaBrowser.Controller.Providers; using System; using System.Collections.Generic; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -137,7 +136,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index 29f6175391..c076cd680a 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using MediaBrowser.Model.Serialization; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Extensions; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -115,7 +114,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index cdf0214d3d..3a3a902a35 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.Linq; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.TV { diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index 81e030cea1..8e3cd0b70d 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities { @@ -121,7 +122,7 @@ namespace MediaBrowser.Controller.Entities var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) { - Logger.Debug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); + Logger.LogDebug("{0} path has changed from {1} to {2}", GetType().Name, Path, newPath); return true; } return base.RequiresRefresh(); diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index 5abbadcc72..31ec149bf9 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Net; +using MediaBrowser.Model.Net; using MediaBrowser.Model.Threading; using System.Collections.Generic; using System.Globalization; @@ -9,8 +8,6 @@ using System.Threading.Tasks; using System.Threading; using System; using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Threading; namespace MediaBrowser.Controller.Net { diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 27d65a3e25..9bb2f5bedd 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -1,10 +1,7 @@ using Microsoft.Extensions.Logging; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.IO; using System.Linq; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.Providers From 88aa5da3545962170a6074de8a5d1e5f4dd57aad Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 28 Dec 2018 23:20:52 +0100 Subject: [PATCH 024/125] Fix build due to rebase --- Emby.Server.Implementations/Activity/ActivityRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index fcdcb0c2c2..91a4a5fd45 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -184,7 +184,7 @@ namespace Emby.Server.Implementations.Activity var whereTextWithoutPaging = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); if (startIndex.HasValue && startIndex.Value > 0) { @@ -199,7 +199,7 @@ namespace Emby.Server.Implementations.Activity var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses.ToArray(whereClauses.Count)); + " where " + string.Join(" AND ", whereClauses.ToArray()); commandText += whereText; @@ -244,7 +244,7 @@ namespace Emby.Server.Implementations.Activity result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); } - result.Items = list.ToArray(list.Count); + result.Items = list.ToArray(); return result; }, ReadTransactionMode); From bbe2ca412b215e4d0b7ac6744e004c448fc80854 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 12:27:28 +0100 Subject: [PATCH 025/125] Fix build error --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 77edc8ea1a..a4a24dda0a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -2066,7 +2066,7 @@ namespace Emby.Server.Implementations } catch(Exception ex) { - Logger.ErrorException("Error getting WAN Ip address information", ex); + Logger.LogError(ex, "Error getting WAN Ip address information"); } return null; } From 4c95aee52eda793d1e013164cc0fde9eb609f894 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 22:49:09 +0100 Subject: [PATCH 026/125] Fix logging in XmlTvListingsProvider --- .../LiveTv/Listings/XmlTvListingsProvider.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index a8609ce2da..4d7c7fef41 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -15,7 +15,7 @@ using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; +using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Implementations.LiveTv.Listings { @@ -58,7 +58,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings private async Task GetXml(string path, CancellationToken cancellationToken) { - _logger.Info("xmltv path: {0}", path); + _logger.LogInformation("xmltv path: {path}", path); if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { @@ -72,7 +72,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings return UnzipIfNeeded(path, cacheFile); } - _logger.Info("Downloading xmltv listings from {0}", path); + _logger.LogInformation("Downloading xmltv listings from {path}", path); string tempFile = await _httpClient.GetTempFile(new HttpRequestOptions { @@ -109,7 +109,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.ErrorException("Error extracting from gz file {0}", ex, file); + _logger.LogError(ex, "Error extracting from gz file {file}", file); } try @@ -119,7 +119,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings } catch (Exception ex) { - _logger.ErrorException("Error extracting from zip file {0}", ex, file); + _logger.LogError(ex, "Error extracting from zip file {file}", file); } } @@ -177,10 +177,10 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings } }*/ - _logger.Debug("Getting xmltv programs for channel {0}", channelId); + _logger.LogDebug("Getting xmltv programs for channel {id}", channelId); string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); - _logger.Debug("Opening XmlTvReader for {0}", path); + _logger.LogDebug("Opening XmlTvReader for {path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) @@ -273,7 +273,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { // In theory this should never be called because there is always only one lineup string path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false); - _logger.Debug("Opening XmlTvReader for {0}", path); + _logger.LogDebug("Opening XmlTvReader for {path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); IEnumerable results = reader.GetChannels(); @@ -285,7 +285,7 @@ namespace Jellyfin.Server.Implementations.LiveTv.Listings { // In theory this should never be called because there is always only one lineup string path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false); - _logger.Debug("Opening XmlTvReader for {0}", path); + _logger.LogDebug("Opening XmlTvReader for {path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); IEnumerable results = reader.GetChannels(); From cd251799a4f5d0d2ab811563227dc638c035d766 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 23:31:19 +0100 Subject: [PATCH 027/125] Change location of logging.json from to /config --- MediaBrowser.Server.Mono/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index cf61b79fe8..b8c29796dc 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -164,7 +164,7 @@ namespace MediaBrowser.Server.Mono } try { - string path = Path.Combine(_appPaths.ProgramDataPath, "logging.json"); + string path = Path.Combine(_appPaths.ConfigurationDirectoryPath, "logging.json"); if (!File.Exists(path)) { @@ -178,7 +178,7 @@ namespace MediaBrowser.Server.Mono } } var configuration = new ConfigurationBuilder() - .SetBasePath(_appPaths.ProgramDataPath) + .SetBasePath(_appPaths.ConfigurationDirectoryPath) .AddJsonFile("logging.json") .AddEnvironmentVariables("JELLYFIN_") .Build(); From 7d0ae2bca2a50518d8b3eacae8dac5fd9856f781 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 31 Dec 2018 15:34:27 +0100 Subject: [PATCH 028/125] Fix location log dir when failed to read configuration --- MediaBrowser.Server.Mono/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs index b8c29796dc..f512fc98e0 100644 --- a/MediaBrowser.Server.Mono/Program.cs +++ b/MediaBrowser.Server.Mono/Program.cs @@ -193,7 +193,7 @@ namespace MediaBrowser.Server.Mono Serilog.Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.File( - Path.Combine(logDir, "logs", "log_.log"), + Path.Combine(logDir, "log_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") .Enrich.FromLogContext() From d046c4f5f26353dcf5440cfbe53fb824ea17e1d8 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Tue, 1 Jan 2019 12:32:15 +0100 Subject: [PATCH 029/125] reenable udpserver for server discovery in apps etc. (#349) --- Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index f8e2d32ddf..730ced0554 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -45,9 +45,6 @@ namespace Emby.Server.Implementations.EntryPoints /// public void Run() { - // ToDo: Fix This - return; - var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory); try From cff0ece07329bbfa05fd22fbde444d09aaeb9a5c Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Tue, 1 Jan 2019 12:33:22 +0100 Subject: [PATCH 030/125] set EnableAnonymousUsageReporting to false to avoid log spam (#348) It's the default value for the setting, so it'll only affect new servers. If enabled, it'll send usage statistics to an endpoint that doesn't exist, which just clutters the console/logs. --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index cc12750352..5effba26be 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -221,7 +221,7 @@ namespace MediaBrowser.Model.Configuration HttpsPortNumber = DefaultHttpsPort; EnableHttps = true; EnableDashboardResponseCaching = true; - EnableAnonymousUsageReporting = true; + EnableAnonymousUsageReporting = false; EnableCaseSensitiveItemIds = true; EnableAutomaticRestart = true; From e094c45abb44ece2bf685087ca6326cb00c468a8 Mon Sep 17 00:00:00 2001 From: Joshua Boniface Date: Tue, 1 Jan 2019 13:33:44 -0500 Subject: [PATCH 031/125] Add copyright from upstream projects --- RSSDP/LICENSE | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 RSSDP/LICENSE diff --git a/RSSDP/LICENSE b/RSSDP/LICENSE new file mode 100644 index 0000000000..aabeb93af0 --- /dev/null +++ b/RSSDP/LICENSE @@ -0,0 +1,4 @@ +RSSDP + +Copyright (c) 2015 Troy Willmot +Copyright (c) 2015-2018 Luke Pulverenti From 75efe9cf0a15b6871726a4c2e8802e2af88cf1d1 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 16:27:11 +0100 Subject: [PATCH 032/125] Rename and rework entry point --- .../ApplicationHost.cs | 5 +- .../EnvironmentInfo/EnvironmentInfo.cs | 19 +- Emby.Server.Implementations/StartupOptions.cs | 17 +- Jellyfin.Server/CoreAppHost.cs | 57 +++ Jellyfin.Server/Jellyfin.Server.csproj | 39 ++ .../PowerManagement.cs | 8 +- Jellyfin.Server/Program.cs | 302 ++++++++++++++ .../SocketSharp/HttpFile.cs | 6 +- .../SocketSharp/RequestMono.cs | 6 +- .../SocketSharp/SharpWebSocket.cs | 8 +- .../SocketSharp/WebSocketSharpListener.cs | 16 +- .../SocketSharp/WebSocketSharpRequest.cs | 6 +- .../SocketSharp/WebSocketSharpResponse.cs | 7 +- MediaBrowser.Model/System/Architecture.cs | 10 - MediaBrowser.Model/System/IEnvironmentInfo.cs | 3 +- MediaBrowser.Model/System/SystemInfo.cs | 3 +- MediaBrowser.Server.Mono/EmbyServer.csproj | 66 --- .../ImageEncoderHelper.cs | 50 --- MediaBrowser.Server.Mono/MonoAppHost.cs | 104 ----- .../Native/MonoFileSystem.cs | 23 -- MediaBrowser.Server.Mono/Program.cs | 380 ------------------ .../Properties/AssemblyInfo.cs | 15 - .../Properties/launchSettings.json | 7 - .../Resources/Configuration/logging.json | 19 - MediaBrowser.sln | 41 +- 25 files changed, 461 insertions(+), 756 deletions(-) create mode 100644 Jellyfin.Server/CoreAppHost.cs create mode 100644 Jellyfin.Server/Jellyfin.Server.csproj rename {MediaBrowser.Server.Mono/Native => Jellyfin.Server}/PowerManagement.cs (78%) create mode 100644 Jellyfin.Server/Program.cs rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/HttpFile.cs (76%) rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/RequestMono.cs (99%) rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/SharpWebSocket.cs (98%) rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/WebSocketSharpListener.cs (98%) rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/WebSocketSharpRequest.cs (99%) rename {MediaBrowser.Server.Mono => Jellyfin.Server}/SocketSharp/WebSocketSharpResponse.cs (99%) delete mode 100644 MediaBrowser.Model/System/Architecture.cs delete mode 100644 MediaBrowser.Server.Mono/EmbyServer.csproj delete mode 100644 MediaBrowser.Server.Mono/ImageEncoderHelper.cs delete mode 100644 MediaBrowser.Server.Mono/MonoAppHost.cs delete mode 100644 MediaBrowser.Server.Mono/Native/MonoFileSystem.cs delete mode 100644 MediaBrowser.Server.Mono/Program.cs delete mode 100644 MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs delete mode 100644 MediaBrowser.Server.Mono/Properties/launchSettings.json delete mode 100644 MediaBrowser.Server.Mono/Resources/Configuration/logging.json diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index a4a24dda0a..060898684e 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -416,7 +416,6 @@ namespace Emby.Server.Implementations ConfigurationManager = GetConfigurationManager(); - // Initialize this early in case the -v command line option is used Logger = LoggerFactory.CreateLogger("App"); StartupOptions = options; @@ -467,7 +466,7 @@ namespace Emby.Server.Implementations { get { - return _version ?? (_version = GetType().GetTypeInfo().Assembly.GetName().Version); + return _version ?? (_version = typeof(ApplicationHost).Assembly.GetName().Version); } } @@ -1772,7 +1771,7 @@ namespace Emby.Server.Implementations return list.ToList(); } - protected abstract List GetAssembliesWithPartsInternal(); + protected abstract IEnumerable GetAssembliesWithPartsInternal(); /// /// Gets the plugin assemblies. diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 7655051095..ad941de550 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -1,12 +1,12 @@ using System; using System.IO; using MediaBrowser.Model.System; +using System.Runtime.InteropServices; namespace Emby.Server.Implementations.EnvironmentInfo { public class EnvironmentInfo : IEnvironmentInfo { - private Architecture? _customArchitecture; private MediaBrowser.Model.System.OperatingSystem? _customOperatingSystem; public virtual MediaBrowser.Model.System.OperatingSystem OperatingSystem @@ -60,22 +60,7 @@ namespace Emby.Server.Implementations.EnvironmentInfo } } - public Architecture SystemArchitecture - { - get - { - if (_customArchitecture.HasValue) - { - return _customArchitecture.Value; - } - - return Environment.Is64BitOperatingSystem ? MediaBrowser.Model.System.Architecture.X64 : MediaBrowser.Model.System.Architecture.X86; - } - set - { - _customArchitecture = value; - } - } + public Architecture SystemArchitecture { get; set; } public string GetEnvironmentVariable(string name) { diff --git a/Emby.Server.Implementations/StartupOptions.cs b/Emby.Server.Implementations/StartupOptions.cs index 159c36248c..2114d85bf8 100644 --- a/Emby.Server.Implementations/StartupOptions.cs +++ b/Emby.Server.Implementations/StartupOptions.cs @@ -1,33 +1,30 @@ using System; -using System.Collections.Generic; using System.Linq; namespace Emby.Server.Implementations { public class StartupOptions { - private readonly List _options; + private readonly string[] _options; public StartupOptions(string[] commandLineArgs) { - _options = commandLineArgs.ToList(); + _options = commandLineArgs; } public bool ContainsOption(string option) - { - return _options.Contains(option, StringComparer.OrdinalIgnoreCase); - } + => _options.Contains(option, StringComparer.OrdinalIgnoreCase); public string GetOption(string name) { - var index = _options.IndexOf(name); + int index = Array.IndexOf(_options, name); - if (index != -1) + if (index == -1) { - return _options.ElementAtOrDefault(index + 1); + return null; } - return null; + return _options.ElementAtOrDefault(index + 1); } } } diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs new file mode 100644 index 0000000000..2fb106b3c0 --- /dev/null +++ b/Jellyfin.Server/CoreAppHost.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.Reflection; +using Emby.Server.Implementations; +using Emby.Server.Implementations.HttpServer; +using Jellyfin.SocketSharp; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.System; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server +{ + public class CoreAppHost : ApplicationHost + { + public CoreAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) + : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) + { + } + + public override bool CanSelfRestart + { + get + { + // A restart script must be provided + return StartupOptions.ContainsOption("-restartpath"); + } + } + + protected override void RestartInternal() => Program.Restart(); + + protected override IEnumerable GetAssembliesWithPartsInternal() + => new [] { typeof(CoreAppHost).Assembly }; + + protected override void ShutdownInternal() => Program.Shutdown(); + + protected override bool SupportsDualModeSockets + { + get + { + return true; + } + } + + protected override IHttpListener CreateHttpListener() + => new WebSocketSharpListener( + Logger, + Certificate, + StreamHelper, + TextEncoding, + NetworkManager, + SocketFactory, + CryptographyProvider, + SupportsDualModeSockets, + FileSystemManager, + EnvironmentInfo + ); + } +} diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj new file mode 100644 index 0000000000..cf83967855 --- /dev/null +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -0,0 +1,39 @@ + + + + Exe + netcoreapp2.1 + false + + + + + latest + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MediaBrowser.Server.Mono/Native/PowerManagement.cs b/Jellyfin.Server/PowerManagement.cs similarity index 78% rename from MediaBrowser.Server.Mono/Native/PowerManagement.cs rename to Jellyfin.Server/PowerManagement.cs index 219a69d652..c27c518937 100644 --- a/MediaBrowser.Server.Mono/Native/PowerManagement.cs +++ b/Jellyfin.Server/PowerManagement.cs @@ -1,21 +1,23 @@ -using System; +using System; using MediaBrowser.Model.System; -namespace MediaBrowser.Server.Mono.Native +namespace Jellyfin.Server.Native { public class PowerManagement : IPowerManagement { public void PreventSystemStandby() { + } public void AllowSystemStandby() { + } public void ScheduleWake(DateTime wakeTimeUtc, string displayName) { - // nothing to Do + } } } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs new file mode 100644 index 0000000000..b768e10323 --- /dev/null +++ b/Jellyfin.Server/Program.cs @@ -0,0 +1,302 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Emby.Drawing; +using Emby.Drawing.ImageMagick; +using Emby.Drawing.Skia; +using Emby.Server.Implementations; +using Emby.Server.Implementations.EnvironmentInfo; +using Emby.Server.Implementations.IO; +using Emby.Server.Implementations.Networking; +using Jellyfin.Server.Native; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.System; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.AspNetCore; +using ILogger = Microsoft.Extensions.Logging.ILogger; + +namespace Jellyfin.Server +{ + public static class Program + { + private static readonly TaskCompletionSource ApplicationTaskCompletionSource = new TaskCompletionSource(); + private static ILoggerFactory _loggerFactory; + private static ILogger _logger; + private static bool _restartOnShutdown; + + public static async Task Main(string[] args) + { + StartupOptions options = new StartupOptions(args); + + Assembly entryAssembly = Assembly.GetEntryAssembly(); + + if (options.ContainsOption("-v") || options.ContainsOption("--version")) + { + Console.WriteLine(entryAssembly.GetName().Version.ToString()); + return 0; + } + + string dataPath = options.GetOption("-programdata"); + string binPath = entryAssembly.Location; + ServerApplicationPaths appPaths = CreateApplicationPaths(binPath, dataPath); + + await createLogger(appPaths); + _loggerFactory = new SerilogLoggerFactory(); + _logger = _loggerFactory.CreateLogger("Main"); + + AppDomain.CurrentDomain.UnhandledException += (sender, e) + => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");; + + ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true); + + SQLitePCL.Batteries_V2.Init(); + + // Allow all https requests + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); + + EnvironmentInfo environmentInfo = getEnvironmentInfo(); + var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); + + using (var appHost = new CoreAppHost( + appPaths, + _loggerFactory, + options, + fileSystem, + new PowerManagement(), + "embyserver-mono_{version}.zip", + environmentInfo, + new NullImageEncoder(), + new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")), + new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) + { + appHost.Init(); + + appHost.ImageProcessor.ImageEncoder = GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); + + _logger.LogInformation("Running startup tasks"); + + await appHost.RunStartupTasks(); + + // TODO: read input for a stop command + // Block main thread until shutdown + await ApplicationTaskCompletionSource.Task; + + _logger.LogInformation("Disposing app host"); + } + + if (_restartOnShutdown) + { + StartNewInstance(options); + } + + return 0; + } + + private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath) + { + if (string.IsNullOrEmpty(programDataPath)) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + } + else + { + // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. + programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); + // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used. + if (string.IsNullOrEmpty(programDataPath)){ + programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"); + } + } + programDataPath = Path.Combine(programDataPath, "jellyfin"); + } + + string appFolderPath = Path.GetDirectoryName(applicationPath); + + return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath); + } + + private static async Task createLogger(IApplicationPaths appPaths) + { + string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); + if (string.IsNullOrEmpty(logDir)){ + logDir = Path.Combine(appPaths.ProgramDataPath, "logs"); + Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); + } + try + { + string path = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json"); + + if (!File.Exists(path)) + { + // For some reason the csproj name is used instead of the assembly name + using (Stream rscstr = typeof(Program).Assembly + .GetManifestResourceStream("EmbyServer.Resources.Configuration.logging.json")) + using (Stream fstr = File.Open(path, FileMode.CreateNew)) + { + await rscstr.CopyToAsync(fstr); + } + } + var configuration = new ConfigurationBuilder() + .SetBasePath(appPaths.ConfigurationDirectoryPath) + .AddJsonFile("logging.json") + .AddEnvironmentVariables("JELLYFIN_") + .Build(); + + // Serilog.Log is used by SerilogLoggerFactory when no logger is specified + Serilog.Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .CreateLogger(); + } + catch (Exception ex) + { + Serilog.Log.Logger = new LoggerConfiguration() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.File( + Path.Combine(logDir, "log_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") + .Enrich.FromLogContext() + .CreateLogger(); + + Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration"); + } + } + + public static IImageEncoder GetImageEncoder( + ILogger logger, + IFileSystem fileSystem, + StartupOptions startupOptions, + Func httpClient, + IApplicationPaths appPaths, + IEnvironmentInfo environment, + ILocalizationManager localizationManager) + { + if (!startupOptions.ContainsOption("-enablegdi")) + { + try + { + return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); + } + catch (Exception ex) + { + logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message); + } + + try + { + return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); + } + catch + { + logger.LogInformation("ImageMagick not available. Will try next image processor."); + } + } + + return new NullImageEncoder(); + } + + private static EnvironmentInfo getEnvironmentInfo() + => new EnvironmentInfo() + { + SystemArchitecture = RuntimeInformation.OSArchitecture, + OperatingSystem = getOperatingSystem() + }; + + private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() { + switch (Environment.OSVersion.Platform) + { + case PlatformID.MacOSX: + return MediaBrowser.Model.System.OperatingSystem.OSX; + case PlatformID.Win32NT: + return MediaBrowser.Model.System.OperatingSystem.Windows; + case PlatformID.Unix: + { + string osDescription = RuntimeInformation.OSDescription; + if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.Linux; + } + else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.OSX; + } + else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.BSD; + } + throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}"); + } + default: throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}"); + } + } + + public static void Shutdown() + { + ApplicationTaskCompletionSource.SetResult(true); + } + + public static void Restart() + { + _restartOnShutdown = true; + + Shutdown(); + } + + private static void StartNewInstance(StartupOptions startupOptions) + { + _logger.LogInformation("Starting new instance"); + + string module = startupOptions.GetOption("-restartpath"); + + if (string.IsNullOrWhiteSpace(module)) + { + module = Environment.GetCommandLineArgs().First(); + } + + string commandLineArgsString; + + if (startupOptions.ContainsOption("-restartargs")) + { + commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty; + } + else + { + commandLineArgsString = string .Join(" ", + Environment.GetCommandLineArgs() + .Skip(1) + .Select(NormalizeCommandLineArgument) + ); + } + + _logger.LogInformation("Executable: {0}", module); + _logger.LogInformation("Arguments: {0}", commandLineArgsString); + + Process.Start(module, commandLineArgsString); + } + + private static string NormalizeCommandLineArgument(string arg) + { + if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase)) + { + return arg; + } + + return "\"" + arg + "\""; + } + } +} diff --git a/MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs b/Jellyfin.Server/SocketSharp/HttpFile.cs similarity index 76% rename from MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs rename to Jellyfin.Server/SocketSharp/HttpFile.cs index 1e7c93debb..4a798062dd 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/HttpFile.cs +++ b/Jellyfin.Server/SocketSharp/HttpFile.cs @@ -1,7 +1,7 @@ -using MediaBrowser.Model.Services; -using System.IO; +using System.IO; +using MediaBrowser.Model.Services; -namespace EmbyServer.SocketSharp +namespace Jellyfin.SocketSharp { public class HttpFile : IHttpFile { diff --git a/MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs b/Jellyfin.Server/SocketSharp/RequestMono.cs similarity index 99% rename from MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs rename to Jellyfin.Server/SocketSharp/RequestMono.cs index 9d23543169..31f2894977 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/RequestMono.cs +++ b/Jellyfin.Server/SocketSharp/RequestMono.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Net; @@ -8,7 +7,7 @@ using System.Text; using System.Threading.Tasks; using MediaBrowser.Model.Services; -namespace EmbyServer.SocketSharp +namespace Jellyfin.SocketSharp { public partial class WebSocketSharpRequest : IHttpRequest { @@ -52,7 +51,7 @@ namespace EmbyServer.SocketSharp input.Position = 0; - //Uncomment to debug + // Uncomment to debug //var content = new StreamReader(ms).ReadToEnd(); //Console.WriteLine(boundary + "::" + content); //input.Position = 0; @@ -802,6 +801,5 @@ namespace EmbyServer.SocketSharp return path.Substring(path.LastIndexOf('\\') + 1); } } - } } diff --git a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs b/Jellyfin.Server/SocketSharp/SharpWebSocket.cs similarity index 98% rename from MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs rename to Jellyfin.Server/SocketSharp/SharpWebSocket.cs index fd32640a25..1c72035a55 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/SharpWebSocket.cs +++ b/Jellyfin.Server/SocketSharp/SharpWebSocket.cs @@ -1,12 +1,12 @@ -using MediaBrowser.Common.Events; -using Microsoft.Extensions.Logging; -using System; +using System; using System.Threading; using System.Threading.Tasks; using System.Net.WebSockets; using Emby.Server.Implementations.Net; +using MediaBrowser.Common.Events; +using Microsoft.Extensions.Logging; -namespace EmbyServer.SocketSharp +namespace Jellyfin.SocketSharp { public class SharpWebSocket : IWebSocket { diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs similarity index 98% rename from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs rename to Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs index 993863e8c8..c360a8fcea 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs +++ b/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs @@ -1,23 +1,22 @@ -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; -using SocketHttpListener.Net; -using System; +using System; using System.Collections.Generic; -using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; +using Emby.Server.Implementations.Net; +using Emby.Server.Implementations.HttpServer; using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using MediaBrowser.Model.Services; using MediaBrowser.Model.System; using MediaBrowser.Model.Text; -using Emby.Server.Implementations.Net; -using Emby.Server.Implementations.HttpServer; +using Microsoft.Extensions.Logging; +using SocketHttpListener.Net; -namespace EmbyServer.SocketSharp +namespace Jellyfin.SocketSharp { public class WebSocketSharpListener : IHttpListener { @@ -258,5 +257,4 @@ namespace EmbyServer.SocketSharp } } } - } diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs similarity index 99% rename from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs rename to Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs index 1e1c3db7c4..7c9dc8f88c 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpRequest.cs +++ b/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs @@ -3,17 +3,15 @@ using System.Collections.Generic; using System.IO; using System.Text; using Emby.Server.Implementations.HttpServer; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; using SocketHttpListener.Net; using IHttpFile = MediaBrowser.Model.Services.IHttpFile; using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest; using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse; using IResponse = MediaBrowser.Model.Services.IResponse; -using System.Threading.Tasks; -namespace EmbyServer.SocketSharp +namespace Jellyfin.SocketSharp { public partial class WebSocketSharpRequest : IHttpRequest { diff --git a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs b/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs similarity index 99% rename from MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs rename to Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs index 08fa4cbd62..c7437c8254 100644 --- a/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpResponse.cs +++ b/Jellyfin.Server/SocketSharp/WebSocketSharpResponse.cs @@ -2,18 +2,19 @@ using System.Collections.Generic; using System.IO; using System.Net; +using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse; using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse; using IRequest = MediaBrowser.Model.Services.IRequest; -using System.Net.Sockets; -namespace EmbyServer.SocketSharp + +namespace Jellyfin.SocketSharp { public class WebSocketSharpResponse : IHttpResponse { diff --git a/MediaBrowser.Model/System/Architecture.cs b/MediaBrowser.Model/System/Architecture.cs deleted file mode 100644 index 73f78cd582..0000000000 --- a/MediaBrowser.Model/System/Architecture.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace MediaBrowser.Model.System -{ - public enum Architecture - { - X86 = 0, - X64 = 1, - Arm = 2, - Arm64 = 3 - } -} diff --git a/MediaBrowser.Model/System/IEnvironmentInfo.cs b/MediaBrowser.Model/System/IEnvironmentInfo.cs index 8cf25a365f..6af514dc8e 100644 --- a/MediaBrowser.Model/System/IEnvironmentInfo.cs +++ b/MediaBrowser.Model/System/IEnvironmentInfo.cs @@ -1,4 +1,5 @@ - +using System.Runtime.InteropServices; + namespace MediaBrowser.Model.System { public interface IEnvironmentInfo diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs index c790731c6f..031222b751 100644 --- a/MediaBrowser.Model/System/SystemInfo.cs +++ b/MediaBrowser.Model/System/SystemInfo.cs @@ -1,6 +1,5 @@ using MediaBrowser.Model.Updates; -using System.Collections.Generic; -using System; +using System.Runtime.InteropServices; namespace MediaBrowser.Model.System { diff --git a/MediaBrowser.Server.Mono/EmbyServer.csproj b/MediaBrowser.Server.Mono/EmbyServer.csproj deleted file mode 100644 index 609af9674b..0000000000 --- a/MediaBrowser.Server.Mono/EmbyServer.csproj +++ /dev/null @@ -1,66 +0,0 @@ - - - - Exe - jellyfin - netcoreapp2.1 - false - - - - None - ubuntu.16.04-x64 - - - - AnyCPU - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs b/MediaBrowser.Server.Mono/ImageEncoderHelper.cs deleted file mode 100644 index 29760ec55b..0000000000 --- a/MediaBrowser.Server.Mono/ImageEncoderHelper.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using Emby.Drawing; -using Emby.Drawing.ImageMagick; -using Emby.Server.Implementations; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; -using Emby.Drawing.Skia; -using MediaBrowser.Model.System; -using MediaBrowser.Model.Globalization; - -namespace MediaBrowser.Server.Startup.Common -{ - public class ImageEncoderHelper - { - public static IImageEncoder GetImageEncoder(ILogger logger, - IFileSystem fileSystem, - StartupOptions startupOptions, - Func httpClient, - IApplicationPaths appPaths, - IEnvironmentInfo environment, - ILocalizationManager localizationManager) - { - if (!startupOptions.ContainsOption("-enablegdi")) - { - try - { - return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); - } - catch (Exception ex) - { - logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message); - } - - try - { - return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); - } - catch - { - logger.LogInformation("ImageMagick not available. Will try next image processor."); - } - } - - return new NullImageEncoder(); - } - } -} diff --git a/MediaBrowser.Server.Mono/MonoAppHost.cs b/MediaBrowser.Server.Mono/MonoAppHost.cs deleted file mode 100644 index c2ec423f84..0000000000 --- a/MediaBrowser.Server.Mono/MonoAppHost.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -//using Emby.Server.CinemaMode; -using Emby.Server.Implementations; -using Emby.Server.Implementations.Library; -using Emby.Server.Implementations.HttpServer; -using Emby.Server.Implementations.Net; -using MediaBrowser.Controller.Connect; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Sync; -using IsoMounter; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Services; -using MediaBrowser.Model.System; - -namespace MediaBrowser.Server.Mono -{ - public class MonoAppHost : ApplicationHost - { - public MonoAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) - : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) - { - } - - public override bool CanSelfRestart - { - get - { - // A restart script must be provided - return StartupOptions.ContainsOption("-restartpath"); - } - } - - //protected override ISyncManager CreateSyncManager() - //{ - // return new SyncManager(); - //} - - protected override void RestartInternal() - { - MainClass.Restart(); - } - - protected override List GetAssembliesWithPartsInternal() - { - var list = new List(); - - list.Add(GetType().Assembly); - - return list; - } - - protected override void ShutdownInternal() - { - MainClass.Shutdown(); - } - - protected override bool SupportsDualModeSockets - { - get - { - return GetMonoVersion() >= new Version(4, 6); - } - } - - private static Version GetMonoVersion() - { - Type type = Type.GetType("Mono.Runtime"); - if (type != null) - { - MethodInfo displayName = type.GetTypeInfo().GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); - var displayNameValue = displayName.Invoke(null, null).ToString().Trim().Split(' ')[0]; - - Version version; - if (Version.TryParse(displayNameValue, out version)) - { - return version; - } - } - - return new Version(1, 0); - } - - protected override IHttpListener CreateHttpListener() - { - return new EmbyServer.SocketSharp.WebSocketSharpListener( - Logger, - Certificate, - StreamHelper, - TextEncoding, - NetworkManager, - SocketFactory, - CryptographyProvider, - SupportsDualModeSockets, - FileSystemManager, - EnvironmentInfo); - } - - } -} diff --git a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs b/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs deleted file mode 100644 index 2499d8bb51..0000000000 --- a/MediaBrowser.Server.Mono/Native/MonoFileSystem.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Emby.Server.Implementations.IO; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.System; -using Mono.Unix.Native; - -namespace MediaBrowser.Server.Mono.Native -{ - public class MonoFileSystem : ManagedFileSystem - { - public MonoFileSystem(ILogger logger, IEnvironmentInfo environment, string defaultDirectory, string tempPath, bool enableSeperateFileAndDirectoryQueries) - : base(logger, environment,defaultDirectory, tempPath, enableSeperateFileAndDirectoryQueries) - { - } - - public override void SetExecutable(string path) - { - // Linux: File permission to 666, and user's execute bit - Logger.LogInformation("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path); - - Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH); - } - } -} diff --git a/MediaBrowser.Server.Mono/Program.cs b/MediaBrowser.Server.Mono/Program.cs deleted file mode 100644 index f512fc98e0..0000000000 --- a/MediaBrowser.Server.Mono/Program.cs +++ /dev/null @@ -1,380 +0,0 @@ -using MediaBrowser.Server.Mono.Native; -using MediaBrowser.Server.Startup.Common; -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Security; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Emby.Drawing; -using Emby.Server.Implementations; -using Emby.Server.Implementations.EnvironmentInfo; -using Emby.Server.Implementations.IO; -using Emby.Server.Implementations.Networking; -using MediaBrowser.Controller; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.System; -using Mono.Unix.Native; -using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; -using System.Threading; -using InteropServices = System.Runtime.InteropServices; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Configuration; -using ILogger = Microsoft.Extensions.Logging.ILogger; -using Serilog; -using Serilog.AspNetCore; - -namespace MediaBrowser.Server.Mono -{ - public class MainClass - { - private static ILogger _logger; - private static IFileSystem FileSystem; - private static IServerApplicationPaths _appPaths; - private static ILoggerFactory _loggerFactory; - - private static readonly TaskCompletionSource ApplicationTaskCompletionSource = new TaskCompletionSource(); - private static bool _restartOnShutdown; - - public static void Main(string[] args) - { - var applicationPath = Assembly.GetEntryAssembly().Location; - - SetSqliteProvider(); - - var options = new StartupOptions(Environment.GetCommandLineArgs()); - - // Allow this to be specified on the command line. - var customProgramDataPath = options.GetOption("-programdata"); - - var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath); - _appPaths = appPaths; - - createLogger(); - - using (var loggerFactory = new SerilogLoggerFactory()) - { - _loggerFactory = loggerFactory; - - _logger = loggerFactory.CreateLogger("Main"); - - ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true); - - AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - - RunApplication(appPaths, loggerFactory, options); - - _logger.LogInformation("Disposing app host"); - - if (_restartOnShutdown) - { - StartNewInstance(options); - } - } - } - - private static void SetSqliteProvider() - { - // SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3()); - //SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3()); - SQLitePCL.Batteries_V2.Init(); - } - - private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath) - { - if (string.IsNullOrEmpty(programDataPath)) - { - if (InteropServices.RuntimeInformation.IsOSPlatform(InteropServices.OSPlatform.Windows)) - { - programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - } - else - { - // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. - programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); - // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used. - if (string.IsNullOrEmpty(programDataPath)){ - programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"); - } - } - programDataPath = Path.Combine(programDataPath, "jellyfin"); - } - - var appFolderPath = Path.GetDirectoryName(applicationPath); - - return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath); - } - - private static void RunApplication(ServerApplicationPaths appPaths, ILoggerFactory loggerFactory, StartupOptions options) - { - // Allow all https requests - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); - - var environmentInfo = GetEnvironmentInfo(); - - var fileSystem = new ManagedFileSystem(loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); - - FileSystem = fileSystem; - - using (var appHost = new MonoAppHost(appPaths, - loggerFactory, - options, - fileSystem, - new PowerManagement(), - "embyserver-mono_{version}.zip", - environmentInfo, - new NullImageEncoder(), - new SystemEvents(loggerFactory.CreateLogger("SystemEvents")), - new NetworkManager(loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) - { - if (options.ContainsOption("-v")) - { - Console.WriteLine(appHost.ApplicationVersion.ToString()); - return; - } - - //Console.WriteLine("appHost.Init"); - - appHost.Init(); - - appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); - - //Console.WriteLine("Running startup tasks"); - _logger.LogInformation("Running startup tasks"); - - var task = appHost.RunStartupTasks(); - Task.WaitAll(task); - - task = ApplicationTaskCompletionSource.Task; - - Task.WaitAll(task); - } - } - - private static void createLogger() - { - var logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); - if (string.IsNullOrEmpty(logDir)){ - logDir = Path.Combine(_appPaths.ProgramDataPath, "logs"); - Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); - } - try - { - string path = Path.Combine(_appPaths.ConfigurationDirectoryPath, "logging.json"); - - if (!File.Exists(path)) - { - var assembly = typeof(MainClass).Assembly; - // For some reason the csproj name is used instead of the assembly name - var resourcePath = "EmbyServer.Resources.Configuration.logging.json"; - using (Stream rscstr = assembly.GetManifestResourceStream(resourcePath)) - using (Stream fstr = File.Open(path, FileMode.CreateNew)) - { - rscstr.CopyTo(fstr); - } - } - var configuration = new ConfigurationBuilder() - .SetBasePath(_appPaths.ConfigurationDirectoryPath) - .AddJsonFile("logging.json") - .AddEnvironmentVariables("JELLYFIN_") - .Build(); - - Serilog.Log.Logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .Enrich.FromLogContext() - .CreateLogger(); - } - catch (Exception ex) - { - Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.File( - Path.Combine(logDir, "log_.log"), - rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") - .Enrich.FromLogContext() - .CreateLogger(); - - Serilog.Log.Logger.Fatal(ex, "Failed to read logger config"); - } - } - - private static MonoEnvironmentInfo GetEnvironmentInfo() - { - var info = new MonoEnvironmentInfo(); - - var uname = GetUnixName(); - - var sysName = uname.sysname ?? string.Empty; - - if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase)) - { - info.OperatingSystem = Model.System.OperatingSystem.OSX; - } - else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase)) - { - info.OperatingSystem = Model.System.OperatingSystem.Linux; - } - else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase)) - { - info.OperatingSystem = Model.System.OperatingSystem.BSD; - } - - var archX86 = new Regex("(i|I)[3-6]86"); - - if (archX86.IsMatch(uname.machine)) - { - info.SystemArchitecture = Architecture.X86; - } - else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase)) - { - info.SystemArchitecture = Architecture.X64; - } - else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase)) - { - info.SystemArchitecture = Architecture.Arm; - } - else if (System.Environment.Is64BitOperatingSystem) - { - info.SystemArchitecture = Architecture.X64; - } - else - { - info.SystemArchitecture = Architecture.X86; - } - - return info; - } - - private static Uname _unixName; - - private static Uname GetUnixName() - { - if (_unixName == null) - { - var uname = new Uname(); - try - { - Utsname utsname; - var callResult = Syscall.uname(out utsname); - if (callResult == 0) - { - uname.sysname = utsname.sysname ?? string.Empty; - uname.machine = utsname.machine ?? string.Empty; - } - - } - catch (Exception ex) - { - _logger.LogError(ex, "Error getting unix name"); - } - _unixName = uname; - } - return _unixName; - } - - public class Uname - { - public string sysname = string.Empty; - public string machine = string.Empty; - } - - /// - /// Handles the UnhandledException event of the CurrentDomain control. - /// - /// The source of the event. - /// The instance containing the event data. - static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) - { - var exception = (Exception)e.ExceptionObject; - - //new UnhandledExceptionWriter(_appPaths, _logger, _logManager, FileSystem, new ConsoleLogger()).Log(exception); - - _logger.LogCritical(exception, "Unhandled Exception"); - - // TODO: @bond - /* - if (!Debugger.IsAttached) - { - var message = LogHelper.GetLogMessage(exception).ToString(); - - if (message.IndexOf("InotifyWatcher", StringComparison.OrdinalIgnoreCase) == -1 && - message.IndexOf("_IOCompletionCallback", StringComparison.OrdinalIgnoreCase) == -1) - { - Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception)); - } - } - */ - } - - public static void Shutdown() - { - ApplicationTaskCompletionSource.SetResult(true); - } - - public static void Restart() - { - _restartOnShutdown = true; - - Shutdown(); - } - - private static void StartNewInstance(StartupOptions startupOptions) - { - _logger.LogInformation("Starting new instance"); - - string module = startupOptions.GetOption("-restartpath"); - string commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty; - - if (string.IsNullOrWhiteSpace(module)) - { - module = Environment.GetCommandLineArgs().First(); - } - if (!startupOptions.ContainsOption("-restartargs")) - { - var args = Environment.GetCommandLineArgs() - .Skip(1) - .Select(NormalizeCommandLineArgument) - .ToArray(); - - commandLineArgsString = string.Join(" ", args); - } - - _logger.LogInformation("Executable: {0}", module); - _logger.LogInformation("Arguments: {0}", commandLineArgsString); - - Process.Start(module, commandLineArgsString); - } - - private static string NormalizeCommandLineArgument(string arg) - { - if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1) - { - return arg; - } - - return "\"" + arg + "\""; - } - } - - // class NoCheckCertificatePolicy : ICertificatePolicy - // { - // public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) - // { - // return true; - // } - // } - - public class MonoEnvironmentInfo : EnvironmentInfo - { - - //public override string GetUserId() - //{ - // return Syscall.getuid().ToString(CultureInfo.InvariantCulture); - //} - } -} diff --git a/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs b/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs deleted file mode 100644 index eda3bcf97e..0000000000 --- a/MediaBrowser.Server.Mono/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Reflection; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. -[assembly: AssemblyTitle ("MediaBrowser.Server.Mono")] -[assembly: AssemblyDescription ("")] -[assembly: AssemblyConfiguration ("")] -[assembly: AssemblyCompany ("")] -[assembly: AssemblyProduct ("")] -[assembly: AssemblyCopyright ("Emby")] -[assembly: AssemblyTrademark ("")] -[assembly: AssemblyCulture ("")] -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. \ No newline at end of file diff --git a/MediaBrowser.Server.Mono/Properties/launchSettings.json b/MediaBrowser.Server.Mono/Properties/launchSettings.json deleted file mode 100644 index 058ad7adca..0000000000 --- a/MediaBrowser.Server.Mono/Properties/launchSettings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "profiles": { - "EmbyServer": { - "commandName": "Project" - } - } -} diff --git a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json b/MediaBrowser.Server.Mono/Resources/Configuration/logging.json deleted file mode 100644 index 78f99b2ad9..0000000000 --- a/MediaBrowser.Server.Mono/Resources/Configuration/logging.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "Serilog": { - "MinimumLevel": "Information", - "WriteTo": [ - { "Name": "Console", - "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" - } - }, - { "Name": "File", - "Args": { - "path": "%JELLYFIN_LOG_DIR%//log_.log", - "rollingInterval": "Day", - "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" - } - } - ] - } -} diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 1f4b01b314..07b9fc4c8a 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -28,8 +28,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.XbmcMetadata", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.LocalMetadata", "MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj", "{7EF9F3E0-697D-42F3-A08F-19DEB5F84392}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EmbyServer", "MediaBrowser.Server.Mono\EmbyServer.csproj", "{175A9388-F352-4586-A6B4-070DED62B644}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing", "Emby.Drawing\Emby.Drawing.csproj", "{08FFF49B-F175-4807-A2B5-73B0EBD9F716}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Photos", "Emby.Photos\Emby.Photos.csproj", "{89AB4548-770D-41FD-A891-8DAFF44F452C}" @@ -66,6 +64,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IsoMounter", "Emby.IsoMount EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -216,23 +216,6 @@ Global {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Win32.ActiveCfg = Release|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x64.ActiveCfg = Release|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x86.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Any CPU.Build.0 = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Win32.ActiveCfg = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|Win32.Build.0 = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x64.ActiveCfg = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x86.ActiveCfg = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Debug|x86.Build.0 = Debug|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|Any CPU.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|Win32.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|Win32.Build.0 = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|x64.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|x86.ActiveCfg = Release|Any CPU - {175A9388-F352-4586-A6B4-070DED62B644}.Release|x86.Build.0 = Release|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.Build.0 = Debug|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -567,6 +550,26 @@ Global {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x64.Build.0 = Release|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.ActiveCfg = Release|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Win32.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Win32.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x64.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x64.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x86.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x86.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Win32.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Win32.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x64.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x64.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From a44936f97f8afc2817d3491615a7cfe1e31c251c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 18:41:02 +0100 Subject: [PATCH 033/125] Fix and improve logging --- .../ApplicationHost.cs | 60 ++++++------------- .../EnvironmentInfo/EnvironmentInfo.cs | 10 +++- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++ Jellyfin.Server/Program.cs | 8 ++- .../Resources/Configuration/logging.json | 19 ++++++ 5 files changed, 56 insertions(+), 45 deletions(-) create mode 100644 Jellyfin.Server/Resources/Configuration/logging.json diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 060898684e..09179c15ea 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -799,27 +799,6 @@ namespace Emby.Server.Implementations JsonSerializer = CreateJsonSerializer(); - OnLoggerLoaded(true); - //LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false); - - DiscoverTypes(); - - SetHttpLimit(); - - RegisterResources(); - - FindParts(); - } - - protected virtual void OnLoggerLoaded(bool isFirstLoad) - { - Logger.LogInformation("Application version: {0}", ApplicationVersion); - - if (!isFirstLoad) - { - LogEnvironmentInfo(Logger, ApplicationPaths, false); - } - if (Plugins != null) { var pluginBuilder = new StringBuilder(); @@ -831,6 +810,14 @@ namespace Emby.Server.Implementations Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString()); } + + DiscoverTypes(); + + SetHttpLimit(); + + RegisterResources(); + + FindParts(); } protected virtual IHttpClient CreateHttpClient() @@ -1073,36 +1060,27 @@ namespace Emby.Server.Implementations { get { - return "netframework"; + return "netcore"; } } - public static void LogEnvironmentInfo(ILogger Logger, IApplicationPaths appPaths, bool isStartup) - { - Logger.LogInformation("Jellyfin:\n{ex}", GetBaseExceptionMessage(appPaths).ToString()); - } - - protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths) + public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo) { var builder = new StringBuilder(); // Distinct these to prevent users from reporting problems that aren't actually problems var commandLineArgs = Environment .GetCommandLineArgs() - .Distinct() - .ToArray(); + .Distinct(); - builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", commandLineArgs))); - - builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion)); - builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem)); - builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess)); - builder.AppendLine(string.Format("User Interactive: {0}", Environment.UserInteractive)); - builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount)); - builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath)); - builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath)); - - return builder; + logger.LogInformation("Arguments: {Args}", commandLineArgs); + logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion); + logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture); + logger.LogInformation("64-Bit Process: {0}", Environment.Is64BitProcess); + logger.LogInformation("User Interactive: {0}", Environment.UserInteractive); + logger.LogInformation("Processor count: {0}", Environment.ProcessorCount); + logger.LogInformation("Program data path: {0}", appPaths.ProgramDataPath); + logger.LogInformation("Application directory: {0}", appPaths.ProgramSystemPath); } private void SetHttpLimit() diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index ad941de550..5cff2dff09 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; namespace Emby.Server.Implementations.EnvironmentInfo { + // TODO: Rework @bond public class EnvironmentInfo : IEnvironmentInfo { private MediaBrowser.Model.System.OperatingSystem? _customOperatingSystem; @@ -40,7 +41,14 @@ namespace Emby.Server.Implementations.EnvironmentInfo { get { - return Environment.OSVersion.Platform.ToString(); + switch (OperatingSystem) { + case MediaBrowser.Model.System.OperatingSystem.Android: return "Android"; + case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD"; + case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux"; + case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS"; + case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows"; + default: throw new Exception($"Unknown OS {OperatingSystem}"); + } } } diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index cf83967855..09491d6a53 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -15,6 +15,10 @@ + + + + diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index b768e10323..dd5e427df2 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -59,14 +59,16 @@ namespace Jellyfin.Server AppDomain.CurrentDomain.UnhandledException += (sender, e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");; - ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true); + _logger.LogInformation("Jellyfin version: {Version}", entryAssembly.GetName().Version); + + EnvironmentInfo environmentInfo = getEnvironmentInfo(); + ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); SQLitePCL.Batteries_V2.Init(); // Allow all https requests ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); - EnvironmentInfo environmentInfo = getEnvironmentInfo(); var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); using (var appHost = new CoreAppHost( @@ -144,7 +146,7 @@ namespace Jellyfin.Server { // For some reason the csproj name is used instead of the assembly name using (Stream rscstr = typeof(Program).Assembly - .GetManifestResourceStream("EmbyServer.Resources.Configuration.logging.json")) + .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json")) using (Stream fstr = File.Open(path, FileMode.CreateNew)) { await rscstr.CopyToAsync(fstr); diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json new file mode 100644 index 0000000000..78f99b2ad9 --- /dev/null +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -0,0 +1,19 @@ +{ + "Serilog": { + "MinimumLevel": "Information", + "WriteTo": [ + { "Name": "Console", + "Args": { + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" + } + }, + { "Name": "File", + "Args": { + "path": "%JELLYFIN_LOG_DIR%//log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" + } + } + ] + } +} From 33889e53527901fb59e5dd4a6bceddeb2442d70c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 18:51:55 +0100 Subject: [PATCH 034/125] Remove useless string builder --- Emby.Server.Implementations/ApplicationHost.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 09179c15ea..f1e1b4b2d0 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1066,8 +1066,6 @@ namespace Emby.Server.Implementations public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo) { - var builder = new StringBuilder(); - // Distinct these to prevent users from reporting problems that aren't actually problems var commandLineArgs = Environment .GetCommandLineArgs() @@ -1076,11 +1074,11 @@ namespace Emby.Server.Implementations logger.LogInformation("Arguments: {Args}", commandLineArgs); logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion); logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture); - logger.LogInformation("64-Bit Process: {0}", Environment.Is64BitProcess); - logger.LogInformation("User Interactive: {0}", Environment.UserInteractive); - logger.LogInformation("Processor count: {0}", Environment.ProcessorCount); - logger.LogInformation("Program data path: {0}", appPaths.ProgramDataPath); - logger.LogInformation("Application directory: {0}", appPaths.ProgramSystemPath); + logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess); + logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive); + logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount); + logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath); + logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath); } private void SetHttpLimit() @@ -1151,7 +1149,7 @@ namespace Emby.Server.Implementations //localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { - Logger.LogError("No private key included in SSL cert {0}.", certificateLocation); + Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation); return null; } @@ -1159,7 +1157,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error loading cert from {certificateLocation}", certificateLocation); + Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation); return null; } } From 95a5dd881076f6649f4b5dc5a1897df98dc3c008 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 21:34:12 +0100 Subject: [PATCH 035/125] Fix log dir --- .../AppBase/BaseApplicationPaths.cs | 24 +++++++-- .../ServerApplicationPaths.cs | 4 +- Jellyfin.Server/Program.cs | 51 ++++++++++--------- MediaBrowser.Api/System/SystemService.cs | 10 ++-- 4 files changed, 54 insertions(+), 35 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs index 52e421374b..76d0076a66 100644 --- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs +++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using System.IO; using MediaBrowser.Common.Configuration; namespace Emby.Server.Implementations.AppBase @@ -13,10 +12,11 @@ namespace Emby.Server.Implementations.AppBase /// /// Initializes a new instance of the class. /// - protected BaseApplicationPaths(string programDataPath, string appFolderPath) + protected BaseApplicationPaths(string programDataPath, string appFolderPath, string logDirectoryPath) { ProgramDataPath = programDataPath; ProgramSystemPath = appFolderPath; + LogDirectoryPath = logDirectoryPath; } public string ProgramDataPath { get; private set; } @@ -106,6 +106,11 @@ namespace Emby.Server.Implementations.AppBase } } + /// + /// The _log directory + /// + private string _logDirectoryPath; + /// /// Gets the path to the log directory /// @@ -114,7 +119,18 @@ namespace Emby.Server.Implementations.AppBase { get { - return Path.Combine(ProgramDataPath, "logs"); + if (string.IsNullOrEmpty(_logDirectoryPath)) + { + _logDirectoryPath = Path.Combine(ProgramDataPath, "logs"); + + Directory.CreateDirectory(_logDirectoryPath); + } + + return _logDirectoryPath; + } + set + { + _logDirectoryPath = value; } } diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs index 1686a548bc..f5986f9433 100644 --- a/Emby.Server.Implementations/ServerApplicationPaths.cs +++ b/Emby.Server.Implementations/ServerApplicationPaths.cs @@ -13,8 +13,8 @@ namespace Emby.Server.Implementations /// /// Initializes a new instance of the class. /// - public ServerApplicationPaths(string programDataPath, string appFolderPath, string applicationResourcesPath) - : base(programDataPath, appFolderPath) + public ServerApplicationPaths(string programDataPath, string appFolderPath, string applicationResourcesPath, string logDirectoryPath = null) + : base(programDataPath, appFolderPath, logDirectoryPath) { ApplicationResourcesPath = applicationResourcesPath; } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index dd5e427df2..aef22e020f 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -39,27 +39,23 @@ namespace Jellyfin.Server public static async Task Main(string[] args) { StartupOptions options = new StartupOptions(args); - - Assembly entryAssembly = Assembly.GetEntryAssembly(); + Version version = Assembly.GetEntryAssembly().GetName().Version; if (options.ContainsOption("-v") || options.ContainsOption("--version")) { - Console.WriteLine(entryAssembly.GetName().Version.ToString()); + Console.WriteLine(version.ToString()); return 0; } - string dataPath = options.GetOption("-programdata"); - string binPath = entryAssembly.Location; - ServerApplicationPaths appPaths = CreateApplicationPaths(binPath, dataPath); - + ServerApplicationPaths appPaths = createApplicationPaths(options); await createLogger(appPaths); _loggerFactory = new SerilogLoggerFactory(); _logger = _loggerFactory.CreateLogger("Main"); AppDomain.CurrentDomain.UnhandledException += (sender, e) - => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");; + => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); - _logger.LogInformation("Jellyfin version: {Version}", entryAssembly.GetName().Version); + _logger.LogInformation("Jellyfin version: {Version}", version); EnvironmentInfo environmentInfo = getEnvironmentInfo(); ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); @@ -106,9 +102,14 @@ namespace Jellyfin.Server return 0; } - private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath) + private static ServerApplicationPaths createApplicationPaths(StartupOptions options) { - if (string.IsNullOrEmpty(programDataPath)) + string programDataPath; + if (options.ContainsOption("-programdata")) + { + programDataPath = options.GetOption("-programdata"); + } + else { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -126,28 +127,30 @@ namespace Jellyfin.Server programDataPath = Path.Combine(programDataPath, "jellyfin"); } - string appFolderPath = Path.GetDirectoryName(applicationPath); + string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); + if (string.IsNullOrEmpty(logDir)){ + logDir = Path.Combine(programDataPath, "logs"); + // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager + Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); + } - return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath); + string appPath = Assembly.GetEntryAssembly().Location; + + return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir); } private static async Task createLogger(IApplicationPaths appPaths) { - string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); - if (string.IsNullOrEmpty(logDir)){ - logDir = Path.Combine(appPaths.ProgramDataPath, "logs"); - Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); - } try { - string path = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json"); + string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json"); - if (!File.Exists(path)) + if (!File.Exists(configPath)) { // For some reason the csproj name is used instead of the assembly name using (Stream rscstr = typeof(Program).Assembly .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json")) - using (Stream fstr = File.Open(path, FileMode.CreateNew)) + using (Stream fstr = File.Open(configPath, FileMode.CreateNew)) { await rscstr.CopyToAsync(fstr); } @@ -169,7 +172,7 @@ namespace Jellyfin.Server Serilog.Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.File( - Path.Combine(logDir, "log_.log"), + Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}") .Enrich.FromLogContext() @@ -227,6 +230,7 @@ namespace Jellyfin.Server case PlatformID.Win32NT: return MediaBrowser.Model.System.OperatingSystem.Windows; case PlatformID.Unix: + default: { string osDescription = RuntimeInformation.OSDescription; if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase)) @@ -241,9 +245,8 @@ namespace Jellyfin.Server { return MediaBrowser.Model.System.OperatingSystem.BSD; } - throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}"); + throw new Exception($"Can't resolve OS with description: '{osDescription}'"); } - default: throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}"); } } diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index d2880f735a..52e14dbcc9 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -9,12 +9,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; - -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using MediaBrowser.Model.Services; using System.Threading; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.System { @@ -137,11 +136,12 @@ namespace MediaBrowser.Api.System try { - files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt" }, true, false); + files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt", ".log" }, true, false); } - catch (IOException) + catch (IOException ex) { - files = new FileSystemMetadata[] { }; + Logger.LogError(ex, "Error getting logs"); + files = Enumerable.Empty(); } var result = files.Select(i => new LogFile From 9ccc259c99b11469cd93cb3e15ad2f69f54f0b46 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 23:19:00 +0100 Subject: [PATCH 036/125] Fix errors and assembly name --- Jellyfin.Server/Jellyfin.Server.csproj | 1 + Jellyfin.Server/Program.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 09491d6a53..fa603a0867 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -1,6 +1,7 @@  + jellyfin Exe netcoreapp2.1 false diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index aef22e020f..73c7a0c7cf 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -134,7 +134,7 @@ namespace Jellyfin.Server Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); } - string appPath = Assembly.GetEntryAssembly().Location; + string appPath = AppContext.BaseDirectory; return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir); } From 76d6b1fc2aa8d448803ecf874e7a37a9b6afef9e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 1 Jan 2019 23:56:32 +0100 Subject: [PATCH 037/125] Ensure log dir exists --- Jellyfin.Server/Program.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 73c7a0c7cf..6f3c8c317b 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -130,6 +130,8 @@ namespace Jellyfin.Server string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); if (string.IsNullOrEmpty(logDir)){ logDir = Path.Combine(programDataPath, "logs"); + // Ensure logDir exists + Directory.CreateDirectory(logDir); // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir); } From 5d855ee84c26ab4cdc3a8672433b168ba4cb8610 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 00:10:26 +0100 Subject: [PATCH 038/125] Log when falling back on NullImageEncoder --- Jellyfin.Server/Program.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 6f3c8c317b..a477d8b5ad 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -81,7 +81,7 @@ namespace Jellyfin.Server { appHost.Init(); - appHost.ImageProcessor.ImageEncoder = GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); + appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); _logger.LogInformation("Running startup tasks"); @@ -184,7 +184,7 @@ namespace Jellyfin.Server } } - public static IImageEncoder GetImageEncoder( + public static IImageEncoder getImageEncoder( ILogger logger, IFileSystem fileSystem, StartupOptions startupOptions, @@ -201,17 +201,18 @@ namespace Jellyfin.Server } catch (Exception ex) { - logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message); + logger.LogInformation(ex, "Skia not available. Will try next image processor. {0}"); } try { return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); } - catch + catch (Exception ex) { - logger.LogInformation("ImageMagick not available. Will try next image processor."); + logger.LogInformation(ex, "ImageMagick not available. Will try next image processor."); } + _logger.LogInformation("Falling back on NullImageEncoder"); } return new NullImageEncoder(); From cf7e36561037e0e3c0d532b7a0c8d7d668c2373b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 00:21:06 +0100 Subject: [PATCH 039/125] Fix inconsistent code style --- .../EnvironmentInfo/EnvironmentInfo.cs | 3 ++- Jellyfin.Server/Program.cs | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 5cff2dff09..985eb71da9 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -41,7 +41,8 @@ namespace Emby.Server.Implementations.EnvironmentInfo { get { - switch (OperatingSystem) { + switch (OperatingSystem) + { case MediaBrowser.Model.System.OperatingSystem.Android: return "Android"; case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD"; case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux"; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index a477d8b5ad..f0907fd581 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -120,7 +120,8 @@ namespace Jellyfin.Server // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used. - if (string.IsNullOrEmpty(programDataPath)){ + if (string.IsNullOrEmpty(programDataPath)) + { programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"); } } @@ -128,7 +129,8 @@ namespace Jellyfin.Server } string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); - if (string.IsNullOrEmpty(logDir)){ + if (string.IsNullOrEmpty(logDir)) + { logDir = Path.Combine(programDataPath, "logs"); // Ensure logDir exists Directory.CreateDirectory(logDir); From c99b45dbe0b6f0b02850eda5c9ece071c6c03e85 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 31 Dec 2018 00:28:23 +0100 Subject: [PATCH 040/125] Remove some warnings --- .../Serialization/JsonSerializer.cs | 8 +-- MediaBrowser.Common/Updates/GithubUpdater.cs | 24 ++++----- MediaBrowser.Controller/Entities/Game.cs | 7 ++- .../MediaEncoding/EncodingJobOptions.cs | 3 -- .../Encoder/EncodingJob.cs | 53 ++++++++----------- .../Encoder/FontConfigLoader.cs | 5 +- .../Encoder/MediaEncoder.cs | 3 +- .../Probing/ProbeResultNormalizer.cs | 13 ++--- .../Manager/ProviderManager.cs | 40 +++++++------- .../Providers/BaseNfoProvider.cs | 14 ++--- 10 files changed, 71 insertions(+), 99 deletions(-) diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs index 423fe7b183..e28acd769f 100644 --- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs +++ b/Emby.Server.Implementations/Serialization/JsonSerializer.cs @@ -136,19 +136,15 @@ namespace Emby.Common.Implementations.Serialization return ServiceStack.Text.JsonSerializer.DeserializeFromStream(stream); } - public async Task DeserializeFromStreamAsync(Stream stream) + public Task DeserializeFromStreamAsync(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } - using (var reader = new StreamReader(stream)) - { - var json = await reader.ReadToEndAsync().ConfigureAwait(false); - return ServiceStack.Text.JsonSerializer.DeserializeFromString(json); - } + return ServiceStack.Text.JsonSerializer.DeserializeFromStreamAsync(stream); } /// diff --git a/MediaBrowser.Common/Updates/GithubUpdater.cs b/MediaBrowser.Common/Updates/GithubUpdater.cs index 4275799a98..22ed788e0c 100644 --- a/MediaBrowser.Common/Updates/GithubUpdater.cs +++ b/MediaBrowser.Common/Updates/GithubUpdater.cs @@ -41,13 +41,11 @@ namespace MediaBrowser.Common.Updates } using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) + using (var stream = response.Content) { - using (var stream = response.Content) - { - var obj = _jsonSerializer.DeserializeFromStream(stream); + var obj = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false); - return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); - } + return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); } } @@ -114,19 +112,17 @@ namespace MediaBrowser.Common.Updates }; using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) + using (var stream = response.Content) { - using (var stream = response.Content) - { - var obj = _jsonSerializer.DeserializeFromStream(stream); + var obj = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false); - obj = obj.Where(i => (i.assets ?? new List()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray(); + obj = obj.Where(i => (i.assets ?? new List()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray(); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1)); + list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1)); - return list; - } + return list; } } diff --git a/MediaBrowser.Controller/Entities/Game.cs b/MediaBrowser.Controller/Entities/Game.cs index e4c417c8a9..3d006a699c 100644 --- a/MediaBrowser.Controller/Entities/Game.cs +++ b/MediaBrowser.Controller/Entities/Game.cs @@ -1,11 +1,10 @@ -using MediaBrowser.Controller.Providers; +using System; +using System.Collections.Generic; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using System; -using System.Collections.Generic; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; -using System; namespace MediaBrowser.Controller.Entities { diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs index 7333149c2b..befbb21404 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs @@ -11,13 +11,10 @@ namespace MediaBrowser.Controller.MediaEncoding { public string OutputDirectory { get; set; } - public string DeviceId { get; set; } public string ItemId { get; set; } public string MediaSourceId { get; set; } public string AudioCodec { get; set; } - public DeviceProfile DeviceProfile { get; set; } - public bool ReadInputAtNativeFramerate { get; set; } /// diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs index e97898ac53..9761de98fb 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs @@ -1,18 +1,10 @@ -using MediaBrowser.Controller.Library; +using System; +using System.IO; +using System.Threading.Tasks; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder @@ -153,7 +145,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null; - // job.Framerate = framerate; + //job.Framerate = framerate; if (!percentComplete.HasValue && ticks.HasValue && RunTimeTicks.HasValue) { @@ -166,8 +158,9 @@ namespace MediaBrowser.MediaEncoding.Encoder Progress.Report(percentComplete.Value); } - // job.TranscodingPositionTicks = ticks; - // job.BytesTranscoded = bytesTranscoded; + /* + job.TranscodingPositionTicks = ticks; + job.BytesTranscoded = bytesTranscoded; var deviceId = Options.DeviceId; @@ -176,21 +169,21 @@ namespace MediaBrowser.MediaEncoding.Encoder var audioCodec = ActualOutputVideoCodec; var videoCodec = ActualOutputVideoCodec; - // SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo - // { - // Bitrate = job.TotalOutputBitrate, - // AudioCodec = audioCodec, - // VideoCodec = videoCodec, - // Container = job.Options.OutputContainer, - // Framerate = framerate, - // CompletionPercentage = percentComplete, - // Width = job.OutputWidth, - // Height = job.OutputHeight, - // AudioChannels = job.OutputAudioChannels, - // IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase), - // IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) - // }); - } + SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo + { + Bitrate = job.TotalOutputBitrate, + AudioCodec = audioCodec, + VideoCodec = videoCodec, + Container = job.Options.OutputContainer, + Framerate = framerate, + CompletionPercentage = percentComplete, + Width = job.OutputWidth, + Height = job.OutputHeight, + AudioChannels = job.OutputAudioChannels, + IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase), + IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) + }); + }*/ } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs index d2cf7f3950..c62de0b113 100644 --- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs +++ b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs @@ -3,15 +3,12 @@ using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; -using MediaBrowser.Model.IO; using MediaBrowser.Common.Configuration; - using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Encoder { diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index a661d76917..181fc0f655 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -6,7 +6,6 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Session; using MediaBrowser.MediaEncoding.Probing; using MediaBrowser.Model.Dlna; -using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -550,7 +549,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { //process.BeginErrorReadLine(); - var result = _jsonSerializer.DeserializeFromStream(process.StandardOutput.BaseStream); + var result = await _jsonSerializer.DeserializeFromStreamAsync(process.StandardOutput.BaseStream).ConfigureAwait(false); if (result == null || (result.streams == null && result.format == null)) { diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index d0ccef2f80..5367a87f7b 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1,20 +1,17 @@ -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; -using MediaBrowser.Model.IO; - -using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; using MediaBrowser.Model.MediaInfo; +using Microsoft.Extensions.Logging; namespace MediaBrowser.MediaEncoding.Probing { diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 8a9aae1175..8eed5e6266 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -1,31 +1,29 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Providers; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; -using MediaBrowser.Model.IO; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dto; -using MediaBrowser.Model.Events; -using MediaBrowser.Model.Serialization; -using Priority_Queue; -using MediaBrowser.Model.Extensions; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Events; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Providers; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; +using Priority_Queue; namespace MediaBrowser.Providers.Manager { @@ -827,7 +825,7 @@ namespace MediaBrowser.Providers.Manager } } } - catch (Exception ex) + catch (Exception) { // Logged at lower levels } diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs index 123c0493fb..ae8e638cbd 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs @@ -1,10 +1,10 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; -using MediaBrowser.XbmcMetadata.Savers; -using System.IO; +using System.IO; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; +using MediaBrowser.XbmcMetadata.Savers; namespace MediaBrowser.XbmcMetadata.Providers { @@ -13,7 +13,7 @@ namespace MediaBrowser.XbmcMetadata.Providers { protected IFileSystem FileSystem; - public async Task> GetMetadata(ItemInfo info, + public Task> GetMetadata(ItemInfo info, IDirectoryService directoryService, CancellationToken cancellationToken) { @@ -23,7 +23,7 @@ namespace MediaBrowser.XbmcMetadata.Providers if (file == null) { - return result; + return Task.FromResult(result); } var path = file.FullName; @@ -44,7 +44,7 @@ namespace MediaBrowser.XbmcMetadata.Providers result.HasMetadata = false; } - return result; + return Task.FromResult(result); } protected abstract void Fetch(MetadataResult result, string path, CancellationToken cancellationToken); From a445233192954dec53f1ed01eec6871039c123ed Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 31 Dec 2018 00:51:15 +0100 Subject: [PATCH 041/125] Fix warning and improve performance --- .../LiveTv/Listings/SchedulesDirect.cs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 8fb3af2113..60bc38616c 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -117,10 +117,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestContent = requestString; using (var response = await Post(httpOptions, true, info).ConfigureAwait(false)) { - StreamReader reader = new StreamReader(response.Content); - string responseString = reader.ReadToEnd(); - var dailySchedules = _jsonSerializer.DeserializeFromString>(responseString); - _logger.LogDebug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect"); + var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync>(response.Content).ConfigureAwait(false); + _logger.LogDebug("Found {ScheduleCount} programs on {StationID} ScheduleDirect", dailySchedules.Count, stationID); httpOptions = new HttpRequestOptions() { @@ -140,16 +138,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestContent = requestBody; double wideAspect = 1.77777778; - var primaryImageCategory = "Logo"; using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false)) { - StreamReader innerReader = new StreamReader(innerResponse.Content); - responseString = innerReader.ReadToEnd(); - - var programDetails = - _jsonSerializer.DeserializeFromString>( - responseString); + var programDetails = await _jsonSerializer.DeserializeFromStreamAsync>(innerResponse.Content).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); var programIdsWithImages = From 6643ac3ea412ea62fc067ae6b24ddfe69fd18482 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 00:41:47 +0100 Subject: [PATCH 042/125] Clean up EnvironmentInfo --- .../EnvironmentInfo/EnvironmentInfo.cs | 32 +++---------------- Jellyfin.Server/Program.cs | 9 +----- 2 files changed, 6 insertions(+), 35 deletions(-) diff --git a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs index 985eb71da9..03e10e7ea3 100644 --- a/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs +++ b/Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs @@ -8,35 +8,13 @@ namespace Emby.Server.Implementations.EnvironmentInfo // TODO: Rework @bond public class EnvironmentInfo : IEnvironmentInfo { - private MediaBrowser.Model.System.OperatingSystem? _customOperatingSystem; - - public virtual MediaBrowser.Model.System.OperatingSystem OperatingSystem + public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem) { - get - { - if (_customOperatingSystem.HasValue) - { - return _customOperatingSystem.Value; - } - - switch (Environment.OSVersion.Platform) - { - case PlatformID.MacOSX: - return MediaBrowser.Model.System.OperatingSystem.OSX; - case PlatformID.Win32NT: - return MediaBrowser.Model.System.OperatingSystem.Windows; - case PlatformID.Unix: - return MediaBrowser.Model.System.OperatingSystem.Linux; - } - - return MediaBrowser.Model.System.OperatingSystem.Windows; - } - set - { - _customOperatingSystem = value; - } + OperatingSystem = operatingSystem; } + public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; } + public string OperatingSystemName { get @@ -69,7 +47,7 @@ namespace Emby.Server.Implementations.EnvironmentInfo } } - public Architecture SystemArchitecture { get; set; } + public Architecture SystemArchitecture { get { return RuntimeInformation.OSArchitecture; } } public string GetEnvironmentVariable(string name) { diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index f0907fd581..0150cd5337 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -57,7 +57,7 @@ namespace Jellyfin.Server _logger.LogInformation("Jellyfin version: {Version}", version); - EnvironmentInfo environmentInfo = getEnvironmentInfo(); + EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem()); ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); SQLitePCL.Batteries_V2.Init(); @@ -220,13 +220,6 @@ namespace Jellyfin.Server return new NullImageEncoder(); } - private static EnvironmentInfo getEnvironmentInfo() - => new EnvironmentInfo() - { - SystemArchitecture = RuntimeInformation.OSArchitecture, - OperatingSystem = getOperatingSystem() - }; - private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() { switch (Environment.OSVersion.Platform) { From 68715bb1dc592924c1ff81c364e807d861da0696 Mon Sep 17 00:00:00 2001 From: Phallacy Date: Tue, 1 Jan 2019 20:28:29 -0800 Subject: [PATCH 043/125] minor: copy install.bat for rename --- build-jellyfin.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-jellyfin.ps1 b/build-jellyfin.ps1 index 5544df88af..2247166211 100644 --- a/build-jellyfin.ps1 +++ b/build-jellyfin.ps1 @@ -103,7 +103,7 @@ if($InstallNSSM.IsPresent -or ($InstallNSSM -eq $true)){ Install-NSSM $InstallLocation $Architecture } Copy-Item .\install-jellyfin.ps1 $InstallLocation\install-jellyfin.ps1 -Copy-Item .\installjellyfin.bat $InstallLocation\installjellyfin.bat +Copy-Item .\install.bat $InstallLocation\install.bat if($GenerateZip.IsPresent -or ($GenerateZip -eq $true)){ Compress-Archive -Path $InstallLocation -DestinationPath "$InstallLocation/jellyfin.zip" -Force } From 87812d1e7fd4c423b58fbeaf150bc7fe0811e5fc Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Wed, 2 Jan 2019 01:22:21 -0500 Subject: [PATCH 044/125] Fix spacing to C#/Visual Studio standards - This is a fix automatically applied by Visual Studio --- Emby.Drawing/Emby.Drawing.csproj | 2 +- Emby.Photos/Emby.Photos.csproj | 2 +- MediaBrowser.Api/MediaBrowser.Api.csproj | 2 +- MediaBrowser.Common/MediaBrowser.Common.csproj | 2 +- MediaBrowser.Controller/MediaBrowser.Controller.csproj | 2 +- MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj | 2 +- MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj | 2 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj | 2 +- MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj | 2 +- Mono.Nat/Mono.Nat.csproj | 2 +- SocketHttpListener/SocketHttpListener.csproj | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 3fa60fad14..5ffaaed276 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -6,7 +6,7 @@ - + diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index e945ff444d..3ecab9176a 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -7,7 +7,7 @@ - + diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index 3fa60fad14..5ffaaed276 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -6,7 +6,7 @@ - + diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 43f3b0be7a..f625a17eef 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -5,7 +5,7 @@ - + diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 8e816080cd..4567f62dd5 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -6,7 +6,7 @@ - + diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index bdf2f9873a..b5eb9c2eed 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -6,7 +6,7 @@ - + diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index d9d2b4bf95..d93394957a 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -6,7 +6,7 @@ - + diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index a5b2f40833..fe10688426 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -10,7 +10,7 @@ - + diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index fb5d397436..855b8b627d 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -6,7 +6,7 @@ - + diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 3fa60fad14..5ffaaed276 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -6,7 +6,7 @@ - + diff --git a/Mono.Nat/Mono.Nat.csproj b/Mono.Nat/Mono.Nat.csproj index eacf84c356..26028eca9e 100644 --- a/Mono.Nat/Mono.Nat.csproj +++ b/Mono.Nat/Mono.Nat.csproj @@ -6,7 +6,7 @@ - + diff --git a/SocketHttpListener/SocketHttpListener.csproj b/SocketHttpListener/SocketHttpListener.csproj index 494bc7fc90..ca9056a6ad 100644 --- a/SocketHttpListener/SocketHttpListener.csproj +++ b/SocketHttpListener/SocketHttpListener.csproj @@ -6,7 +6,7 @@ - + From d22324d68dc747778d4d816edbf81958bb0eda8f Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Wed, 2 Jan 2019 01:38:17 -0500 Subject: [PATCH 045/125] Add TagLib-Sharp Building and new file header - This enables TagLib-Sharp being built when using Visual Studio, for both Debug and Release modes - Adds a new file header that is respected when using VS for Mac or MonoDevelop --- MediaBrowser.sln | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 07b9fc4c8a..077bc6aee7 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -570,6 +570,10 @@ Global {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x64.Build.0 = Release|Any CPU {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.ActiveCfg = Release|Any CPU {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.Build.0 = Release|Any CPU + {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -577,4 +581,11 @@ Global GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} EndGlobalSection + GlobalSection(MonoDevelopProperties) = preSolution + Policies = $0 + $0.StandardHeader = $1 + $1.Text = @### This header should be used to start new files.\n### It provides an explicit per-file license reference that should be present on all new files.\n### To use this header, delete these lines and the following empty line, modify to\n### the proper full path, and then add new code following the header and a single empty line.\n\n// ${FileName}\n// Part of the Jellyfin project (https://jellyfin.media)\n//\n// All copyright belongs to the Jellyfin contributors; a full list can\n// be found in the file CONTRIBUTORS.md\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, version 2.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n + $0.DotNetNamingPolicy = $2 + $2.DirectoryNamespaceAssociation = PrefixedHierarchical + EndGlobalSection EndGlobal From 6c27e3a7f71a314d72fcbaa009b92a4f4b89f456 Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Wed, 2 Jan 2019 01:42:21 -0500 Subject: [PATCH 046/125] Add anthonylavado to CONTRIBUTORS.md --- CONTRIBUTORS.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3a2c229d11..fad5796475 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,15 +8,16 @@ - [flemse](https://github.com/flemse) - [bfayers](https://github.com/bfayers) - [Bond_009](https://github.com/Bond-009) + - [AnthonyLavado](https://github.com/anthonylavado) # Emby Contributors - - [LukePulverenti](https://github.com/LukePulverenti) - - [ebr11](https://github.com/ebr11) - - [lalmanzar](https://github.com/lalmanzar) - - [schneifu](https://github.com/schneifu) - - [Mark2xv](https://github.com/Mark2xv) - - [ScottRapsey](https://github.com/ScottRapsey) + - [LukePulverenti](https://github.com/LukePulverenti) + - [ebr11](https://github.com/ebr11) + - [lalmanzar](https://github.com/lalmanzar) + - [schneifu](https://github.com/schneifu) + - [Mark2xv](https://github.com/Mark2xv) + - [ScottRapsey](https://github.com/ScottRapsey) - [skynet600](https://github.com/skynet600) - [Cheesegeezer](https://githum.com/Cheesegeezer) - [Radeon](https://github.com/radeonorama) From cdcdeb5996a80b06504004ec46972adf2b7724dd Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Wed, 2 Jan 2019 02:10:43 -0500 Subject: [PATCH 047/125] Add JSON assets for VSCode development - This adds two configuration files that allow VSCode to open the solution and begin work with the project --- .vscode/launch.json | 28 ++++++++++++++++++++++++++++ .vscode/tasks.json | 15 +++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000000..21b8323ea0 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,28 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll", + "args": [], + "cwd": "${workspaceFolder}/Jellyfin.Server", + // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window + "console": "internalConsole", + "stopAtEntry": false, + "internalConsoleOptions": "openOnSessionStart" + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ,] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000000..ac517e10c6 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,15 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Jellyfin.Server/Jellyfin.Server.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file From 07e7b13b75288e52f71f0ab171b86e14a4229d04 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Wed, 2 Jan 2019 10:55:05 +0100 Subject: [PATCH 048/125] change userid type to guid --- MediaBrowser.Model/Devices/DeviceQuery.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Devices/DeviceQuery.cs b/MediaBrowser.Model/Devices/DeviceQuery.cs index 9ceea1ea8f..fa2e11d4d8 100644 --- a/MediaBrowser.Model/Devices/DeviceQuery.cs +++ b/MediaBrowser.Model/Devices/DeviceQuery.cs @@ -1,4 +1,6 @@  +using System; + namespace MediaBrowser.Model.Devices { public class DeviceQuery @@ -17,6 +19,6 @@ namespace MediaBrowser.Model.Devices /// Gets or sets the user identifier. /// /// The user identifier. - public string UserId { get; set; } + public Guid UserId { get; set; } } } From 96ad22a00931ffea7dba828d5a677dac3d45d83c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 01:01:36 +0100 Subject: [PATCH 049/125] Reduce log spam and clean up EncoderValidator --- .../Encoder/EncoderValidator.cs | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index fb131f304c..0f24a23702 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using MediaBrowser.Model.Diagnostics; using Microsoft.Extensions.Logging; @@ -73,7 +72,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private List GetDecoders(string encoderAppPath) { - string output = string.Empty; + string output = null; try { output = GetProcessOutput(encoderAppPath, "-decoders"); @@ -83,7 +82,11 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.LogError(ex, "Error detecting available decoders"); } - var found = new List(); + if (string.IsNullOrWhiteSpace(output)) + { + return new List(); + } + var required = new[] { "mpeg2video", @@ -101,17 +104,19 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc" }; + var found = new List(); foreach (var codec in required) { var srch = " " + codec + " "; if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) { - _logger.LogInformation("Decoder available: " + codec); found.Add(codec); } } + _logger.LogInformation("Available decoders: {Codecs}", found); + return found; } @@ -122,11 +127,16 @@ namespace MediaBrowser.MediaEncoding.Encoder { output = GetProcessOutput(encoderAppPath, "-encoders"); } - catch + catch (Exception ex) { + _logger.LogError(ex, "Error getting encoders"); + } + + if (string.IsNullOrWhiteSpace(output)) + { + return new List(); } - var found = new List(); var required = new[] { "libx264", @@ -151,26 +161,19 @@ namespace MediaBrowser.MediaEncoding.Encoder "ac3" }; - output = output ?? string.Empty; - - var index = 0; - + var found = new List(); foreach (var codec in required) { var srch = " " + codec + " "; if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) { - if (index < required.Length - 1) - { - _logger.LogInformation("Encoder available: " + codec); - } - found.Add(codec); } - index++; } + _logger.LogInformation("Available encoders: {Codecs}", found); + return found; } From 0042b96c806ce38b575b33246bdb56dfe73adace Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 01:23:49 +0100 Subject: [PATCH 050/125] Use ValueTuple and Linq --- .../Encoder/EncoderValidator.cs | 43 ++++++------------- .../Encoder/MediaEncoder.cs | 8 ++-- 2 files changed, 17 insertions(+), 34 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 0f24a23702..400fa0b81c 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using MediaBrowser.Model.Diagnostics; using Microsoft.Extensions.Logging; @@ -17,21 +18,21 @@ namespace MediaBrowser.MediaEncoding.Encoder _processFactory = processFactory; } - public Tuple, List> Validate(string encoderPath) + public (IEnumerable decoders, IEnumerable encoders) Validate(string encoderPath) { - _logger.LogInformation("Validating media encoder at {0}", encoderPath); + _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath); var decoders = GetDecoders(encoderPath); var encoders = GetEncoders(encoderPath); _logger.LogInformation("Encoder validation complete"); - return new Tuple, List>(decoders, encoders); + return (decoders, encoders); } public bool ValidateVersion(string encoderAppPath, bool logOutput) { - string output = string.Empty; + string output = null; try { output = GetProcessOutput(encoderAppPath, "-version"); @@ -70,7 +71,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return true; } - private List GetDecoders(string encoderAppPath) + private IEnumerable GetDecoders(string encoderAppPath) { string output = null; try @@ -84,7 +85,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (string.IsNullOrWhiteSpace(output)) { - return new List(); + return Enumerable.Empty(); } var required = new[] @@ -104,23 +105,14 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc" }; - var found = new List(); - foreach (var codec in required) - { - var srch = " " + codec + " "; - - if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) - { - found.Add(codec); - } - } + var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); _logger.LogInformation("Available decoders: {Codecs}", found); return found; } - private List GetEncoders(string encoderAppPath) + private IEnumerable GetEncoders(string encoderAppPath) { string output = null; try @@ -134,7 +126,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (string.IsNullOrWhiteSpace(output)) { - return new List(); + return Enumerable.Empty(); } var required = new[] @@ -161,16 +153,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "ac3" }; - var found = new List(); - foreach (var codec in required) - { - var srch = " " + codec + " "; - - if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1) - { - found.Add(codec); - } - } + var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); _logger.LogInformation("Available encoders: {Codecs}", found); @@ -179,7 +162,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private string GetProcessOutput(string path, string arguments) { - var process = _processFactory.Create(new ProcessOptions + IProcess process = _processFactory.Create(new ProcessOptions { CreateNoWindow = true, UseShellExecute = false, @@ -190,7 +173,7 @@ namespace MediaBrowser.MediaEncoding.Encoder RedirectStandardOutput = true }); - _logger.LogInformation("Running {path} {arguments}", path, arguments); + _logger.LogInformation("Running {Path} {Arguments}", path, arguments); using (process) { diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 181fc0f655..1d8cd67786 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -175,8 +175,8 @@ namespace MediaBrowser.MediaEncoding.Encoder { var result = new EncoderValidator(_logger, _processFactory).Validate(FFMpegPath); - SetAvailableDecoders(result.Item1); - SetAvailableEncoders(result.Item2); + SetAvailableDecoders(result.decoders); + SetAvailableEncoders(result.encoders); if (EnableEncoderFontFile) { @@ -401,14 +401,14 @@ namespace MediaBrowser.MediaEncoding.Encoder } private List _encoders = new List(); - public void SetAvailableEncoders(List list) + public void SetAvailableEncoders(IEnumerable list) { _encoders = list.ToList(); //_logger.Info("Supported encoders: {0}", string.Join(",", list.ToArray())); } private List _decoders = new List(); - public void SetAvailableDecoders(List list) + public void SetAvailableDecoders(IEnumerable list) { _decoders = list.ToList(); //_logger.Info("Supported decoders: {0}", string.Join(",", list.ToArray())); From 12c43cd76974fb795043c15d907251b5bb459a20 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 10:48:10 +0100 Subject: [PATCH 051/125] Use regex to check if ffmpeg output contains codec Demo of the regex: https://regex101.com/r/bn9IOy/10/ --- .../Encoder/EncoderValidator.cs | 88 +++++++++---------- 1 file changed, 41 insertions(+), 47 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 400fa0b81c..cafe3c64f1 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.RegularExpressions; using MediaBrowser.Model.Diagnostics; using Microsoft.Extensions.Logging; @@ -22,8 +23,8 @@ namespace MediaBrowser.MediaEncoding.Encoder { _logger.LogInformation("Validating media encoder at {EncoderPath}", encoderPath); - var decoders = GetDecoders(encoderPath); - var encoders = GetEncoders(encoderPath); + var decoders = GetCodecs(encoderPath, Codec.Decoder); + var encoders = GetCodecs(encoderPath, Codec.Encoder); _logger.LogInformation("Encoder validation complete"); @@ -71,24 +72,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return true; } - private IEnumerable GetDecoders(string encoderAppPath) - { - string output = null; - try - { - output = GetProcessOutput(encoderAppPath, "-decoders"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error detecting available decoders"); - } - - if (string.IsNullOrWhiteSpace(output)) - { - return Enumerable.Empty(); - } - - var required = new[] + private static readonly string[] requiredDecoders = new[] { "mpeg2video", "h264_qsv", @@ -105,31 +89,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc" }; - var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); - - _logger.LogInformation("Available decoders: {Codecs}", found); - - return found; - } - - private IEnumerable GetEncoders(string encoderAppPath) - { - string output = null; - try - { - output = GetProcessOutput(encoderAppPath, "-encoders"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error getting encoders"); - } - - if (string.IsNullOrWhiteSpace(output)) - { - return Enumerable.Empty(); - } - - var required = new[] + private static readonly string[] requiredEncoders = new[] { "libx264", "libx265", @@ -153,9 +113,43 @@ namespace MediaBrowser.MediaEncoding.Encoder "ac3" }; - var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); + private enum Codec + { + Encoder, + Decoder + } - _logger.LogInformation("Available encoders: {Codecs}", found); + private IEnumerable GetCodecs(string encoderAppPath, Codec codec) + { + string codecstr = codec == Codec.Encoder ? "encoders" : "decoders"; + string output = null; + try + { + output = GetProcessOutput(encoderAppPath, "-" + codecstr); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error detecting available {Codec}", codecstr); + } + + if (string.IsNullOrWhiteSpace(output)) + { + return Enumerable.Empty(); + } + + var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders; + + Regex regex = new Regex(@"\s\S{6}\s(?(\w|-)+)\s{3}"); + + MatchCollection matches = regex.Matches(output); + + var found = matches.Cast() + .Select(x => x.Groups["codec"].Value) + .Where(x => required.Contains(x)); + + //var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); + + _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found); return found; } From c05e8088d68a6e6f5b7ce6ed4462c072a347aed3 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 11:03:19 +0100 Subject: [PATCH 052/125] Remove extra capture group from regex https://regex101.com/r/bn9IOy/11/ --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index cafe3c64f1..abb827e310 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -139,7 +139,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders; - Regex regex = new Regex(@"\s\S{6}\s(?(\w|-)+)\s{3}"); + Regex regex = new Regex(@"\s\S{6}\s(?[\w|-]+)\s{3}"); MatchCollection matches = regex.Matches(output); @@ -147,8 +147,6 @@ namespace MediaBrowser.MediaEncoding.Encoder .Select(x => x.Groups["codec"].Value) .Where(x => required.Contains(x)); - //var found = required.Where(x => output.IndexOf(x, StringComparison.OrdinalIgnoreCase) != -1); - _logger.LogInformation("Available {Codec}: {Codecs}", codecstr, found); return found; From d6f3ca859eab462c12884a3e000a48a47eff6e4b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 11:13:33 +0100 Subject: [PATCH 053/125] Change regex to multiline ex: https://regex101.com/r/bn9IOy/12 --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index abb827e310..0a97434e3a 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -139,10 +139,8 @@ namespace MediaBrowser.MediaEncoding.Encoder var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders; - Regex regex = new Regex(@"\s\S{6}\s(?[\w|-]+)\s{3}"); - + Regex regex = new Regex(@"^\s\S{6}\s(?[\w|-]+)\s+.+$", RegexOptions.Multiline); MatchCollection matches = regex.Matches(output); - var found = matches.Cast() .Select(x => x.Groups["codec"].Value) .Where(x => required.Contains(x)); From f3030812ea8f79d4878a158695df0eb8a741b1e7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 11:32:35 +0100 Subject: [PATCH 054/125] Use static regex --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 0a97434e3a..b68961889e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -139,9 +139,9 @@ namespace MediaBrowser.MediaEncoding.Encoder var required = codec == Codec.Encoder ? requiredEncoders : requiredDecoders; - Regex regex = new Regex(@"^\s\S{6}\s(?[\w|-]+)\s+.+$", RegexOptions.Multiline); - MatchCollection matches = regex.Matches(output); - var found = matches.Cast() + var found = Regex + .Matches(output, @"^\s\S{6}\s(?[\w|-]+)\s+.+$", RegexOptions.Multiline) + .Cast() .Select(x => x.Groups["codec"].Value) .Where(x => required.Contains(x)); From ec47c5b0f7883cebc54a2d50cdb8e65d4e07084f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 15:12:52 +0100 Subject: [PATCH 055/125] Remove unused FontConfigLoader --- .../ApplicationHost.cs | 2 +- .../Encoder/FontConfigLoader.cs | 179 ------------------ .../Encoder/MediaEncoder.cs | 33 ++-- 3 files changed, 19 insertions(+), 195 deletions(-) delete mode 100644 MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f1e1b4b2d0..07705e9e44 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1240,7 +1240,7 @@ namespace Emby.Server.Implementations HttpClient, ZipClient, ProcessFactory, - 5000, false, + 5000, EnvironmentInfo); MediaEncoder = mediaEncoder; diff --git a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs b/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs deleted file mode 100644 index c62de0b113..0000000000 --- a/MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Common.Progress; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Net; -using Microsoft.Extensions.Logging; - -namespace MediaBrowser.MediaEncoding.Encoder -{ - public class FontConfigLoader - { - private readonly IHttpClient _httpClient; - private readonly IApplicationPaths _appPaths; - private readonly ILogger _logger; - private readonly IZipClient _zipClient; - private readonly IFileSystem _fileSystem; - - private readonly string[] _fontUrls = - { - "https://github.com/MediaBrowser/MediaBrowser.Resources/raw/master/ffmpeg/ARIALUNI.7z" - }; - - public FontConfigLoader(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, IZipClient zipClient, IFileSystem fileSystem) - { - _httpClient = httpClient; - _appPaths = appPaths; - _logger = logger; - _zipClient = zipClient; - _fileSystem = fileSystem; - } - - /// - /// Extracts the fonts. - /// - /// The target path. - /// Task. - public async Task DownloadFonts(string targetPath) - { - try - { - var fontsDirectory = Path.Combine(targetPath, "fonts"); - - _fileSystem.CreateDirectory(fontsDirectory); - - const string fontFilename = "ARIALUNI.TTF"; - - var fontFile = Path.Combine(fontsDirectory, fontFilename); - - if (_fileSystem.FileExists(fontFile)) - { - await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false); - } - else - { - // Kick this off, but no need to wait on it - var task = Task.Run(async () => - { - await DownloadFontFile(fontsDirectory, fontFilename, new SimpleProgress()).ConfigureAwait(false); - - await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false); - }); - } - } - catch (HttpException ex) - { - // Don't let the server crash because of this - _logger.LogError(ex, "Error downloading ffmpeg font files"); - } - catch (Exception ex) - { - // Don't let the server crash because of this - _logger.LogError(ex, "Error writing ffmpeg font files"); - } - } - - /// - /// Downloads the font file. - /// - /// The fonts directory. - /// The font filename. - /// Task. - private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress progress) - { - var existingFile = _fileSystem - .GetFilePaths(_appPaths.ProgramDataPath, true) - .FirstOrDefault(i => string.Equals(fontFilename, Path.GetFileName(i), StringComparison.OrdinalIgnoreCase)); - - if (existingFile != null) - { - try - { - _fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true); - return; - } - catch (IOException ex) - { - // Log this, but don't let it fail the operation - _logger.LogError(ex, "Error copying file"); - } - } - - string tempFile = null; - - foreach (var url in _fontUrls) - { - progress.Report(0); - - try - { - tempFile = await _httpClient.GetTempFile(new HttpRequestOptions - { - Url = url, - Progress = progress - - }).ConfigureAwait(false); - - break; - } - catch (Exception ex) - { - // The core can function without the font file, so handle this - _logger.LogError(ex, "Failed to download ffmpeg font file from {url}", url); - } - } - - if (string.IsNullOrEmpty(tempFile)) - { - return; - } - - Extract7zArchive(tempFile, fontsDirectory); - - try - { - _fileSystem.DeleteFile(tempFile); - } - catch (IOException ex) - { - // Log this, but don't let it fail the operation - _logger.LogError(ex, "Error deleting temp file {path}", tempFile); - } - } - private void Extract7zArchive(string archivePath, string targetPath) - { - _logger.LogInformation("Extracting {ArchivePath} to {TargetPath}", archivePath, targetPath); - - _zipClient.ExtractAllFrom7z(archivePath, targetPath, true); - } - - /// - /// Writes the font config file. - /// - /// The fonts directory. - /// Task. - private async Task WriteFontConfigFile(string fontsDirectory) - { - const string fontConfigFilename = "fonts.conf"; - var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename); - - if (!_fileSystem.FileExists(fontConfigFile)) - { - var contents = string.Format("{0}ArialArial Unicode MS", fontsDirectory); - - var bytes = Encoding.UTF8.GetBytes(contents); - - using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileOpenMode.Create, FileAccessMode.Write, - FileShareMode.Read, true)) - { - await fileStream.WriteAsync(bytes, 0, bytes.Length); - } - } - } - } -} diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 1d8cd67786..a93dd97421 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -70,13 +70,27 @@ namespace MediaBrowser.MediaEncoding.Encoder private readonly string _originalFFMpegPath; private readonly string _originalFFProbePath; private readonly int DefaultImageExtractionTimeoutMs; - private readonly bool EnableEncoderFontFile; - private readonly IEnvironmentInfo _environmentInfo; - public MediaEncoder(ILogger logger, IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, bool hasExternalEncoder, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILiveTvManager liveTvManager, IIsoManager isoManager, ILibraryManager libraryManager, IChannelManager channelManager, ISessionManager sessionManager, Func subtitleEncoder, Func mediaSourceManager, IHttpClient httpClient, IZipClient zipClient, IProcessFactory processFactory, + public MediaEncoder(ILogger logger, + IJsonSerializer jsonSerializer, + string ffMpegPath, + string ffProbePath, + bool hasExternalEncoder, + IServerConfigurationManager configurationManager, + IFileSystem fileSystem, + ILiveTvManager liveTvManager, + IIsoManager isoManager, + ILibraryManager libraryManager, + IChannelManager channelManager, + ISessionManager sessionManager, + Func subtitleEncoder, + Func mediaSourceManager, + IHttpClient httpClient, + IZipClient zipClient, + IProcessFactory processFactory, int defaultImageExtractionTimeoutMs, - bool enableEncoderFontFile, IEnvironmentInfo environmentInfo) + IEnvironmentInfo environmentInfo) { _logger = logger; _jsonSerializer = jsonSerializer; @@ -93,7 +107,6 @@ namespace MediaBrowser.MediaEncoding.Encoder _zipClient = zipClient; _processFactory = processFactory; DefaultImageExtractionTimeoutMs = defaultImageExtractionTimeoutMs; - EnableEncoderFontFile = enableEncoderFontFile; _environmentInfo = environmentInfo; FFProbePath = ffProbePath; FFMpegPath = ffMpegPath; @@ -177,16 +190,6 @@ namespace MediaBrowser.MediaEncoding.Encoder SetAvailableDecoders(result.decoders); SetAvailableEncoders(result.encoders); - - if (EnableEncoderFontFile) - { - var directory = FileSystem.GetDirectoryName(FFMpegPath); - - if (!string.IsNullOrWhiteSpace(directory) && FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.ProgramDataPath, directory)) - { - new FontConfigLoader(_httpClient, ConfigurationManager.ApplicationPaths, _logger, _zipClient, FileSystem).DownloadFonts(directory).ConfigureAwait(false); - } - } } } From 3a65fb1da2009df246ae6f1252d44d24e882e554 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 12:14:31 +0100 Subject: [PATCH 056/125] Remove obsolete GetMBId --- .../Channels/ChannelManager.cs | 4 ++-- .../Extensions/BaseExtensions.cs | 20 ------------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 00da46f303..c2160d3384 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -901,8 +901,8 @@ namespace Emby.Server.Implementations.Channels private T GetItemById(string idString, string channelName, out bool isNew) where T : BaseItem, new() { - var id = GetIdToHash(idString, channelName).GetMBId(typeof(T)); - + var id = _libraryManager.GetNewItemId(GetIdToHash(idString, channelName), typeof(T)); + T item = null; try diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs index d7f4424faa..520c04244e 100644 --- a/MediaBrowser.Common/Extensions/BaseExtensions.cs +++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs @@ -34,25 +34,5 @@ namespace MediaBrowser.Common.Extensions { return CryptographyProvider.GetMD5(str); } - - /// - /// Gets the MB id. - /// - /// The STR. - /// The type. - /// Guid. - /// type - [Obsolete("Use LibraryManager.GetNewItemId")] - public static Guid GetMBId(this string str, Type type) - { - if (type == null) - { - throw new ArgumentNullException("type"); - } - - var key = type.FullName + str.ToLower(); - - return key.GetMD5(); - } } } From 32469b3f65596e115bb04427cd1e5daafbb69312 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 12:15:05 +0100 Subject: [PATCH 057/125] Remove obsolete functions --- .../IO/SharpCifs/Smb/SmbFile.cs | 20 ---- .../Networking/IPNetwork/IPNetwork.cs | 106 +----------------- 2 files changed, 2 insertions(+), 124 deletions(-) diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs index 151ec35c48..7fd9f0d84e 100644 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs +++ b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs @@ -3380,26 +3380,6 @@ namespace SharpCifs.Smb SetAttributes(GetAttributes() & ~AttrReadonly); } - /// - /// Returns a - /// System.Uri - /// for this SmbFile. The - /// URL may be used as any other URL might to - /// access an SMB resource. Currently only retrieving data and information - /// is supported (i.e. no doOutput). - /// - /// - /// A new - /// System.Uri - /// for this SmbFile - /// - /// System.UriFormatException - [Obsolete(@"Use getURL() instead")] - public virtual Uri ToUrl() - { - return Url; - } - /// /// Computes a hashCode for this file based on the URL string and IP /// address if the server. diff --git a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs b/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs index 6d7785b906..8d0fb79971 100644 --- a/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs +++ b/Emby.Server.Implementations/Networking/IPNetwork/IPNetwork.cs @@ -189,7 +189,7 @@ namespace System.Net internal #endif - IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr) + IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr) { int maxCidr = family == Sockets.AddressFamily.InterNetwork ? 32 : 128; @@ -1164,18 +1164,6 @@ namespace System.Net } - [Obsolete("static Contains is deprecated, please use instance Contains.")] - public static bool Contains(IPNetwork network, IPAddress ipaddress) - { - - if (network == null) - { - throw new ArgumentNullException("network"); - } - - return network.Contains(ipaddress); - } - /// /// return true is network2 is fully contained in network /// @@ -1201,18 +1189,6 @@ namespace System.Net return contains; } - [Obsolete("static Contains is deprecated, please use instance Contains.")] - public static bool Contains(IPNetwork network, IPNetwork network2) - { - - if (network == null) - { - throw new ArgumentNullException("network"); - } - - return network.Contains(network2); - } - #endregion #region overlap @@ -1245,18 +1221,6 @@ namespace System.Net return overlap; } - [Obsolete("static Overlap is deprecated, please use instance Overlap.")] - public static bool Overlap(IPNetwork network, IPNetwork network2) - { - - if (network == null) - { - throw new ArgumentNullException("network"); - } - - return network.Overlap(network2); - } - #endregion #region ToString @@ -1341,18 +1305,6 @@ namespace System.Net || IPNetwork.IANA_CBLK_RESERVED1.Contains(this); } - [Obsolete("static IsIANAReserved is deprecated, please use instance IsIANAReserved.")] - public static bool IsIANAReserved(IPNetwork ipnetwork) - { - - if (ipnetwork == null) - { - throw new ArgumentNullException("ipnetwork"); - } - - return ipnetwork.IsIANAReserved(); - } - #endregion #region Subnet @@ -1371,16 +1323,6 @@ namespace System.Net return ipnetworkCollection; } - [Obsolete("static Subnet is deprecated, please use instance Subnet.")] - public static IPNetworkCollection Subnet(IPNetwork network, byte cidr) - { - if (network == null) - { - throw new ArgumentNullException("network"); - } - return network.Subnet(cidr); - } - /// /// Subnet a network into multiple nets of cidr mask /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25 @@ -1402,16 +1344,6 @@ namespace System.Net return true; } - [Obsolete("static TrySubnet is deprecated, please use instance TrySubnet.")] - public static bool TrySubnet(IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection) - { - if (network == null) - { - throw new ArgumentNullException("network"); - } - return network.TrySubnet(cidr, out ipnetworkCollection); - } - #if TRAVISCI public #else @@ -1476,12 +1408,6 @@ namespace System.Net return supernet; } - [Obsolete("static Supernet is deprecated, please use instance Supernet.")] - public static IPNetwork Supernet(IPNetwork network, IPNetwork network2) - { - return network.Supernet(network2); - } - /// /// Try to supernet two consecutive cidr equal subnet into a single one /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23 @@ -1500,16 +1426,6 @@ namespace System.Net return parsed; } - [Obsolete("static TrySupernet is deprecated, please use instance TrySupernet.")] - public static bool TrySupernet(IPNetwork network, IPNetwork network2, out IPNetwork supernet) - { - if (network == null) - { - throw new ArgumentNullException("network"); - } - return network.TrySupernet(network2, out supernet); - } - #if TRAVISCI public #else @@ -1920,18 +1836,6 @@ namespace System.Net return sw.ToString(); } - [Obsolete("static Print is deprecated, please use instance Print.")] - public static string Print(IPNetwork ipnetwork) - { - - if (ipnetwork == null) - { - throw new ArgumentNullException("ipnetwork"); - } - - return ipnetwork.Print(); - } - #endregion #region TryGuessCidr @@ -2018,12 +1922,6 @@ namespace System.Net #region ListIPAddress - [Obsolete("static ListIPAddress is deprecated, please use instance ListIPAddress.")] - public static IPAddressCollection ListIPAddress(IPNetwork ipnetwork) - { - return ipnetwork.ListIPAddress(); - } - public IPAddressCollection ListIPAddress() { return new IPAddressCollection(this); @@ -2167,4 +2065,4 @@ namespace System.Net #endregion } -} \ No newline at end of file +} From 40563dc6cc30e45ace90db30a934478395d8c7c1 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 17:09:40 +0100 Subject: [PATCH 058/125] Remove GitHub updater and don't trow exception in release --- .../ApplicationHost.cs | 49 +--- Jellyfin.Server/CoreAppHost.cs | 4 +- Jellyfin.Server/Program.cs | 1 - MediaBrowser.Common/Updates/GithubUpdater.cs | 274 ------------------ 4 files changed, 7 insertions(+), 321 deletions(-) delete mode 100644 MediaBrowser.Common/Updates/GithubUpdater.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f1e1b4b2d0..5853d20c8f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -368,7 +368,6 @@ namespace Emby.Server.Implementations protected IAuthService AuthService { get; private set; } public StartupOptions StartupOptions { get; private set; } - protected readonly string ReleaseAssetFilename; internal IPowerManagement PowerManagement { get; private set; } internal IImageEncoder ImageEncoder { get; private set; } @@ -393,7 +392,6 @@ namespace Emby.Server.Implementations StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, - string releaseAssetFilename, IEnvironmentInfo environmentInfo, IImageEncoder imageEncoder, ISystemEvents systemEvents, @@ -419,7 +417,6 @@ namespace Emby.Server.Implementations Logger = LoggerFactory.CreateLogger("App"); StartupOptions = options; - ReleaseAssetFilename = releaseAssetFilename; PowerManagement = powerManagement; ImageEncoder = imageEncoder; @@ -2292,48 +2289,12 @@ namespace Emby.Server.Implementations /// The cancellation token. /// The progress. /// Task{CheckForUpdateResult}. - public async Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) + public Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) { - var updateLevel = SystemUpdateLevel; - var cacheLength = updateLevel == PackageVersionClass.Release ? - TimeSpan.FromHours(12) : - TimeSpan.FromMinutes(5); - - try - { - var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser", - "Emby.Releases", - ApplicationVersion, - updateLevel, - ReleaseAssetFilename, - "MBServer", - UpdateTargetFileName, - cacheLength, - cancellationToken).ConfigureAwait(false); - - HasUpdateAvailable = result.IsUpdateAvailable; - - return result; - } - catch (HttpException ex) - { - // users are overreacting to this occasionally failing - if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.Forbidden) - { - HasUpdateAvailable = false; - return new CheckForUpdateResult - { - IsUpdateAvailable = false - }; - } - - throw; - } - } - - protected virtual string UpdateTargetFileName - { - get { return "Mbserver.zip"; } +#if DEBUG + throw new Exception("Unimplemented"); +#endif + return Task.FromResult(new CheckForUpdateResult()); } /// diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 2fb106b3c0..b546343871 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -11,8 +11,8 @@ namespace Jellyfin.Server { public class CoreAppHost : ApplicationHost { - public CoreAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, string releaseAssetFilename, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) - : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, releaseAssetFilename, environmentInfo, imageEncoder, systemEvents, networkManager) + public CoreAppHost(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, StartupOptions options, IFileSystem fileSystem, IPowerManagement powerManagement, IEnvironmentInfo environmentInfo, MediaBrowser.Controller.Drawing.IImageEncoder imageEncoder, ISystemEvents systemEvents, MediaBrowser.Common.Net.INetworkManager networkManager) + : base(applicationPaths, loggerFactory, options, fileSystem, powerManagement, environmentInfo, imageEncoder, systemEvents, networkManager) { } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 0150cd5337..9cc2fe1036 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -73,7 +73,6 @@ namespace Jellyfin.Server options, fileSystem, new PowerManagement(), - "embyserver-mono_{version}.zip", environmentInfo, new NullImageEncoder(), new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")), diff --git a/MediaBrowser.Common/Updates/GithubUpdater.cs b/MediaBrowser.Common/Updates/GithubUpdater.cs deleted file mode 100644 index 22ed788e0c..0000000000 --- a/MediaBrowser.Common/Updates/GithubUpdater.cs +++ /dev/null @@ -1,274 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.Updates; - -namespace MediaBrowser.Common.Updates -{ - public class GithubUpdater - { - private readonly IHttpClient _httpClient; - private readonly IJsonSerializer _jsonSerializer; - - public GithubUpdater(IHttpClient httpClient, IJsonSerializer jsonSerializer) - { - _httpClient = httpClient; - _jsonSerializer = jsonSerializer; - } - - public async Task CheckForUpdateResult(string organzation, string repository, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename, TimeSpan cacheLength, CancellationToken cancellationToken) - { - var url = string.Format("https://api.github.com/repos/{0}/{1}/releases", organzation, repository); - - var options = new HttpRequestOptions - { - Url = url, - EnableKeepAlive = false, - CancellationToken = cancellationToken, - UserAgent = "Emby/3.0", - BufferContent = false - }; - - if (cacheLength.Ticks > 0) - { - options.CacheMode = CacheMode.Unconditional; - options.CacheLength = cacheLength; - } - - using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) - using (var stream = response.Content) - { - var obj = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false); - - return CheckForUpdateResult(obj, minVersion, updateLevel, assetFilename, packageName, targetFilename); - } - } - - private CheckForUpdateResult CheckForUpdateResult(RootObject[] obj, Version minVersion, PackageVersionClass updateLevel, string assetFilename, string packageName, string targetFilename) - { - if (updateLevel == PackageVersionClass.Release) - { - // Technically all we need to do is check that it's not pre-release - // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly. - obj = obj.Where(i => !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) && !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase)).ToArray(); - } - else if (updateLevel == PackageVersionClass.Beta) - { - 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)) - .Where(i => i != null) - .OrderByDescending(i => Version.Parse(i.AvailableVersion)) - .FirstOrDefault(); - - return availableUpdate ?? new CheckForUpdateResult - { - IsUpdateAvailable = false - }; - } - - private bool MatchesUpdateLevel(RootObject i, PackageVersionClass updateLevel) - { - if (updateLevel == PackageVersionClass.Beta) - { - return i.prerelease && i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase); - } - if (updateLevel == PackageVersionClass.Dev) - { - return !i.prerelease || i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) || - i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase); - } - - // Technically all we need to do is check that it's not pre-release - // But let's addititional checks for -beta and -dev to handle builds that might be temporarily tagged incorrectly. - return !i.prerelease && !i.name.EndsWith("-beta", StringComparison.OrdinalIgnoreCase) && - !i.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase); - } - - public async Task> GetLatestReleases(string organzation, string repository, string assetFilename, CancellationToken cancellationToken) - { - var list = new List(); - - 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", - BufferContent = false - }; - - using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) - using (var stream = response.Content) - { - var obj = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false); - - obj = obj.Where(i => (i.assets ?? new List()).Any(a => IsAsset(a, assetFilename, i.tag_name))).ToArray(); - - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Release)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Beta)).OrderByDescending(GetVersion).Take(1)); - list.AddRange(obj.Where(i => MatchesUpdateLevel(i, PackageVersionClass.Dev)).OrderByDescending(GetVersion).Take(1)); - - return list; - } - } - - public Version GetVersion(RootObject obj) - { - Version version; - if (!Version.TryParse(obj.tag_name, out version)) - { - return new Version(1, 0); - } - - return version; - } - - private CheckForUpdateResult CheckForUpdateResult(RootObject obj, Version minVersion, string assetFilename, string packageName, string targetFilename) - { - Version version; - var versionString = obj.tag_name; - if (!Version.TryParse(versionString, out version)) - { - return null; - } - - if (version < minVersion) - { - return null; - } - - var asset = (obj.assets ?? new List()).FirstOrDefault(i => IsAsset(i, assetFilename, versionString)); - - if (asset == null) - { - return null; - } - - return new CheckForUpdateResult - { - AvailableVersion = version.ToString(), - IsUpdateAvailable = version > minVersion, - Package = new PackageVersionInfo - { - classification = obj.prerelease ? - (obj.name.EndsWith("-dev", StringComparison.OrdinalIgnoreCase) ? PackageVersionClass.Dev : PackageVersionClass.Beta) : - PackageVersionClass.Release, - name = packageName, - sourceUrl = asset.browser_download_url, - targetFilename = targetFilename, - versionStr = version.ToString(), - requiredVersionStr = "1.0.0", - description = obj.body, - infoUrl = obj.html_url - } - }; - } - - private bool IsAsset(Asset asset, string assetFilename, string version) - { - var downloadFilename = Path.GetFileName(asset.browser_download_url) ?? string.Empty; - - assetFilename = assetFilename.Replace("{version}", version); - - if (downloadFilename.IndexOf(assetFilename, StringComparison.OrdinalIgnoreCase) != -1) - { - return true; - } - - return string.Equals(assetFilename, downloadFilename, StringComparison.OrdinalIgnoreCase); - } - - 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; } - } - } -} From 7679ed037f4bfa31762fc1ff40cec8297105d658 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 17:54:26 +0100 Subject: [PATCH 059/125] Disable SystemUpdateTask --- Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs index 4cb97cbdae..890a20ddf7 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs @@ -13,7 +13,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Plugin Update Task /// - public class SystemUpdateTask : IScheduledTask + public class SystemUpdateTask /*: IScheduledTask*/ { /// /// The _app host From a064a93a8e6ee0fe5dd1266db8d4a84d04d83e7e Mon Sep 17 00:00:00 2001 From: Sparky Date: Wed, 2 Jan 2019 12:01:03 -0500 Subject: [PATCH 060/125] Admin and first setup pages default to dark theme Since the user facing sides of the UI (login and library) are all dark theme by default, changes the default look for the admin sides (first time setup, admin panel) as well. --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index ff9e522592..9bbfd9b745 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ !* +.directory + ################# ## Eclipse ################# From 36a109cb0f5bd22daae2895948b357b366b5062f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 18:03:03 +0100 Subject: [PATCH 061/125] Disable PluginUpdateTask --- Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs index 46a7f1f277..9b3571ac22 100644 --- a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Plugin Update Task /// - public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask + public class PluginUpdateTask /*: IScheduledTask, IConfigurableScheduledTask*/ { /// /// The _logger From 78dafb5399941e0e1b6110c6424d06f4477e80cc Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 18:05:04 +0100 Subject: [PATCH 062/125] Throw exception when calling unreachable function --- Emby.Server.Implementations/ApplicationHost.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 5853d20c8f..98c7cf38b6 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -2291,10 +2291,7 @@ namespace Emby.Server.Implementations /// Task{CheckForUpdateResult}. public Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) { -#if DEBUG throw new Exception("Unimplemented"); -#endif - return Task.FromResult(new CheckForUpdateResult()); } /// From 141661573a7b0d221f26bbc3901cf53c34f66fd2 Mon Sep 17 00:00:00 2001 From: Sparky Date: Wed, 2 Jan 2019 12:06:53 -0500 Subject: [PATCH 063/125] Add myself to contributors file --- CONTRIBUTORS.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3a2c229d11..e6892313c5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,15 +8,16 @@ - [flemse](https://github.com/flemse) - [bfayers](https://github.com/bfayers) - [Bond_009](https://github.com/Bond-009) + - [sparky8251](https://github.com/sparky8251) # Emby Contributors - - [LukePulverenti](https://github.com/LukePulverenti) - - [ebr11](https://github.com/ebr11) - - [lalmanzar](https://github.com/lalmanzar) - - [schneifu](https://github.com/schneifu) - - [Mark2xv](https://github.com/Mark2xv) - - [ScottRapsey](https://github.com/ScottRapsey) + - [LukePulverenti](https://github.com/LukePulverenti) + - [ebr11](https://github.com/ebr11) + - [lalmanzar](https://github.com/lalmanzar) + - [schneifu](https://github.com/schneifu) + - [Mark2xv](https://github.com/Mark2xv) + - [ScottRapsey](https://github.com/ScottRapsey) - [skynet600](https://github.com/skynet600) - [Cheesegeezer](https://githum.com/Cheesegeezer) - [Radeon](https://github.com/radeonorama) From 3fa751e9bbef072c5bb4c39aad1aede8ced1c003 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 18:10:52 +0100 Subject: [PATCH 064/125] Remove CheckForApplicationUpdate function --- Emby.Server.Implementations/ApplicationHost.cs | 11 ----------- .../ScheduledTasks/PluginUpdateTask.cs | 5 +++-- .../ScheduledTasks/SystemUpdateTask.cs | 5 +++-- MediaBrowser.Common/IApplicationHost.cs | 6 ------ 4 files changed, 6 insertions(+), 21 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 98c7cf38b6..fe615fab0a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -2283,17 +2283,6 @@ namespace Emby.Server.Implementations Plugins = list.ToArray(); } - /// - /// Checks for update. - /// - /// The cancellation token. - /// The progress. - /// Task{CheckForUpdateResult}. - public Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress) - { - throw new Exception("Unimplemented"); - } - /// /// Updates the application. /// diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs index 9b3571ac22..8c562e4523 100644 --- a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Common; +/*using MediaBrowser.Common; using MediaBrowser.Common.Updates; using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Plugin Update Task /// - public class PluginUpdateTask /*: IScheduledTask, IConfigurableScheduledTask*/ + public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask { /// /// The _logger @@ -140,3 +140,4 @@ namespace Emby.Server.Implementations.ScheduledTasks public bool IsLogged => true; } } +*/ diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs index 890a20ddf7..18ff33e953 100644 --- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Common; +/*using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using Microsoft.Extensions.Logging; using System; @@ -13,7 +13,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Plugin Update Task /// - public class SystemUpdateTask /*: IScheduledTask*/ + public class SystemUpdateTask : IScheduledTask { /// /// The _app host @@ -126,3 +126,4 @@ namespace Emby.Server.Implementations.ScheduledTasks } } } +*/ diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 32b942b60d..39d69ea15c 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -85,12 +85,6 @@ namespace MediaBrowser.Common /// IEnumerable{``0}. IEnumerable GetExports(bool manageLiftime = true); - /// - /// Checks for update. - /// - /// Task{CheckForUpdateResult}. - Task CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress progress); - /// /// Updates the application. /// From e12888c2c5288ab2e313d74b6fad01a82720f4e2 Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Wed, 2 Jan 2019 12:21:07 -0500 Subject: [PATCH 065/125] restore spaces in CONTRIBUTORS.md --- CONTRIBUTORS.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fad5796475..fdec0e75a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -12,12 +12,12 @@ # Emby Contributors - - [LukePulverenti](https://github.com/LukePulverenti) - - [ebr11](https://github.com/ebr11) - - [lalmanzar](https://github.com/lalmanzar) - - [schneifu](https://github.com/schneifu) - - [Mark2xv](https://github.com/Mark2xv) - - [ScottRapsey](https://github.com/ScottRapsey) + - [LukePulverenti](https://github.com/LukePulverenti) + - [ebr11](https://github.com/ebr11) + - [lalmanzar](https://github.com/lalmanzar) + - [schneifu](https://github.com/schneifu) + - [Mark2xv](https://github.com/Mark2xv) + - [ScottRapsey](https://github.com/ScottRapsey) - [skynet600](https://github.com/skynet600) - [Cheesegeezer](https://githum.com/Cheesegeezer) - [Radeon](https://github.com/radeonorama) From 1fb975c6e766ba40a637d0c9996c1d309b05e8fb Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 2 Jan 2019 18:44:06 +0100 Subject: [PATCH 066/125] Delete SystemUpdateTask.cs --- .../ScheduledTasks/SystemUpdateTask.cs | 129 ------------------ 1 file changed, 129 deletions(-) delete mode 100644 Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs diff --git a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs deleted file mode 100644 index 18ff33e953..0000000000 --- a/Emby.Server.Implementations/ScheduledTasks/SystemUpdateTask.cs +++ /dev/null @@ -1,129 +0,0 @@ -/*using MediaBrowser.Common; -using MediaBrowser.Common.Configuration; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Progress; -using MediaBrowser.Model.Tasks; - -namespace Emby.Server.Implementations.ScheduledTasks -{ - /// - /// Plugin Update Task - /// - public class SystemUpdateTask : IScheduledTask - { - /// - /// The _app host - /// - private readonly IApplicationHost _appHost; - - /// - /// Gets or sets the configuration manager. - /// - /// The configuration manager. - private IConfigurationManager ConfigurationManager { get; set; } - /// - /// Gets or sets the logger. - /// - /// The logger. - private ILogger Logger { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The app host. - /// The configuration manager. - /// The logger. - public SystemUpdateTask(IApplicationHost appHost, IConfigurationManager configurationManager, ILogger logger) - { - _appHost = appHost; - ConfigurationManager = configurationManager; - Logger = logger; - } - - /// - /// Creates the triggers that define when the task will run - /// - /// IEnumerable{BaseTaskTrigger}. - public IEnumerable GetDefaultTriggers() - { - return new[] { - - // At startup - new TaskTriggerInfo {Type = TaskTriggerInfo.TriggerStartup}, - - // Every so often - new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks} - }; - } - - /// - /// Returns the task to be executed - /// - /// The cancellation token. - /// The progress. - /// Task. - public async Task Execute(CancellationToken cancellationToken, IProgress progress) - { - // Create a progress object for the update check - var updateInfo = await _appHost.CheckForApplicationUpdate(cancellationToken, new SimpleProgress()).ConfigureAwait(false); - - if (!updateInfo.IsUpdateAvailable) - { - Logger.LogDebug("No application update available."); - return; - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (!_appHost.CanSelfUpdate) return; - - if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate) - { - Logger.LogInformation("Update Revision {0} available. Updating...", updateInfo.AvailableVersion); - - await _appHost.UpdateApplication(updateInfo.Package, cancellationToken, progress).ConfigureAwait(false); - } - else - { - Logger.LogInformation("A new version of " + _appHost.Name + " is available."); - } - } - - /// - /// Gets the name of the task - /// - /// The name. - public string Name - { - get { return "Check for application updates"; } - } - - /// - /// Gets the description. - /// - /// The description. - public string Description - { - get { return "Downloads and installs application updates."; } - } - - /// - /// Gets the category. - /// - /// The category. - public string Category - { - get { return "Application"; } - } - - public string Key - { - get { return "SystemUpdateTask"; } - } - } -} -*/ From f1bf87665ffeefa0fd3e3a716312d02f20f56231 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 2 Jan 2019 18:44:19 +0100 Subject: [PATCH 067/125] Delete PluginUpdateTask.cs --- .../ScheduledTasks/PluginUpdateTask.cs | 143 ------------------ 1 file changed, 143 deletions(-) delete mode 100644 Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs diff --git a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs deleted file mode 100644 index 8c562e4523..0000000000 --- a/Emby.Server.Implementations/ScheduledTasks/PluginUpdateTask.cs +++ /dev/null @@ -1,143 +0,0 @@ -/*using MediaBrowser.Common; -using MediaBrowser.Common.Updates; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Net; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Progress; -using MediaBrowser.Model.Tasks; - -namespace Emby.Server.Implementations.ScheduledTasks -{ - /// - /// Plugin Update Task - /// - public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask - { - /// - /// The _logger - /// - private readonly ILogger _logger; - - private readonly IInstallationManager _installationManager; - - private readonly IApplicationHost _appHost; - - public PluginUpdateTask(ILogger logger, IInstallationManager installationManager, IApplicationHost appHost) - { - _logger = logger; - _installationManager = installationManager; - _appHost = appHost; - } - - /// - /// Creates the triggers that define when the task will run - /// - /// IEnumerable{BaseTaskTrigger}. - public IEnumerable GetDefaultTriggers() - { - return new[] { - - // At startup - new TaskTriggerInfo {Type = TaskTriggerInfo.TriggerStartup}, - - // Every so often - new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks} - }; - } - - public string Key - { - get { return "PluginUpdates"; } - } - - /// - /// Update installed plugins - /// - /// The cancellation token. - /// The progress. - /// Task. - public async Task Execute(CancellationToken cancellationToken, IProgress progress) - { - progress.Report(0); - - var packagesToInstall = (await _installationManager.GetAvailablePluginUpdates(_appHost.ApplicationVersion, true, cancellationToken).ConfigureAwait(false)).ToList(); - - progress.Report(10); - - var numComplete = 0; - - foreach (var package in packagesToInstall) - { - cancellationToken.ThrowIfCancellationRequested(); - - try - { - await _installationManager.InstallPackage(package, true, new SimpleProgress(), cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - // InstallPackage has it's own inner cancellation token, so only throw this if it's ours - if (cancellationToken.IsCancellationRequested) - { - throw; - } - } - catch (HttpException ex) - { - _logger.LogError(ex, "Error downloading {name}", package.name); - } - catch (IOException ex) - { - _logger.LogError(ex, "Error updating {name}", package.name); - } - - // Update progress - lock (progress) - { - numComplete++; - double percent = numComplete; - percent /= packagesToInstall.Count; - - progress.Report(90 * percent + 10); - } - } - - progress.Report(100); - } - - /// - /// Gets the name of the task - /// - /// The name. - public string Name - { - get { return "Check for plugin updates"; } - } - - /// - /// Gets the description. - /// - /// The description. - public string Description - { - get { return "Downloads and installs updates for plugins that are configured to update automatically."; } - } - - public string Category - { - get { return "Application"; } - } - - public bool IsHidden => true; - - public bool IsEnabled => true; - - public bool IsLogged => true; - } -} -*/ From 1d6987c7131c36fa50c8f85ab140038b71eaf83c Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Wed, 2 Jan 2019 19:13:35 +0100 Subject: [PATCH 068/125] added todo --- Emby.Server.Implementations/Devices/DeviceManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index 2503162118..82df96d8b5 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -145,7 +145,8 @@ namespace Emby.Server.Implementations.Devices HasUser = true }).Items; - + + // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger. if (query.SupportsSync.HasValue) { var val = query.SupportsSync.Value; From 8adcce5c6411dbb017e4c70d0651f5870207b090 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 2 Jan 2019 20:12:24 +0100 Subject: [PATCH 069/125] DeleteLogFileTask: only delete the .txt log files --- .../ScheduledTasks/Tasks/DeleteLogFileTask.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs index d5a7ccadb6..b754d7cb52 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs @@ -56,7 +56,8 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks // Delete log files more than n days old var minDateModified = DateTime.UtcNow.AddDays(-ConfigurationManager.CommonConfiguration.LogFileRetentionDays); - var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, true) + // Only delete the .txt log files, the *.log files created by serilog get managed by itself + var filesToDelete = _fileSystem.GetFiles(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, new[] { ".txt" }, true, true) .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified) .ToList(); @@ -64,8 +65,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks foreach (var file in filesToDelete) { - double percent = index; - percent /= filesToDelete.Count; + double percent = index / filesToDelete.Count; progress.Report(100 * percent); From efa3a234e912b9c2740d24f78c16ade07e9c5ce5 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Thu, 3 Jan 2019 07:58:14 +0100 Subject: [PATCH 070/125] Change null check on UserId to a Guid.Empty check --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index af56f63826..28e75bf55b 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -686,7 +686,7 @@ namespace MediaBrowser.Api.Playback }; var auth = AuthorizationContext.GetAuthorizationInfo(Request); - if (auth.UserId != null) + if (!auth.UserId.Equals(Guid.Empty)) { state.User = UserManager.GetUserById(auth.UserId); } From a1b96a3135bdae274db58ef35ab35708f2257896 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 26 Dec 2018 01:16:02 +0100 Subject: [PATCH 071/125] Clean up HttpClientManager, LiveTvManager and InstallationManager --- .../ApplicationHost.cs | 9 +- .../HttpClientManager/HttpClientManager.cs | 139 ++++------ .../LiveTv/Listings/SchedulesDirect.cs | 200 ++++++-------- .../LiveTv/LiveTvManager.cs | 249 ++++++------------ .../Updates/InstallationManager.cs | 6 +- MediaBrowser.Common/Net/IHttpClient.cs | 7 +- 6 files changed, 227 insertions(+), 383 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 3cc6151f13..ff6586ac1e 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -640,15 +640,14 @@ namespace Emby.Server.Implementations /// Gets the exports. /// /// - /// if set to true [manage liftime]. + /// if set to true [manage lifetime]. /// IEnumerable{``0}. public IEnumerable GetExports(bool manageLifetime = true) { var parts = GetExportTypes() .Select(CreateInstanceSafe) .Where(i => i != null) - .Cast() - .ToList(); + .Cast(); if (manageLifetime) { @@ -703,7 +702,7 @@ namespace Emby.Server.Implementations /// /// Runs the startup tasks. /// - public async Task RunStartupTasks() + public Task RunStartupTasks() { Resolve().AddTasks(GetExports(false)); @@ -736,6 +735,8 @@ namespace Emby.Server.Implementations Logger.LogInformation("All entry points have started"); //LoggerFactory.RemoveConsoleOutput(); + + return Task.CompletedTask; } private void RunEntryPoints(IEnumerable entryPoints, bool isBeforeStartup) diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 23dd55b183..a2f508b80d 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -5,18 +5,15 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net; -using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; -using Emby.Server.Implementations.IO; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; using MediaBrowser.Model.Net; -using MediaBrowser.Controller.IO; namespace Emby.Server.Implementations.HttpClientManager { @@ -136,9 +133,8 @@ namespace Emby.Server.Implementations.HttpClientManager } var request = CreateWebRequest(url); - var httpWebRequest = request as HttpWebRequest; - if (httpWebRequest != null) + if (request is HttpWebRequest httpWebRequest) { AddRequestHeaders(httpWebRequest, options); @@ -159,25 +155,12 @@ namespace Emby.Server.Implementations.HttpClientManager { httpWebRequest.AutomaticDecompression = DecompressionMethods.None; } - } - - - request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); - - if (httpWebRequest != null) - { if (options.EnableKeepAlive) { httpWebRequest.KeepAlive = true; } - } - request.Method = method; - request.Timeout = options.TimeoutMs; - - if (httpWebRequest != null) - { if (!string.IsNullOrEmpty(options.Host)) { httpWebRequest.Host = options.Host; @@ -189,6 +172,11 @@ namespace Emby.Server.Implementations.HttpClientManager } } + request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); + + request.Method = method; + request.Timeout = options.TimeoutMs; + if (!string.IsNullOrWhiteSpace(userInfo)) { var parts = userInfo.Split(':'); @@ -215,7 +203,7 @@ namespace Emby.Server.Implementations.HttpClientManager { var hasUserAgent = false; - foreach (var header in options.RequestHeaders.ToList()) + foreach (var header in options.RequestHeaders) { if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase)) { @@ -340,8 +328,8 @@ namespace Emby.Server.Implementations.HttpClientManager _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(responseCachePath)); using (var responseStream = response.Content) + using (var memoryStream = new MemoryStream()) { - var memoryStream = new MemoryStream(); await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Position = 0; @@ -379,10 +367,7 @@ namespace Emby.Server.Implementations.HttpClientManager { try { - // TODO: We can always put this in the options object if needed - var requestEncoding = Encoding.UTF8; - - var bytes = options.RequestContentBytes ?? requestEncoding.GetBytes(options.RequestContent ?? string.Empty); + var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty); var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded"; @@ -392,7 +377,6 @@ namespace Emby.Server.Implementations.HttpClientManager } httpWebRequest.ContentType = contentType; - httpWebRequest.ContentLength = bytes.Length; (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length); } @@ -409,10 +393,7 @@ namespace Emby.Server.Implementations.HttpClientManager if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds) { - if (options.ResourcePool != null) - { - options.ResourcePool.Release(); - } + options.ResourcePool?.Release(); throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true }; } @@ -455,9 +436,8 @@ namespace Emby.Server.Implementations.HttpClientManager options.CancellationToken.ThrowIfCancellationRequested(); using (var stream = httpResponse.GetResponseStream()) + using (var memoryStream = new MemoryStream()) { - var memoryStream = new MemoryStream(); - await stream.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Position = 0; @@ -476,10 +456,7 @@ namespace Emby.Server.Implementations.HttpClientManager } finally { - if (options.ResourcePool != null) - { - options.ResourcePool.Release(); - } + options.ResourcePool?.Release(); } } @@ -488,13 +465,9 @@ namespace Emby.Server.Implementations.HttpClientManager var responseInfo = new HttpResponseInfo(disposable) { Content = content, - StatusCode = httpResponse.StatusCode, - ContentType = httpResponse.ContentType, - ContentLength = contentLength, - ResponseUrl = httpResponse.ResponseUri.ToString() }; @@ -511,11 +484,8 @@ namespace Emby.Server.Implementations.HttpClientManager var responseInfo = new HttpResponseInfo { TempFilePath = tempFile, - StatusCode = httpResponse.StatusCode, - ContentType = httpResponse.ContentType, - ContentLength = contentLength }; @@ -619,24 +589,22 @@ namespace Emby.Server.Implementations.HttpClientManager var contentLength = GetContentLength(httpResponse); - if (!contentLength.HasValue) - { - // We're not able to track progress - using (var stream = httpResponse.GetResponseStream()) - { - using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) - { - await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); - } - } - } - else + if (contentLength.HasValue) { using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) { await httpResponse.GetResponseStream().CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); } } + else + { + // We're not able to track progress + using (var stream = httpResponse.GetResponseStream()) + using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) + { + await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false); + } + } options.Progress.Report(100); @@ -650,10 +618,7 @@ namespace Emby.Server.Implementations.HttpClientManager } finally { - if (options.ResourcePool != null) - { - options.ResourcePool.Release(); - } + options.ResourcePool?.Release(); } } @@ -810,35 +775,38 @@ namespace Emby.Server.Implementations.HttpClientManager var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299; - if (!isSuccessful) + if (isSuccessful) { - if (options.LogErrorResponseBody) - { - try - { - using (var stream = response.GetResponseStream()) - { - if (stream != null) - { - using (var reader = new StreamReader(stream)) - { - var msg = reader.ReadToEnd(); + return; + } - _logger.LogError(msg); - } + if (options.LogErrorResponseBody) + { + try + { + using (var stream = response.GetResponseStream()) + { + if (stream != null) + { + using (var reader = new StreamReader(stream)) + { + var msg = reader.ReadToEnd(); + + _logger.LogError(msg); } } } - catch - { - - } } - throw new HttpException(response.StatusDescription) + catch { - StatusCode = response.StatusCode - }; + + } } + + throw new HttpException(response.StatusDescription) + { + StatusCode = response.StatusCode + }; } private Task GetResponseAsync(WebRequest request, TimeSpan timeout) @@ -859,13 +827,10 @@ namespace Emby.Server.Implementations.HttpClientManager private static void TimeoutCallback(object state, bool timedOut) { - if (timedOut) + if (timedOut && state != null) { WebRequest request = (WebRequest)state; - if (state != null) - { - request.Abort(); - } + request.Abort(); } } @@ -880,13 +845,13 @@ namespace Emby.Server.Implementations.HttpClientManager public void OnError(Task task) { - if (task.Exception != null) + if (task.Exception == null) { - taskCompletion.TrySetException(task.Exception); + taskCompletion.TrySetException(Enumerable.Empty()); } else { - taskCompletion.TrySetException(new List()); + taskCompletion.TrySetException(task.Exception); } } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 60bc38616c..e8ffd0caaf 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -16,8 +16,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Extensions; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.LiveTv.Listings @@ -32,9 +30,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; - private readonly Dictionary> _channelPairingCache = - new Dictionary>(StringComparer.OrdinalIgnoreCase); - public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost) { _logger = logger; @@ -74,33 +69,29 @@ namespace Emby.Server.Implementations.LiveTv.Listings // Normalize incoming input channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I'); - List programsInfo = new List(); - var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); - return programsInfo; + + return Enumerable.Empty(); } var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); - string stationID = channelId; - - _logger.LogInformation("Channel Station ID is: " + stationID); - List requestList = - new List() + _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId); + var requestList = new List() + { + new ScheduleDirect.RequestScheduleForChannel() { - new ScheduleDirect.RequestScheduleForChannel() - { - stationID = stationID, - date = dates - } - }; + stationID = channelId, + date = dates + } + }; var requestString = _jsonSerializer.SerializeToString(requestList); - _logger.LogDebug("Request string for schedules is: " + requestString); + _logger.LogDebug("Request string for schedules is: {RequestString}", requestString); var httpOptions = new HttpRequestOptions() { @@ -109,16 +100,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken = cancellationToken, // The data can be large so give it some extra time TimeoutMs = 60000, - LogErrorResponseBody = true + LogErrorResponseBody = true, + RequestContent = requestString }; httpOptions.RequestHeaders["token"] = token; - httpOptions.RequestContent = requestString; using (var response = await Post(httpOptions, true, info).ConfigureAwait(false)) + using (StreamReader reader = new StreamReader(response.Content)) { var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync>(response.Content).ConfigureAwait(false); - _logger.LogDebug("Found {ScheduleCount} programs on {StationID} ScheduleDirect", dailySchedules.Count, stationID); + _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); httpOptions = new HttpRequestOptions() { @@ -132,14 +124,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestHeaders["token"] = token; - List programsID = new List(); - programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList(); - var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]"; - httpOptions.RequestContent = requestBody; - - double wideAspect = 1.77777778; + var programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct(); + httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]"; using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false)) + using (StreamReader innerReader = new StreamReader(innerResponse.Content)) { var programDetails = await _jsonSerializer.DeserializeFromStreamAsync>(innerResponse.Content).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); @@ -150,8 +139,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); - var schedules = dailySchedules.SelectMany(d => d.programs); - foreach (ScheduleDirect.Program schedule in schedules) + List programsInfo = new List(); + foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs)) { //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID + // " which corresponds to channel " + channelNumber + " and program id " + @@ -165,15 +154,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings { var programEntry = programDict[schedule.programID]; - var allImages = (images[imageIndex].data ?? new List()).ToList(); - var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList(); - var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)).ToList(); + var allImages = images[imageIndex].data ?? new List(); + var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)); + var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)); - double desiredAspect = 0.666666667; + const double desiredAspect = 0.666666667; programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ?? GetProgramImage(ApiUrl, allImages, true, desiredAspect); + const double wideAspect = 1.77777778; + programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect); // Don't supply the same image twice @@ -193,18 +184,16 @@ namespace Emby.Server.Implementations.LiveTv.Listings programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID])); } + return programsInfo; } } - - return programsInfo; } private int GetSizeOrder(ScheduleDirect.ImageData image) { if (!string.IsNullOrWhiteSpace(image.height)) { - int value; - if (int.TryParse(image.height, out value)) + if (int.TryParse(image.height, out int value)) { return value; } @@ -225,9 +214,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings { channelNumber = map.atscMajor + "." + map.atscMinor; } - channelNumber = channelNumber.TrimStart('0'); - return channelNumber; + return channelNumber.TrimStart('0'); } private bool IsMovie(ScheduleDirect.ProgramDetails programInfo) @@ -382,8 +370,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (details.movie != null) { - int year; - if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out year)) + if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out int year)) { info.ProductionYear = year; } @@ -414,18 +401,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings return date; } - private string GetProgramImage(string apiUrl, List images, bool returnDefaultImage, double desiredAspect) + private string GetProgramImage(string apiUrl, IEnumerable images, bool returnDefaultImage, double desiredAspect) { - string url = null; - - var matches = images; - - matches = matches - .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i))) + var match = images + .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) .ThenByDescending(GetSizeOrder) - .ToList(); - - var match = matches.FirstOrDefault(); + .FirstOrDefault(); if (match == null) { @@ -434,22 +415,21 @@ namespace Emby.Server.Implementations.LiveTv.Listings var uri = match.uri; - if (!string.IsNullOrWhiteSpace(uri)) + if (string.IsNullOrWhiteSpace(uri)) { - if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1) - { - url = uri; - } - else - { - url = apiUrl + "/image/" + uri; - } + return null; + } + else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1) + { + return uri; + } + else + { + return apiUrl + "/image/" + uri; } - //_logger.LogDebug("URL for image is : " + url); - return url; } - private double GetApsectRatio(ScheduleDirect.ImageData i) + private double GetAspectRatio(ScheduleDirect.ImageData i) { int width = 0; int height = 0; @@ -614,8 +594,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value)) { - long ticks; - if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks)) + if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks)) { // If it's under 24 hours old we can still use it if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks) @@ -685,8 +664,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); - options.RequestHeaders["token"] = newToken; + options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);; return await Post(options, false, providerInfo).ConfigureAwait(false); } @@ -724,8 +702,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); - options.RequestHeaders["token"] = newToken; + options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false); return await Get(options, false, providerInfo).ConfigureAwait(false); } @@ -743,9 +720,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " + // httpOptions.RequestContent); - using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false)) + using (var response = await Post(httpOptions, false, null).ConfigureAwait(false)) { - var root = await _jsonSerializer.DeserializeFromStreamAsync(responce.Content).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync(response.Content).ConfigureAwait(false); if (root.message == "OK") { _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); @@ -828,13 +805,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using (var httpResponse = await Get(options, false, null).ConfigureAwait(false)) + using (var response = httpResponse.Content) { - using (var response = httpResponse.Content) - { - var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); + var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); - return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); - } + return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); } } catch (HttpException ex) @@ -913,54 +888,41 @@ namespace Emby.Server.Implementations.LiveTv.Listings var list = new List(); using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false)) + using (var response = httpResponse.Content) { - using (var response = httpResponse.Content) + var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); + _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); + _logger.LogInformation("Mapping Stations to Channel"); + + var allStations = root.stations ?? Enumerable.Empty(); + + foreach (ScheduleDirect.Map map in root.map) { - var root = await _jsonSerializer.DeserializeFromStreamAsync(response).ConfigureAwait(false); - _logger.LogInformation("Found " + root.map.Count + " channels on the lineup on ScheduleDirect"); - _logger.LogInformation("Mapping Stations to Channel"); + var channelNumber = GetChannelNumber(map); - var allStations = root.stations ?? new List(); - - foreach (ScheduleDirect.Map map in root.map) + var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); + if (station == null) { - var channelNumber = GetChannelNumber(map); - - var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); - if (station == null) + station = new ScheduleDirect.Station { - station = new ScheduleDirect.Station - { - stationID = map.stationID - }; - } - - var name = channelNumber; - - var channelInfo = new ChannelInfo - { - Number = channelNumber, - Name = name + stationID = map.stationID }; - - if (station != null) - { - if (!string.IsNullOrWhiteSpace(station.name)) - { - channelInfo.Name = station.name; - } - - channelInfo.Id = station.stationID; - channelInfo.CallSign = station.callsign; - - if (station.logo != null) - { - channelInfo.ImageUrl = station.logo.URL; - } - } - - list.Add(channelInfo); } + + var channelInfo = new ChannelInfo + { + Id = station.stationID, + CallSign = station.callsign, + Number = channelNumber, + Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name + }; + + if (station.logo != null) + { + channelInfo.ImageUrl = station.logo.URL; + } + + list.Add(channelInfo); } } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index ee2a9fe4b3..a4ffbd2fe8 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -132,9 +132,7 @@ namespace Emby.Server.Implementations.LiveTv { service.DataSourceChanged += service_DataSourceChanged; - var embyTv = service as EmbyTV.EmbyTV; - - if (embyTv != null) + if (service is EmbyTV.EmbyTV embyTv) { embyTv.TimerCreated += EmbyTv_TimerCreated; embyTv.TimerCancelled += EmbyTv_TimerCancelled; @@ -251,18 +249,15 @@ namespace Emby.Server.Implementations.LiveTv mediaSourceId = null; } - MediaSourceInfo info; - bool isVideo; - ILiveTvService service; - ILiveStream liveStream; - var channel = (LiveTvChannel)_libraryManager.GetItemById(id); - isVideo = channel.ChannelType == ChannelType.TV; - service = GetService(channel); + + bool isVideo = channel.ChannelType == ChannelType.TV; + ILiveTvService service = GetService(channel); _logger.LogInformation("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId); - var supportsManagedStream = service as ISupportsDirectStreamProvider; - if (supportsManagedStream != null) + MediaSourceInfo info; + ILiveStream liveStream; + if (service is ISupportsDirectStreamProvider supportsManagedStream) { liveStream = await supportsManagedStream.GetChannelStreamWithDirectStreamProvider(channel.ExternalId, mediaSourceId, currentLiveStreams, cancellationToken).ConfigureAwait(false); info = liveStream.MediaSource; @@ -303,14 +298,12 @@ namespace Emby.Server.Implementations.LiveTv throw new NotImplementedException(); } - var list = sources.ToList(); - - foreach (var source in list) + foreach (var source in sources) { Normalize(source, service, baseItem.ChannelType == ChannelType.TV); } - return list; + return sources; } private ILiveTvService GetService(LiveTvChannel item) @@ -542,13 +535,11 @@ namespace Emby.Server.Implementations.LiveTv { var id = _tvDtoService.GetInternalProgramId(info.Id); - LiveTvProgram item = null; - allExistingPrograms.TryGetValue(id, out item); - var isNew = false; var forceUpdate = false; - if (item == null) + LiveTvProgram item; + if (!allExistingPrograms.TryGetValue(id, out item)) { isNew = true; item = new LiveTvProgram @@ -783,11 +774,9 @@ namespace Emby.Server.Implementations.LiveTv var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user); - var list = new List>(); - - var externalSeriesId = program.ExternalSeriesId; - - list.Add(new Tuple(dto, program.ExternalId, externalSeriesId)); + var list = new List>() { + new Tuple(dto, program.ExternalId, program.ExternalSeriesId) + }; await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false); @@ -928,13 +917,11 @@ namespace Emby.Server.Implementations.LiveTv programs = programs.Take(query.Limit.Value); } - var result = new QueryResult - { - Items = programs.ToArray(), - TotalRecordCount = totalCount - }; - - return result; + return new QueryResult + { + Items = programs.ToArray(), + TotalRecordCount = totalCount + }; } public QueryResult GetRecommendedPrograms(InternalItemsQuery query, DtoOptions options, CancellationToken cancellationToken) @@ -948,17 +935,11 @@ namespace Emby.Server.Implementations.LiveTv var internalResult = GetRecommendedProgramsInternal(query, options, cancellationToken); - var user = query.User; - - var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user); - - var result = new QueryResult - { - Items = returnArray, - TotalRecordCount = internalResult.TotalRecordCount - }; - - return result; + return new QueryResult + { + Items = _dtoService.GetBaseItemDtos(internalResult.Items, options, query.User), + TotalRecordCount = internalResult.TotalRecordCount + }; } private int GetRecommendationScore(LiveTvProgram program, User user, bool factorChannelWatchCount) @@ -977,28 +958,26 @@ namespace Emby.Server.Implementations.LiveTv var channel = _libraryManager.GetItemById(program.ChannelId); - if (channel != null) + if (channel == null) { - var channelUserdata = _userDataManager.GetUserData(user, channel); + return score; + } - if (channelUserdata.Likes ?? false) - { - score += 2; - } - else if (!(channelUserdata.Likes ?? true)) - { - score -= 2; - } + var channelUserdata = _userDataManager.GetUserData(user, channel); - if (channelUserdata.IsFavorite) - { - score += 3; - } + if (channelUserdata.Likes.HasValue) + { + score += channelUserdata.Likes.Value ? 2 : -2; + } - if (factorChannelWatchCount) - { - score += channelUserdata.PlayCount; - } + if (channelUserdata.IsFavorite) + { + score += 3; + } + + if (factorChannelWatchCount) + { + score += channelUserdata.PlayCount; } return score; @@ -1153,7 +1132,6 @@ namespace Emby.Server.Implementations.LiveTv var numComplete = 0; var parentFolder = GetInternalLiveTvFolder(cancellationToken); - var parentFolderId = parentFolder.Id; foreach (var channelInfo in allChannelsList) { @@ -1239,30 +1217,11 @@ namespace Emby.Server.Implementations.LiveTv programs.Add(programItem.Id); - if (program.IsMovie) - { - isMovie = true; - } - - if (program.IsSeries) - { - iSSeries = true; - } - - if (program.IsSports) - { - isSports = true; - } - - if (program.IsNews) - { - isNews = true; - } - - if (program.IsKids) - { - isKids = true; - } + isMovie |= program.IsMovie; + iSSeries |= program.IsSeries; + isSports |= program.IsSports; + isNews |= program.IsNews; + isKids |= program.IsKids; } _logger.LogDebug("Channel {0} has {1} new programs and {2} updated programs", currentChannel.Name, newPrograms.Count, updatedPrograms.Count); @@ -1304,8 +1263,7 @@ namespace Emby.Server.Implementations.LiveTv } numComplete++; - double percent = numComplete; - percent /= allChannelsList.Count; + double percent = numComplete / allChannelsList.Count; progress.Report(85 * percent + 15); } @@ -1320,7 +1278,6 @@ namespace Emby.Server.Implementations.LiveTv { IncludeItemTypes = validTypes, DtoOptions = new DtoOptions(false) - }); var numComplete = 0; @@ -1351,8 +1308,7 @@ namespace Emby.Server.Implementations.LiveTv } numComplete++; - double percent = numComplete; - percent /= list.Count; + double percent = numComplete / list.Count; progress.Report(100 * percent); } @@ -1414,28 +1370,22 @@ namespace Emby.Server.Implementations.LiveTv excludeItemTypes.Add(typeof(Episode).Name); } } - if (query.IsSports.HasValue) + if (query.IsSports ?? false) { - if (query.IsSports.Value) - { - genres.Add("Sports"); - } + genres.Add("Sports"); } - if (query.IsKids.HasValue) + if (query.IsKids ?? false) { - if (query.IsKids.Value) - { - genres.Add("Kids"); - genres.Add("Children"); - genres.Add("Family"); - } + genres.Add("Kids"); + genres.Add("Children"); + genres.Add("Family"); } var limit = query.Limit; - if ((query.IsInProgress ?? false)) + if (query.IsInProgress ?? false) { - limit = (query.Limit ?? 10) * 2; + // limit = (query.Limit ?? 10) * 2; limit = null; //var allActivePaths = EmbyTV.EmbyTV.Current.GetAllActiveRecordings().Select(i => i.Path).ToArray(); @@ -1467,7 +1417,7 @@ namespace Emby.Server.Implementations.LiveTv DtoOptions = dtoOptions }); - if ((query.IsInProgress ?? false)) + if (query.IsInProgress ?? false) { result.Items = result .Items @@ -1494,60 +1444,33 @@ namespace Emby.Server.Implementations.LiveTv dto.StartDate = program.StartDate; dto.EpisodeTitle = program.EpisodeTitle; - - if (program.IsRepeat) - { - dto.IsRepeat = program.IsRepeat; - } - if (program.IsMovie) - { - dto.IsMovie = program.IsMovie; - } - if (program.IsSeries) - { - dto.IsSeries = program.IsSeries; - } - if (program.IsSports) - { - dto.IsSports = program.IsSports; - } - if (program.IsLive) - { - dto.IsLive = program.IsLive; - } - if (program.IsNews) - { - dto.IsNews = program.IsNews; - } - if (program.IsKids) - { - dto.IsKids = program.IsKids; - } - if (program.IsPremiere) - { - dto.IsPremiere = program.IsPremiere; - } + dto.IsRepeat |= program.IsRepeat; + dto.IsMovie |= program.IsMovie; + dto.IsSeries |= program.IsSeries; + dto.IsSports |= program.IsSports; + dto.IsLive |= program.IsLive; + dto.IsNews |= program.IsNews; + dto.IsKids |= program.IsKids; + dto.IsPremiere |= program.IsPremiere; if (hasChannelInfo || hasChannelImage) { - var channel = _libraryManager.GetItemById(program.ChannelId) as LiveTvChannel; + var channel = _libraryManager.GetItemById(program.ChannelId); - if (channel != null) + if (channel is LiveTvChannel liveChannel) { - dto.ChannelName = channel.Name; - dto.MediaType = channel.MediaType; - dto.ChannelNumber = channel.Number; + dto.ChannelName = liveChannel.Name; + dto.MediaType = liveChannel.MediaType; + dto.ChannelNumber = liveChannel.Number; - if (hasChannelImage && channel.HasImage(ImageType.Primary)) + if (hasChannelImage && liveChannel.HasImage(ImageType.Primary)) { - dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel); + dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(liveChannel); } } } - var externalSeriesId = program.ExternalSeriesId; - - programTuples.Add(new Tuple(dto, program.ExternalId, externalSeriesId)); + programTuples.Add(new Tuple(dto, program.ExternalId, program.ExternalSeriesId)); } return AddRecordingInfo(programTuples, CancellationToken.None); @@ -2037,19 +1960,13 @@ namespace Emby.Server.Implementations.LiveTv private async Task> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null) { - var service = program != null ? - GetService(program) : - null; - - if (service == null) - { - service = _services.First(); - } - + ILiveTvService service = null; ProgramInfo programInfo = null; - if (program != null) + if(program != null) { + service = GetService(program); + var channel = _libraryManager.GetItemById(program.ChannelId); programInfo = new ProgramInfo @@ -2077,6 +1994,11 @@ namespace Emby.Server.Implementations.LiveTv Name = program.Name, OfficialRating = program.OfficialRating }; + } + + if (service == null) + { + service = _services.First(); } var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false); @@ -2147,8 +2069,7 @@ namespace Emby.Server.Implementations.LiveTv info.Priority = defaultValues.Priority; string newTimerId = null; - var supportsNewTimerIds = service as ISupportsNewTimerIds; - if (supportsNewTimerIds != null) + if (service is ISupportsNewTimerIds supportsNewTimerIds) { newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false); newTimerId = _tvDtoService.GetInternalTimerId(newTimerId); @@ -2192,8 +2113,7 @@ namespace Emby.Server.Implementations.LiveTv info.Priority = defaultValues.Priority; string newTimerId = null; - var supportsNewTimerIds = service as ISupportsNewTimerIds; - if (supportsNewTimerIds != null) + if (service is ISupportsNewTimerIds supportsNewTimerIds) { newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false); newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N"); @@ -2354,8 +2274,7 @@ namespace Emby.Server.Implementations.LiveTv throw new ResourceNotFoundException(); } - var configurable = provider as IConfigurableTunerHost; - if (configurable != null) + if (provider is IConfigurableTunerHost configurable) { await configurable.Validate(info).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index b4d18b69cf..27741863b5 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -549,13 +549,13 @@ namespace Emby.Server.Implementations.Updates // Do plugin-specific processing if (isPlugin) { - if (plugin != null) + if (plugin == null) { - OnPluginUpdated(plugin, package); + OnPluginInstalled(package); } else { - OnPluginInstalled(package); + OnPluginUpdated(plugin, package); } } } diff --git a/MediaBrowser.Common/Net/IHttpClient.cs b/MediaBrowser.Common/Net/IHttpClient.cs index cf55119653..f88cfbb2b5 100644 --- a/MediaBrowser.Common/Net/IHttpClient.cs +++ b/MediaBrowser.Common/Net/IHttpClient.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; +using System.IO; using System.Threading.Tasks; namespace MediaBrowser.Common.Net @@ -56,4 +53,4 @@ namespace MediaBrowser.Common.Net /// Task{HttpResponseInfo}. Task GetTempFileResponse(HttpRequestOptions options); } -} \ No newline at end of file +} From 0bbc4f8219f3df020e505fc861f42f4f52e20766 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 30 Dec 2018 13:01:52 +0100 Subject: [PATCH 072/125] Figure out why it's failing --- .../HttpClientManager/HttpClientManager.cs | 28 ++++++++----------- .../Movies/MovieDbProvider.cs | 4 +-- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index a2f508b80d..60482780f8 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net; +using System.Net.Cache; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -122,17 +123,17 @@ namespace Emby.Server.Implementations.HttpClientManager private WebRequest GetRequest(HttpRequestOptions options, string method) { - var url = options.Url; + string url = options.Url; - var uriAddress = new Uri(url); - var userInfo = uriAddress.UserInfo; + Uri uriAddress = new Uri(url); + string userInfo = uriAddress.UserInfo; if (!string.IsNullOrWhiteSpace(userInfo)) { _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url); url = url.Replace(userInfo + "@", string.Empty); } - var request = CreateWebRequest(url); + WebRequest request = CreateWebRequest(url); if (request is HttpWebRequest httpWebRequest) { @@ -140,15 +141,11 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.EnableHttpCompression) { - if (options.DecompressionMethod.HasValue) + httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate; + if (options.DecompressionMethod.HasValue + && options.DecompressionMethod.Value == CompressionMethod.Gzip) { - httpWebRequest.AutomaticDecompression = options.DecompressionMethod.Value == CompressionMethod.Gzip - ? DecompressionMethods.GZip - : DecompressionMethods.Deflate; - } - else - { - httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate; + httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip; } } else @@ -156,10 +153,7 @@ namespace Emby.Server.Implementations.HttpClientManager httpWebRequest.AutomaticDecompression = DecompressionMethods.None; } - if (options.EnableKeepAlive) - { - httpWebRequest.KeepAlive = true; - } + httpWebRequest.KeepAlive = options.EnableKeepAlive; if (!string.IsNullOrEmpty(options.Host)) { @@ -172,7 +166,7 @@ namespace Emby.Server.Implementations.HttpClientManager } } - request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); + request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); request.Method = method; request.Timeout = options.TimeoutMs; diff --git a/MediaBrowser.Providers/Movies/MovieDbProvider.cs b/MediaBrowser.Providers/Movies/MovieDbProvider.cs index d967d7b623..1ebf56e23c 100644 --- a/MediaBrowser.Providers/Movies/MovieDbProvider.cs +++ b/MediaBrowser.Providers/Movies/MovieDbProvider.cs @@ -146,7 +146,7 @@ namespace MediaBrowser.Providers.Movies return _tmdbSettings; } - using (var response = await GetMovieDbResponse(new HttpRequestOptions + using (HttpResponseInfo response = await GetMovieDbResponse(new HttpRequestOptions { Url = string.Format(TmdbConfigUrl, ApiKey), CancellationToken = cancellationToken, @@ -154,7 +154,7 @@ namespace MediaBrowser.Providers.Movies }).ConfigureAwait(false)) { - using (var json = response.Content) + using (Stream json = response.Content) { _tmdbSettings = await _jsonSerializer.DeserializeFromStreamAsync(json).ConfigureAwait(false); From 3d6dac26f4172ab1dae016e01ea7ca94dad665a6 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 18:28:01 +0100 Subject: [PATCH 073/125] Don't dispose the object we are returning --- .../HttpClientManager/HttpClientManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 60482780f8..d3ba1b683e 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -322,8 +322,8 @@ namespace Emby.Server.Implementations.HttpClientManager _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(responseCachePath)); using (var responseStream = response.Content) - using (var memoryStream = new MemoryStream()) { + var memoryStream = new MemoryStream(); await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Position = 0; @@ -430,8 +430,8 @@ namespace Emby.Server.Implementations.HttpClientManager options.CancellationToken.ThrowIfCancellationRequested(); using (var stream = httpResponse.GetResponseStream()) - using (var memoryStream = new MemoryStream()) { + var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Position = 0; From 0a3862ff8040bc7bd5803bb259842da302a282d1 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 3 Jan 2019 18:59:12 +0100 Subject: [PATCH 074/125] Moved Emby.Drawing.Skia off of deprecated functions. Cleaned up some other declarations along the way. --- Emby.Drawing.Skia/SkiaEncoder.cs | 15 ++++++++------- Emby.Drawing.Skia/StripCollageBuilder.cs | 23 ++++++++++++----------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs index 7a445a09ce..b96d46832d 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing.Skia/SkiaEncoder.cs @@ -548,9 +548,7 @@ namespace Emby.Drawing.Skia using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType)) { // scale image - var resizeMethod = SKBitmapResizeMethod.Lanczos3; - - bitmap.Resize(resizedBitmap, resizeMethod); + bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High); // If all we're doing is resizing then we can stop now if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) @@ -558,7 +556,9 @@ namespace Emby.Drawing.Skia _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); using (var outputStream = new SKFileWStream(outputPath)) { - resizedBitmap.Encode(outputStream, skiaOutputFormat, quality); + SKImageInfo imageInfo = new SKImageInfo(width,height); + var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); + pixmap.Encode(outputStream, skiaOutputFormat, quality); return outputPath; } } @@ -593,8 +593,7 @@ namespace Emby.Drawing.Skia // If foreground layer present then draw if (hasForegroundColor) { - Double opacity; - if (!Double.TryParse(options.ForegroundLayer, out opacity)) + if (!Double.TryParse(options.ForegroundLayer, out double opacity)) { opacity = .4; } @@ -610,7 +609,9 @@ namespace Emby.Drawing.Skia _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); using (var outputStream = new SKFileWStream(outputPath)) { - saveBitmap.Encode(outputStream, skiaOutputFormat, quality); + SKImageInfo imageInfo = new SKImageInfo(width, height); + var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()); + pixmap.Encode(outputStream, skiaOutputFormat, quality); } } } diff --git a/Emby.Drawing.Skia/StripCollageBuilder.cs b/Emby.Drawing.Skia/StripCollageBuilder.cs index 32f0b65857..2528fbc567 100644 --- a/Emby.Drawing.Skia/StripCollageBuilder.cs +++ b/Emby.Drawing.Skia/StripCollageBuilder.cs @@ -49,7 +49,9 @@ namespace Emby.Drawing.Skia { using (var outputStream = new SKFileWStream(outputPath)) { - bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + SKImageInfo imageInfo = new SKImageInfo(width, height); + var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()); + pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); } } } @@ -60,7 +62,9 @@ namespace Emby.Drawing.Skia { using (var outputStream = new SKFileWStream(outputPath)) { - bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + SKImageInfo imageInfo = new SKImageInfo(width, height); + var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()); + pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); } } } @@ -83,9 +87,8 @@ namespace Emby.Drawing.Skia for (int i = 0; i < 4; i++) { - int newIndex; - using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex)) + using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex)) { imageIndex = newIndex; @@ -98,7 +101,7 @@ namespace Emby.Drawing.Skia int iWidth = (int)Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height); using (var resizeBitmap = new SKBitmap(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType)) { - currentBitmap.Resize(resizeBitmap, SKBitmapResizeMethod.Lanczos3); + currentBitmap.ScalePixels(resizeBitmap, SKFilterQuality.High); // crop image int ix = (int)Math.Abs((iWidth - iSlice) / 2); using (var image = SKImage.FromBitmap(resizeBitmap)) @@ -116,7 +119,7 @@ namespace Emby.Drawing.Skia using (var reflectionBitmap = new SKBitmap(croppedBitmap.Width, croppedBitmap.Height / 2, croppedBitmap.ColorType, croppedBitmap.AlphaType)) { // resize to half height - croppedBitmap.Resize(reflectionBitmap, SKBitmapResizeMethod.Lanczos3); + currentBitmap.ScalePixels(reflectionBitmap, SKFilterQuality.High); using (var flippedBitmap = new SKBitmap(reflectionBitmap.Width, reflectionBitmap.Height, reflectionBitmap.ColorType, reflectionBitmap.AlphaType)) using (var flippedCanvas = new SKCanvas(flippedBitmap)) @@ -164,8 +167,7 @@ namespace Emby.Drawing.Skia currentIndex = 0; } - SKEncodedOrigin origin; - bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out origin); + bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out SKEncodedOrigin origin); imagesTested[currentIndex] = 0; @@ -194,9 +196,8 @@ namespace Emby.Drawing.Skia { for (var y = 0; y < 2; y++) { - int newIndex; - using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex)) + using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex)) { imageIndex = newIndex; @@ -208,7 +209,7 @@ namespace Emby.Drawing.Skia using (var resizedBitmap = new SKBitmap(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType)) { // scale image - currentBitmap.Resize(resizedBitmap, SKBitmapResizeMethod.Lanczos3); + currentBitmap.ScalePixels(resizedBitmap, SKFilterQuality.High); // draw this image into the strip at the next position var xPos = x * cellWidth; From 635dd36727f3c779cad8a3b56625bcfbea8ee286 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 3 Jan 2019 19:11:18 +0100 Subject: [PATCH 075/125] Put all pixmap constructors in `using` statements. Cleanup extra ImageInfo as well --- Emby.Drawing.Skia/SkiaEncoder.cs | 16 +++++++++------- Emby.Drawing.Skia/StripCollageBuilder.cs | 14 ++++++++------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/Emby.Drawing.Skia/SkiaEncoder.cs b/Emby.Drawing.Skia/SkiaEncoder.cs index b96d46832d..0467794dc9 100644 --- a/Emby.Drawing.Skia/SkiaEncoder.cs +++ b/Emby.Drawing.Skia/SkiaEncoder.cs @@ -556,10 +556,11 @@ namespace Emby.Drawing.Skia _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); using (var outputStream = new SKFileWStream(outputPath)) { - SKImageInfo imageInfo = new SKImageInfo(width,height); - var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); - pixmap.Encode(outputStream, skiaOutputFormat, quality); - return outputPath; + using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels())) + { + pixmap.Encode(outputStream, skiaOutputFormat, quality); + return outputPath; + } } } @@ -609,9 +610,10 @@ namespace Emby.Drawing.Skia _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); using (var outputStream = new SKFileWStream(outputPath)) { - SKImageInfo imageInfo = new SKImageInfo(width, height); - var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()); - pixmap.Encode(outputStream, skiaOutputFormat, quality); + using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels())) + { + pixmap.Encode(outputStream, skiaOutputFormat, quality); + } } } } diff --git a/Emby.Drawing.Skia/StripCollageBuilder.cs b/Emby.Drawing.Skia/StripCollageBuilder.cs index 2528fbc567..a98450e08b 100644 --- a/Emby.Drawing.Skia/StripCollageBuilder.cs +++ b/Emby.Drawing.Skia/StripCollageBuilder.cs @@ -49,9 +49,10 @@ namespace Emby.Drawing.Skia { using (var outputStream = new SKFileWStream(outputPath)) { - SKImageInfo imageInfo = new SKImageInfo(width, height); - var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()); - pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels())) + { + pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + } } } } @@ -62,9 +63,10 @@ namespace Emby.Drawing.Skia { using (var outputStream = new SKFileWStream(outputPath)) { - SKImageInfo imageInfo = new SKImageInfo(width, height); - var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()); - pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels())) + { + pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); + } } } } From db62648510dbe1aa6adda3c88a7560615daa5188 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 19:51:18 +0100 Subject: [PATCH 076/125] Remove firebase and empty resource config file --- .../ApplicationHost.cs | 47 ------- .../Session/FirebaseSessionController.cs | 131 ------------------ .../Session/SessionManager.cs | 13 -- MediaBrowser.Common/IApplicationHost.cs | 2 - .../Session/ClientCapabilities.cs | 5 +- .../Music/MusicBrainzAlbumProvider.cs | 84 +---------- MediaBrowser.Providers/Omdb/OmdbProvider.cs | 16 +-- 7 files changed, 12 insertions(+), 286 deletions(-) delete mode 100644 Emby.Server.Implementations/Session/FirebaseSessionController.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 3cc6151f13..05398984bb 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -2437,53 +2437,6 @@ namespace Emby.Server.Implementations } } } - - private Dictionary _values; - public string GetValue(string name) - { - if (_values == null) - { - _values = LoadValues(); - } - - string value; - - if (_values.TryGetValue(name, out value)) - { - return value; - } - - return null; - } - - // TODO: @bond Remove? - private Dictionary LoadValues() - { - Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - - using (var stream = typeof(ApplicationHost).Assembly.GetManifestResourceStream(typeof(ApplicationHost).Namespace + ".values.txt")) - { - using (var reader = new StreamReader(stream)) - { - while (!reader.EndOfStream) - { - var line = reader.ReadLine(); - if (string.IsNullOrEmpty(line)) - { - continue; - } - - var index = line.IndexOf('='); - if (index != -1) - { - values[line.Substring(0, index)] = line.Substring(index + 1); - } - } - } - } - - return values; - } } internal class CertificateInfo diff --git a/Emby.Server.Implementations/Session/FirebaseSessionController.cs b/Emby.Server.Implementations/Session/FirebaseSessionController.cs deleted file mode 100644 index cfe513305e..0000000000 --- a/Emby.Server.Implementations/Session/FirebaseSessionController.cs +++ /dev/null @@ -1,131 +0,0 @@ -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Net; -using MediaBrowser.Common.Net; -using MediaBrowser.Model.Serialization; -using System; -using System.Threading; -using System.Threading.Tasks; -using System.Text; -using MediaBrowser.Common; - -namespace Emby.Server.Implementations.Session -{ - public class FirebaseSessionController : ISessionController - { - private readonly IHttpClient _httpClient; - private readonly IJsonSerializer _json; - private readonly ISessionManager _sessionManager; - - public SessionInfo Session { get; private set; } - - private readonly string _token; - - private IApplicationHost _appHost; - private string _senderId; - private string _applicationId; - - public FirebaseSessionController(IHttpClient httpClient, - IApplicationHost appHost, - IJsonSerializer json, - SessionInfo session, - string token, ISessionManager sessionManager) - { - _httpClient = httpClient; - _json = json; - _appHost = appHost; - Session = session; - _token = token; - _sessionManager = sessionManager; - - _applicationId = _appHost.GetValue("firebase_applicationid"); - _senderId = _appHost.GetValue("firebase_senderid"); - } - - public static bool IsSupported(IApplicationHost appHost) - { - return !string.IsNullOrEmpty(appHost.GetValue("firebase_applicationid")) && !string.IsNullOrEmpty(appHost.GetValue("firebase_senderid")); - } - - public bool IsSessionActive - { - get - { - return (DateTime.UtcNow - Session.LastActivityDate).TotalDays <= 3; - } - } - - public bool SupportsMediaControl - { - get { return true; } - } - - public async Task SendMessage(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken) - { - if (!IsSessionActive) - { - return; - } - - if (string.IsNullOrEmpty(_senderId) || string.IsNullOrEmpty(_applicationId)) - { - return; - } - - foreach (var controller in allControllers) - { - // Don't send if there's an active web socket connection - if ((controller is WebSocketController) && controller.IsSessionActive) - { - return; - } - } - - var msg = new WebSocketMessage - { - Data = data, - MessageType = name, - MessageId = messageId, - ServerId = _appHost.SystemId - }; - - var req = new FirebaseBody - { - to = _token, - data = msg - }; - - var byteArray = Encoding.UTF8.GetBytes(_json.SerializeToString(req)); - - var enableLogging = false; - -#if DEBUG - enableLogging = true; -#endif - - var options = new HttpRequestOptions - { - Url = "https://fcm.googleapis.com/fcm/send", - RequestContentType = "application/json", - RequestContentBytes = byteArray, - CancellationToken = cancellationToken, - LogRequest = enableLogging, - LogResponse = enableLogging, - LogErrors = enableLogging - }; - - options.RequestHeaders["Authorization"] = string.Format("key={0}", _applicationId); - options.RequestHeaders["Sender"] = string.Format("id={0}", _senderId); - - using (var response = await _httpClient.Post(options).ConfigureAwait(false)) - { - - } - } - } - - internal class FirebaseBody - { - public string to { get; set; } - public WebSocketMessage data { get; set; } - } -} diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 2b2b3c6779..9911cd0c67 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1577,14 +1577,6 @@ namespace Emby.Server.Implementations.Session { session.Capabilities = capabilities; - if (!string.IsNullOrEmpty(capabilities.PushToken)) - { - if (string.Equals(capabilities.PushTokenType, "firebase", StringComparison.OrdinalIgnoreCase) && FirebaseSessionController.IsSupported(_appHost)) - { - EnsureFirebaseController(session, capabilities.PushToken); - } - } - if (saveCapabilities) { EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs @@ -1604,11 +1596,6 @@ namespace Emby.Server.Implementations.Session } } - private void EnsureFirebaseController(SessionInfo session, string token) - { - session.EnsureController(s => new FirebaseSessionController(_httpClient, _appHost, _jsonSerializer, s, token, this)); - } - private ClientCapabilities GetSavedCapabilities(string deviceId) { return _deviceManager.GetCapabilities(deviceId); diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 39d69ea15c..c4f760b151 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -135,7 +135,5 @@ namespace MediaBrowser.Common object CreateInstance(Type type); PackageVersionClass SystemUpdateLevel { get; } - - string GetValue(string name); } } diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs index 0a780b9103..6860b29f9c 100644 --- a/MediaBrowser.Model/Session/ClientCapabilities.cs +++ b/MediaBrowser.Model/Session/ClientCapabilities.cs @@ -1,5 +1,4 @@ using MediaBrowser.Model.Dlna; -using System; namespace MediaBrowser.Model.Session { @@ -12,8 +11,6 @@ namespace MediaBrowser.Model.Session public bool SupportsMediaControl { get; set; } public bool SupportsContentUploading { get; set; } public string MessageCallbackUrl { get; set; } - public string PushToken { get; set; } - public string PushTokenType { get; set; } public bool SupportsPersistentIdentifier { get; set; } public bool SupportsSync { get; set; } @@ -30,4 +27,4 @@ namespace MediaBrowser.Model.Session SupportsPersistentIdentifier = true; } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs index 0dbc433136..2c94d6a070 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzAlbumProvider.cs @@ -720,82 +720,6 @@ namespace MediaBrowser.Providers.Music return null; } - private long _lastMbzUrlQueryTicks = 0; - private List _mbzUrls = null; - private MbzUrl _chosenUrl; - - private async Task GetMbzUrl(bool forceMusicBrainzProper = false) - { - if (_chosenUrl == null || _mbzUrls == null || (DateTime.UtcNow.Ticks - _lastMbzUrlQueryTicks) > TimeSpan.FromHours(12).Ticks) - { - var urls = await RefreshMzbUrls(forceMusicBrainzProper).ConfigureAwait(false); - - if (urls.Count > 1) - { - _chosenUrl = urls[new Random().Next(0, urls.Count)]; - } - else - { - _chosenUrl = urls[0]; - } - } - - return _chosenUrl; - } - - private async Task> RefreshMzbUrls(bool forceMusicBrainzProper = false) - { - List list = null; - - if (!forceMusicBrainzProper) - { - var musicbrainzadminurl = _appHost.GetValue("musicbrainzadminurl"); - - if (!string.IsNullOrEmpty(musicbrainzadminurl)) - { - try - { - var options = new HttpRequestOptions - { - Url = musicbrainzadminurl, - UserAgent = _appHost.Name + "/" + _appHost.ApplicationVersion - }; - - using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) - { - using (var stream = response.Content) - { - var results = await _json.DeserializeFromStreamAsync>(stream).ConfigureAwait(false); - - list = results; - } - } - _lastMbzUrlQueryTicks = DateTime.UtcNow.Ticks; - } - catch (Exception ex) - { - _logger.LogError(ex, "Error getting music brainz info"); - } - } - } - - if (list == null) - { - list = new List - { - new MbzUrl - { - url = MusicBrainzBaseUrl, - throttleMs = 1000 - } - }; - } - - _mbzUrls = list.ToList(); - - return list; - } - internal Task GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken) { return GetMusicBrainzResponse(url, isSearch, false, cancellationToken); @@ -806,7 +730,7 @@ namespace MediaBrowser.Providers.Music /// internal async Task GetMusicBrainzResponse(string url, bool isSearch, bool forceMusicBrainzProper, CancellationToken cancellationToken) { - var urlInfo = await GetMbzUrl(forceMusicBrainzProper).ConfigureAwait(false); + var urlInfo = new MbzUrl(MusicBrainzBaseUrl, 1000); var throttleMs = urlInfo.throttleMs; if (throttleMs > 0) @@ -841,6 +765,12 @@ namespace MediaBrowser.Providers.Music internal class MbzUrl { + internal MbzUrl(string url, int throttleMs) + { + this.url = url; + this.throttleMs = throttleMs; + } + public string url { get; set; } public int throttleMs { get; set; } } diff --git a/MediaBrowser.Providers/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Omdb/OmdbProvider.cs index 5c4eb62a8b..bb4624b5c0 100644 --- a/MediaBrowser.Providers/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbProvider.cs @@ -270,21 +270,13 @@ namespace MediaBrowser.Providers.Omdb public static string GetOmdbUrl(string query, IApplicationHost appHost, CancellationToken cancellationToken) { - var baseUrl = appHost.GetValue("omdb_baseurl"); + const string url = "https://www.omdbapi.com?apikey=fe53f97e"; - if (string.IsNullOrEmpty(baseUrl)) + if (string.IsNullOrWhiteSpace(query)) { - baseUrl = "https://www.omdbapi.com"; + return url; } - - var url = baseUrl + "?apikey=fe53f97e"; - - if (!string.IsNullOrWhiteSpace(query)) - { - url += "&" + query; - } - - return url; + return url + "&" + query; } private async Task EnsureItemInfo(string imdbId, CancellationToken cancellationToken) From 64a79341a734330ad19c9c70e969f31ba7a34de8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 20:21:42 +0100 Subject: [PATCH 077/125] Don't send info to Emby servers on install Not even to a fake one --- MediaBrowser.Api/StartupWizardService.cs | 29 ------------------------ 1 file changed, 29 deletions(-) diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs index 7fccbcc9b0..0ddc1e1dd3 100644 --- a/MediaBrowser.Api/StartupWizardService.cs +++ b/MediaBrowser.Api/StartupWizardService.cs @@ -68,35 +68,6 @@ namespace MediaBrowser.Api _config.Configuration.IsStartupWizardCompleted = true; _config.SetOptimalValues(); _config.SaveConfiguration(); - - Task.Run(UpdateStats); - } - - private async Task UpdateStats() - { - try - { - var url = string.Format("http://www.mb3admin.local/admin/service/package/installed?mac={0}&product=MBServer&operation=Install&version={1}", - _appHost.SystemId, - _appHost.ApplicationVersion.ToString()); - - using (var response = await _httpClient.SendAsync(new HttpRequestOptions - { - - Url = url, - CancellationToken = CancellationToken.None, - LogErrors = false, - LogRequest = false - - }, "GET").ConfigureAwait(false)) - { - - } - } - catch - { - - } } public object Get(GetStartupConfiguration request) From d2be83dc441f500cbfb6ebd8d73719651df2aa9d Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 20:38:36 +0100 Subject: [PATCH 078/125] Don't send usage to emby --- .../EntryPoints/UsageEntryPoint.cs | 131 ------------------ .../EntryPoints/UsageReporter.cs | 130 ----------------- 2 files changed, 261 deletions(-) delete mode 100644 Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs delete mode 100644 Emby.Server.Implementations/EntryPoints/UsageReporter.cs diff --git a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs deleted file mode 100644 index f7542a5e92..0000000000 --- a/Emby.Server.Implementations/EntryPoints/UsageEntryPoint.cs +++ /dev/null @@ -1,131 +0,0 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; -using MediaBrowser.Controller.Session; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Model.Extensions; - -namespace Emby.Server.Implementations.EntryPoints -{ - /// - /// Class UsageEntryPoint - /// - public class UsageEntryPoint : IServerEntryPoint - { - private readonly IServerApplicationHost _applicationHost; - private readonly IHttpClient _httpClient; - private readonly ILogger _logger; - private readonly ISessionManager _sessionManager; - private readonly IUserManager _userManager; - private readonly IServerConfigurationManager _config; - - private readonly ConcurrentDictionary _apps = new ConcurrentDictionary(); - - public UsageEntryPoint(ILogger logger, IServerApplicationHost applicationHost, IHttpClient httpClient, ISessionManager sessionManager, IUserManager userManager, IServerConfigurationManager config) - { - _logger = logger; - _applicationHost = applicationHost; - _httpClient = httpClient; - _sessionManager = sessionManager; - _userManager = userManager; - _config = config; - - _sessionManager.SessionStarted += _sessionManager_SessionStarted; - } - - void _sessionManager_SessionStarted(object sender, SessionEventArgs e) - { - var session = e.SessionInfo; - - if (!string.IsNullOrEmpty(session.Client) && - !string.IsNullOrEmpty(session.DeviceName) && - !string.IsNullOrEmpty(session.DeviceId) && - !string.IsNullOrEmpty(session.ApplicationVersion)) - { - var keys = new List - { - session.Client, - session.DeviceName, - session.DeviceId, - session.ApplicationVersion - }; - - var key = string.Join("_", keys.ToArray()).GetMD5(); - - ClientInfo info; - if (!_apps.TryGetValue(key, out info)) - { - info = new ClientInfo - { - AppName = session.Client, - AppVersion = session.ApplicationVersion, - DeviceName = session.DeviceName, - DeviceId = session.DeviceId - }; - - _apps[key] = info; - - if (_config.Configuration.EnableAnonymousUsageReporting) - { - Task.Run(() => ReportNewSession(info)); - } - } - } - } - - private async Task ReportNewSession(ClientInfo client) - { - try - { - await new UsageReporter(_applicationHost, _httpClient, _logger) - .ReportAppUsage(client, CancellationToken.None) - .ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error sending anonymous usage statistics."); - } - } - - public async void Run() - { - await Task.Delay(5000).ConfigureAwait(false); - OnTimerFired(); - } - - /// - /// Called when [timer fired]. - /// - private async void OnTimerFired() - { - if (!_config.Configuration.EnableAnonymousUsageReporting) - { - return; - } - - try - { - await new UsageReporter(_applicationHost, _httpClient, _logger) - .ReportServerUsage(CancellationToken.None) - .ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error sending anonymous usage statistics."); - } - } - - public void Dispose() - { - _sessionManager.SessionStarted -= _sessionManager_SessionStarted; - } - } -} diff --git a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs b/Emby.Server.Implementations/EntryPoints/UsageReporter.cs deleted file mode 100644 index e962bb59b2..0000000000 --- a/Emby.Server.Implementations/EntryPoints/UsageReporter.cs +++ /dev/null @@ -1,130 +0,0 @@ -using MediaBrowser.Common; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Connect; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller; -using Microsoft.Extensions.Logging; - -namespace Emby.Server.Implementations.EntryPoints -{ - public class UsageReporter - { - private readonly IServerApplicationHost _applicationHost; - private readonly IHttpClient _httpClient; - private readonly ILogger _logger; - private const string MbAdminUrl = "https://www.mb3admin.local/admin/"; - - public UsageReporter(IServerApplicationHost applicationHost, IHttpClient httpClient, ILogger logger) - { - _applicationHost = applicationHost; - _httpClient = httpClient; - _logger = logger; - } - - public async Task ReportServerUsage(CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - var data = new Dictionary - { - { "feature", _applicationHost.Name }, - { "mac", _applicationHost.SystemId }, - { "serverid", _applicationHost.SystemId }, - { "deviceid", _applicationHost.SystemId }, - { "ver", _applicationHost.ApplicationVersion.ToString() }, - { "platform", _applicationHost.OperatingSystemDisplayName } - }; - - data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray()); - - var logErrors = false; -#if DEBUG - logErrors = true; -#endif - var options = new HttpRequestOptions - { - Url = MbAdminUrl + "service/registration/ping", - CancellationToken = cancellationToken, - - // Seeing block length errors - EnableHttpCompression = false, - - LogRequest = false, - LogErrors = logErrors, - BufferContent = false - }; - - options.SetPostData(data); - - using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)) - { - - } - } - - public async Task ReportAppUsage(ClientInfo app, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(app.DeviceId)) - { - throw new ArgumentException("Client info must have a device Id"); - } - - _logger.LogInformation("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}", - app.AppName ?? "Unknown App", - app.AppVersion ?? "Unknown", - app.DeviceId, - app.DeviceName ?? "Unknown"); - - cancellationToken.ThrowIfCancellationRequested(); - - var data = new Dictionary - { - { "feature", app.AppName ?? "Unknown App" }, - { "serverid", _applicationHost.SystemId }, - { "deviceid", app.DeviceId }, - { "mac", app.DeviceId }, - { "ver", app.AppVersion ?? "Unknown" }, - { "platform", app.DeviceName }, - }; - - var logErrors = false; - -#if DEBUG - logErrors = true; -#endif - var options = new HttpRequestOptions - { - Url = MbAdminUrl + "service/registration/ping", - CancellationToken = cancellationToken, - - // Seeing block length errors - EnableHttpCompression = false, - - LogRequest = false, - LogErrors = logErrors, - BufferContent = false - }; - - options.SetPostData(data); - - using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)) - { - - } - } - } - - public class ClientInfo - { - public string AppName { get; set; } - public string AppVersion { get; set; } - public string DeviceName { get; set; } - public string DeviceId { get; set; } - } -} From 30a19d345a7efe35a1f11cf47a3e00bae186f909 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 21:05:17 +0100 Subject: [PATCH 079/125] Remove report usage configuration option --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 5effba26be..09b7835876 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -175,7 +175,6 @@ namespace MediaBrowser.Model.Configuration public int SchemaVersion { get; set; } - public bool EnableAnonymousUsageReporting { get; set; } public bool EnableFolderView { get; set; } public bool EnableGroupingIntoCollections { get; set; } public bool DisplaySpecialsWithinSeasons { get; set; } @@ -221,7 +220,6 @@ namespace MediaBrowser.Model.Configuration HttpsPortNumber = DefaultHttpsPort; EnableHttps = true; EnableDashboardResponseCaching = true; - EnableAnonymousUsageReporting = false; EnableCaseSensitiveItemIds = true; EnableAutomaticRestart = true; From 4875d49fa20ddbca8f60129b08532170fb60d8a9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 21:25:39 +0100 Subject: [PATCH 080/125] Remove remaining part old logging code --- .../ApplicationHost.cs | 38 +++++-------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ff6586ac1e..ef965ec8a4 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -421,8 +421,6 @@ namespace Emby.Server.Implementations ImageEncoder = imageEncoder; - //SetBaseExceptionMessage(); - fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); NetworkManager.NetworkChanged += NetworkManager_NetworkChanged; @@ -687,18 +685,6 @@ namespace Emby.Server.Implementations return parts; } - // TODO: @bond - /* - private void SetBaseExceptionMessage() - { - var builder = GetBaseExceptionMessage(ApplicationPaths); - - builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine)); - builder.Insert(0, "*** Error Report ***" + Environment.NewLine); - - LoggerFactory.ExceptionMessagePrefix = builder.ToString(); - }*/ - /// /// Runs the startup tasks. /// @@ -734,8 +720,6 @@ namespace Emby.Server.Implementations RunEntryPoints(entryPoints, false); Logger.LogInformation("All entry points have started"); - //LoggerFactory.RemoveConsoleOutput(); - return Task.CompletedTask; } @@ -749,7 +733,7 @@ namespace Emby.Server.Implementations } var name = entryPoint.GetType().FullName; - Logger.LogInformation("Starting entry point {0}", name); + Logger.LogInformation("Starting entry point {Name}", name); var now = DateTime.UtcNow; try { @@ -757,9 +741,9 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error in {name}", name); + Logger.LogError(ex, "Error while running entrypoint {Name}", name); } - Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); + Logger.LogInformation("Entry point completed: {Name}. Duration: {Duration} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos"); } } @@ -1384,12 +1368,11 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error getting plugin Id from {pluginName}.", plugin.GetType().FullName); + Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName); } } - var hasPluginConfiguration = plugin as IHasPluginConfiguration; - if (hasPluginConfiguration != null) + if (plugin is IHasPluginConfiguration hasPluginConfiguration) { hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); } @@ -1808,13 +1791,13 @@ namespace Emby.Server.Implementations { var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion); - Logger.LogInformation("File {0} has version {1}", path, result); + Logger.LogInformation("File {Path} has version {Version}", path, result); return result; } catch (Exception ex) { - Logger.LogError(ex, "Error getting version number from {path}", path); + Logger.LogError(ex, "Error getting version number from {Path}", path); return new Version(1, 0); } @@ -2417,15 +2400,14 @@ namespace Emby.Server.Implementations { var type = GetType(); - //LoggerFactory.AddConsoleOutput(); - Logger.LogInformation("Disposing " + type.Name); + Logger.LogInformation("Disposing {Type}", type.Name); var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList(); DisposableParts.Clear(); foreach (var part in parts) { - Logger.LogInformation("Disposing " + part.GetType().Name); + Logger.LogInformation("Disposing {Type}", part.GetType().Name); try { @@ -2433,7 +2415,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error disposing {0}", part.GetType().Name); + Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name); } } } From d15af6eb35c782b0f150fc67bf0f2b0566d86edc Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 3 Jan 2019 21:29:48 +0100 Subject: [PATCH 081/125] Removed all old and unused ImageEncoders. Remove solution platform cruft. --- .../Emby.Drawing.ImageMagick.csproj | 19 - Emby.Drawing.ImageMagick/ImageHelpers.cs | 43 -- .../ImageMagickEncoder.cs | 354 -------------- .../PercentPlayedDrawer.cs | 40 -- .../PlayedIndicatorDrawer.cs | 125 ----- .../Properties/AssemblyInfo.cs | 36 -- .../StripCollageBuilder.cs | 202 -------- .../UnplayedCountIndicator.cs | 73 --- Emby.Drawing.Net/DynamicImageHelpers.cs | 110 ----- Emby.Drawing.Net/Emby.Drawing.Net.csproj | 17 - Emby.Drawing.Net/GDIImageEncoder.cs | 282 ----------- Emby.Drawing.Net/ImageExtensions.cs | 217 --------- Emby.Drawing.Net/ImageHelpers.cs | 43 -- Emby.Drawing.Net/PercentPlayedDrawer.cs | 34 -- Emby.Drawing.Net/PlayedIndicatorDrawer.cs | 32 -- Emby.Drawing.Net/Properties/AssemblyInfo.cs | 36 -- Emby.Drawing.Net/UnplayedCountIndicator.cs | 50 -- Emby.Drawing.Net/empty.png | Bin 68 -> 0 bytes Jellyfin.Server/Jellyfin.Server.csproj | 1 - Jellyfin.Server/Program.cs | 27 +- MediaBrowser.sln | 454 +----------------- 21 files changed, 32 insertions(+), 2163 deletions(-) delete mode 100644 Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj delete mode 100644 Emby.Drawing.ImageMagick/ImageHelpers.cs delete mode 100644 Emby.Drawing.ImageMagick/ImageMagickEncoder.cs delete mode 100644 Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs delete mode 100644 Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs delete mode 100644 Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs delete mode 100644 Emby.Drawing.ImageMagick/StripCollageBuilder.cs delete mode 100644 Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs delete mode 100644 Emby.Drawing.Net/DynamicImageHelpers.cs delete mode 100644 Emby.Drawing.Net/Emby.Drawing.Net.csproj delete mode 100644 Emby.Drawing.Net/GDIImageEncoder.cs delete mode 100644 Emby.Drawing.Net/ImageExtensions.cs delete mode 100644 Emby.Drawing.Net/ImageHelpers.cs delete mode 100644 Emby.Drawing.Net/PercentPlayedDrawer.cs delete mode 100644 Emby.Drawing.Net/PlayedIndicatorDrawer.cs delete mode 100644 Emby.Drawing.Net/Properties/AssemblyInfo.cs delete mode 100644 Emby.Drawing.Net/UnplayedCountIndicator.cs delete mode 100644 Emby.Drawing.Net/empty.png diff --git a/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj b/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj deleted file mode 100644 index 2c5c923675..0000000000 --- a/Emby.Drawing.ImageMagick/Emby.Drawing.ImageMagick.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - netstandard2.0 - false - - - - - - - - - - - - - - diff --git a/Emby.Drawing.ImageMagick/ImageHelpers.cs b/Emby.Drawing.ImageMagick/ImageHelpers.cs deleted file mode 100644 index 8666933995..0000000000 --- a/Emby.Drawing.ImageMagick/ImageHelpers.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Emby.Drawing.ImageMagick -{ - internal static class ImageHelpers - { - internal static List ProjectPaths(string[] paths, int count) - { - if (count <= 0) - { - throw new ArgumentOutOfRangeException("count"); - } - if (paths.Length == 0) - { - throw new ArgumentOutOfRangeException("paths"); - } - - var list = new List(); - - AddToList(list, paths, count); - - return list.Take(count).ToList(); - } - - private static void AddToList(List list, string[] paths, int count) - { - while (list.Count < count) - { - foreach (var path in paths) - { - list.Add(path); - - if (list.Count >= count) - { - return; - } - } - } - } - } -} diff --git a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs deleted file mode 100644 index 5de8ac383e..0000000000 --- a/Emby.Drawing.ImageMagick/ImageMagickEncoder.cs +++ /dev/null @@ -1,354 +0,0 @@ -using System.Threading.Tasks; -using ImageMagickSharp; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Model.Drawing; -using Microsoft.Extensions.Logging; -using System; -using System.IO; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.System; - -namespace Emby.Drawing.ImageMagick -{ - public class ImageMagickEncoder : IImageEncoder, IDisposable - { - private readonly ILogger _logger; - private readonly IApplicationPaths _appPaths; - private readonly Func _httpClientFactory; - private readonly IFileSystem _fileSystem; - private readonly IEnvironmentInfo _environment; - - public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, Func httpClientFactory, IFileSystem fileSystem, IEnvironmentInfo environment) - { - _logger = logger; - _appPaths = appPaths; - _httpClientFactory = httpClientFactory; - _fileSystem = fileSystem; - _environment = environment; - - LogVersion(); - } - - public string[] SupportedInputFormats - { - get - { - // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif. - return new[] - { - "tiff", - "tif", - "jpeg", - "jpg", - "png", - "aiff", - "cr2", - "crw", - "dng", - - // Remove until supported - //"nef", - "orf", - "pef", - "arw", - "webp", - "gif", - "bmp", - "erf", - "raf", - "rw2", - "nrw" - }; - } - } - - public ImageFormat[] SupportedOutputFormats - { - get - { - if (_webpAvailable) - { - return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; - } - return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; - } - } - - private void LogVersion() - { - _logger.LogInformation("ImageMagick version: " + GetVersion()); - TestWebp(); - Wand.SetMagickThreadCount(1); - } - - public static string GetVersion() - { - return Wand.VersionString; - } - - private bool _webpAvailable = true; - private void TestWebp() - { - try - { - var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp"); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath)); - - using (var wand = new MagickWand(1, 1, new PixelWand("none", 1))) - { - wand.SaveImage(tmpPath); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error loading webp"); - _webpAvailable = false; - } - } - - public ImageSize GetImageSize(string path) - { - CheckDisposed(); - - using (var wand = new MagickWand()) - { - wand.PingImage(path); - var img = wand.CurrentImage; - - return new ImageSize - { - Width = img.Width, - Height = img.Height - }; - } - } - - private bool HasTransparency(string path) - { - var ext = Path.GetExtension(path); - - return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) || - string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase); - } - - public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat) - { - // Even if the caller specified 100, don't use it because it takes forever - quality = Math.Min(quality, 99); - - if (string.IsNullOrEmpty(options.BackgroundColor) || !HasTransparency(inputPath)) - { - using (var originalImage = new MagickWand(inputPath)) - { - if (options.CropWhiteSpace) - { - originalImage.CurrentImage.TrimImage(10); - } - - var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height); - - if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient) - { - // Just spit out the original file if all the options are default - return inputPath; - } - - var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize); - - var width = Convert.ToInt32(Math.Round(newImageSize.Width)); - var height = Convert.ToInt32(Math.Round(newImageSize.Height)); - - ScaleImage(originalImage, width, height, options.Blur ?? 0); - - if (autoOrient) - { - AutoOrientImage(originalImage); - } - - AddForegroundLayer(originalImage, options); - DrawIndicator(originalImage, width, height, options); - - originalImage.CurrentImage.CompressionQuality = quality; - originalImage.CurrentImage.StripImage(); - - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath)); - - originalImage.SaveImage(outputPath); - } - } - else - { - using (var originalImage = new MagickWand(inputPath)) - { - var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height); - - var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize); - - var width = Convert.ToInt32(Math.Round(newImageSize.Width)); - var height = Convert.ToInt32(Math.Round(newImageSize.Height)); - - using (var wand = new MagickWand(width, height, options.BackgroundColor)) - { - ScaleImage(originalImage, width, height, options.Blur ?? 0); - - if (autoOrient) - { - AutoOrientImage(originalImage); - } - - wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0); - - AddForegroundLayer(wand, options); - DrawIndicator(wand, width, height, options); - - wand.CurrentImage.CompressionQuality = quality; - wand.CurrentImage.StripImage(); - - wand.SaveImage(outputPath); - } - } - } - - return outputPath; - } - - private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options) - { - if (string.IsNullOrEmpty(options.ForegroundLayer)) - { - return; - } - - Double opacity; - if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4; - - using (var pixel = new PixelWand("#000", opacity)) - using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel)) - { - wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0); - } - } - - private void AutoOrientImage(MagickWand wand) - { - wand.CurrentImage.AutoOrientImage(); - } - - public static void RotateImage(MagickWand wand, float angle) - { - using (var pixelWand = new PixelWand("none", 1)) - { - wand.CurrentImage.RotateImage(pixelWand, angle); - } - } - - private void ScaleImage(MagickWand wand, int width, int height, int blur) - { - var useResize = blur > 1; - - if (useResize) - { - wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur); - } - else - { - wand.CurrentImage.ScaleImage(width, height); - } - } - - /// - /// Draws the indicator. - /// - /// The wand. - /// Width of the image. - /// Height of the image. - /// The options. - private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options) - { - if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0)) - { - return; - } - - try - { - if (options.AddPlayedIndicator) - { - var currentImageSize = new ImageSize(imageWidth, imageHeight); - - var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize); - Task.WaitAll(task); - } - else if (options.UnplayedCount.HasValue) - { - var currentImageSize = new ImageSize(imageWidth, imageHeight); - - new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value); - } - - if (options.PercentPlayed > 0) - { - new PercentPlayedDrawer().Process(wand, options.PercentPlayed); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error drawing indicator overlay"); - } - } - - public void CreateImageCollage(ImageCollageOptions options) - { - double ratio = options.Width; - ratio /= options.Height; - - if (ratio >= 1.4) - { - new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height); - } - else if (ratio >= .9) - { - new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height); - } - else - { - new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height); - } - } - - public string Name - { - get { return "ImageMagick"; } - } - - private bool _disposed; - public void Dispose() - { - _disposed = true; - Wand.CloseEnvironment(); - } - - private void CheckDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } - } - - public bool SupportsImageCollageCreation - { - get - { - return true; - } - } - - public bool SupportsImageEncoding - { - get { return true; } - } - } -} diff --git a/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs b/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs deleted file mode 100644 index 90f9d56095..0000000000 --- a/Emby.Drawing.ImageMagick/PercentPlayedDrawer.cs +++ /dev/null @@ -1,40 +0,0 @@ -using ImageMagickSharp; -using System; - -namespace Emby.Drawing.ImageMagick -{ - public class PercentPlayedDrawer - { - private const int IndicatorHeight = 8; - - public void Process(MagickWand wand, double percent) - { - var currentImage = wand.CurrentImage; - var height = currentImage.Height; - - using (var draw = new DrawingWand()) - { - using (PixelWand pixel = new PixelWand()) - { - var endX = currentImage.Width - 1; - var endY = height - 1; - - pixel.Color = "black"; - pixel.Opacity = 0.4; - draw.FillColor = pixel; - draw.DrawRectangle(0, endY - IndicatorHeight, endX, endY); - - double foregroundWidth = endX; - foregroundWidth *= percent; - foregroundWidth /= 100; - - pixel.Color = "#52B54B"; - pixel.Opacity = 0; - draw.FillColor = pixel; - draw.DrawRectangle(0, endY - IndicatorHeight, Convert.ToInt32(Math.Round(foregroundWidth)), endY); - wand.CurrentImage.DrawImage(draw); - } - } - } - } -} diff --git a/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs b/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs deleted file mode 100644 index 4dccca0c3d..0000000000 --- a/Emby.Drawing.ImageMagick/PlayedIndicatorDrawer.cs +++ /dev/null @@ -1,125 +0,0 @@ -using ImageMagickSharp; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; -using MediaBrowser.Model.Drawing; -using System; -using System.IO; -using System.Threading.Tasks; -using MediaBrowser.Common.Progress; -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.ImageMagick -{ - public class PlayedIndicatorDrawer - { - private const int FontSize = 52; - private const int OffsetFromTopRightCorner = 38; - - private readonly IApplicationPaths _appPaths; - private readonly IHttpClient _iHttpClient; - private readonly IFileSystem _fileSystem; - - public PlayedIndicatorDrawer(IApplicationPaths appPaths, IHttpClient iHttpClient, IFileSystem fileSystem) - { - _appPaths = appPaths; - _iHttpClient = iHttpClient; - _fileSystem = fileSystem; - } - - public async Task DrawPlayedIndicator(MagickWand wand, ImageSize imageSize) - { - var x = imageSize.Width - OffsetFromTopRightCorner; - - using (var draw = new DrawingWand()) - { - using (PixelWand pixel = new PixelWand()) - { - pixel.Color = "#52B54B"; - pixel.Opacity = 0.2; - draw.FillColor = pixel; - draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20); - - pixel.Opacity = 0; - pixel.Color = "white"; - draw.FillColor = pixel; - draw.Font = await DownloadFont("webdings.ttf", "https://github.com/MediaBrowser/Emby.Resources/raw/master/fonts/webdings.ttf", _appPaths, _iHttpClient, _fileSystem).ConfigureAwait(false); - draw.FontSize = FontSize; - draw.FontStyle = FontStyleType.NormalStyle; - draw.TextAlignment = TextAlignType.CenterAlign; - draw.FontWeight = FontWeightType.RegularStyle; - draw.TextAntialias = true; - draw.DrawAnnotation(x + 4, OffsetFromTopRightCorner + 14, "a"); - - draw.FillColor = pixel; - wand.CurrentImage.DrawImage(draw); - } - } - } - - internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem) - { - var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); - - if (fileSystem.FileExists(filePath)) - { - return filePath; - } - - var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name; - var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf"); - fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath)); - - using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath)) - { - using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read)) - { - stream.CopyTo(fileStream); - } - } - - fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath)); - - try - { - fileSystem.CopyFile(tempPath, filePath, false); - } - catch (IOException) - { - - } - - return tempPath; - } - - internal static async Task DownloadFont(string name, string url, IApplicationPaths paths, IHttpClient httpClient, IFileSystem fileSystem) - { - var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); - - if (fileSystem.FileExists(filePath)) - { - return filePath; - } - - var tempPath = await httpClient.GetTempFile(new HttpRequestOptions - { - Url = url, - Progress = new SimpleProgress() - - }).ConfigureAwait(false); - - fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath)); - - try - { - fileSystem.CopyFile(tempPath, filePath, false); - } - catch (IOException) - { - - } - - return tempPath; - } - } -} diff --git a/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs b/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs deleted file mode 100644 index 1089607d67..0000000000 --- a/Emby.Drawing.ImageMagick/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Emby.Drawing.ImageMagick")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Drawing.ImageMagick")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("6cfee013-6e7c-432b-ac37-cabf0880c69a")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Emby.Drawing.ImageMagick/StripCollageBuilder.cs b/Emby.Drawing.ImageMagick/StripCollageBuilder.cs deleted file mode 100644 index 26c6c868db..0000000000 --- a/Emby.Drawing.ImageMagick/StripCollageBuilder.cs +++ /dev/null @@ -1,202 +0,0 @@ -using ImageMagickSharp; -using MediaBrowser.Common.Configuration; -using System; -using System.Collections.Generic; - -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.ImageMagick -{ - public class StripCollageBuilder - { - private readonly IApplicationPaths _appPaths; - private readonly IFileSystem _fileSystem; - - public StripCollageBuilder(IApplicationPaths appPaths, IFileSystem fileSystem) - { - _appPaths = appPaths; - _fileSystem = fileSystem; - } - - public void BuildPosterCollage(string[] paths, string outputPath, int width, int height) - { - using (var wand = BuildPosterCollageWand(paths, width, height)) - { - wand.SaveImage(outputPath); - } - } - - public void BuildSquareCollage(string[] paths, string outputPath, int width, int height) - { - using (var wand = BuildSquareCollageWand(paths, width, height)) - { - wand.SaveImage(outputPath); - } - } - - public void BuildThumbCollage(string[] paths, string outputPath, int width, int height) - { - using (var wand = BuildThumbCollageWand(paths, width, height)) - { - wand.SaveImage(outputPath); - } - } - - private MagickWand BuildPosterCollageWand(string[] paths, int width, int height) - { - var inputPaths = ImageHelpers.ProjectPaths(paths, 3); - using (var wandImages = new MagickWand(inputPaths.ToArray())) - { - var wand = new MagickWand(width, height); - wand.OpenImage("gradient:#111111-#111111"); - using (var draw = new DrawingWand()) - { - var iSlice = Convert.ToInt32(width * 0.3); - int iTrans = Convert.ToInt32(height * .25); - int iHeight = Convert.ToInt32(height * .65); - var horizontalImagePadding = Convert.ToInt32(width * 0.0366); - - foreach (var element in wandImages.ImageList) - { - using (var blackPixelWand = new PixelWand(ColorName.Black)) - { - int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); - element.Gravity = GravityType.CenterGravity; - element.BackgroundColor = blackPixelWand; - element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); - int ix = (int)Math.Abs((iWidth - iSlice) / 2); - element.CropImage(iSlice, iHeight, ix, 0); - - element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); - } - } - - wandImages.SetFirstIterator(); - using (var wandList = wandImages.AppendImages()) - { - wandList.CurrentImage.TrimImage(1); - using (var mwr = wandList.CloneMagickWand()) - { - using (var blackPixelWand = new PixelWand(ColorName.Black)) - { - using (var greyPixelWand = new PixelWand(ColorName.Grey70)) - { - mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); - mwr.CurrentImage.FlipImage(); - - mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; - mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); - - using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) - { - mwg.OpenImage("gradient:black-none"); - var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); - mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing); - - wandList.AddImage(mwr); - int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; - wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .05)); - } - } - } - } - } - } - - return wand; - } - } - - private MagickWand BuildThumbCollageWand(string[] paths, int width, int height) - { - var inputPaths = ImageHelpers.ProjectPaths(paths, 4); - using (var wandImages = new MagickWand(inputPaths.ToArray())) - { - var wand = new MagickWand(width, height); - wand.OpenImage("gradient:#111111-#111111"); - using (var draw = new DrawingWand()) - { - var iSlice = Convert.ToInt32(width * 0.24125); - int iTrans = Convert.ToInt32(height * .25); - int iHeight = Convert.ToInt32(height * .70); - var horizontalImagePadding = Convert.ToInt32(width * 0.0125); - - foreach (var element in wandImages.ImageList) - { - using (var blackPixelWand = new PixelWand(ColorName.Black)) - { - int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); - element.Gravity = GravityType.CenterGravity; - element.BackgroundColor = blackPixelWand; - element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); - int ix = (int)Math.Abs((iWidth - iSlice) / 2); - element.CropImage(iSlice, iHeight, ix, 0); - - element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); - } - } - - wandImages.SetFirstIterator(); - using (var wandList = wandImages.AppendImages()) - { - wandList.CurrentImage.TrimImage(1); - using (var mwr = wandList.CloneMagickWand()) - { - using (var blackPixelWand = new PixelWand(ColorName.Black)) - { - using (var greyPixelWand = new PixelWand(ColorName.Grey70)) - { - mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); - mwr.CurrentImage.FlipImage(); - - mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; - mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); - - using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) - { - mwg.OpenImage("gradient:black-none"); - var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); - mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing); - - wandList.AddImage(mwr); - int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; - wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .045)); - } - } - } - } - } - } - - return wand; - } - } - - private MagickWand BuildSquareCollageWand(string[] paths, int width, int height) - { - var inputPaths = ImageHelpers.ProjectPaths(paths, 4); - var outputWand = new MagickWand(width, height, new PixelWand("none", 1)); - var imageIndex = 0; - var cellWidth = width/2; - var cellHeight = height/2; - for (var x = 0; x < 2; x++) - { - for (var y = 0; y < 2; y++) - { - using (var temp = new MagickWand(inputPaths[imageIndex])) - { - temp.CurrentImage.ScaleImage(cellWidth, cellHeight); - // draw this image into the strip at the next position - var xPos = x*cellWidth; - var yPos = y*cellHeight; - outputWand.CurrentImage.CompositeImage(temp, CompositeOperator.OverCompositeOp, xPos, yPos); - } - imageIndex++; - } - } - - return outputWand; - } - } -} diff --git a/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs b/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs deleted file mode 100644 index ee685c3c5f..0000000000 --- a/Emby.Drawing.ImageMagick/UnplayedCountIndicator.cs +++ /dev/null @@ -1,73 +0,0 @@ -using ImageMagickSharp; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Drawing; -using System.Globalization; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.ImageMagick -{ - public class UnplayedCountIndicator - { - private const int OffsetFromTopRightCorner = 38; - - private readonly IApplicationPaths _appPaths; - private readonly IFileSystem _fileSystem; - - public UnplayedCountIndicator(IApplicationPaths appPaths, IFileSystem fileSystem) - { - _appPaths = appPaths; - _fileSystem = fileSystem; - } - - public void DrawUnplayedCountIndicator(MagickWand wand, ImageSize imageSize, int count) - { - var x = imageSize.Width - OffsetFromTopRightCorner; - var text = count.ToString(CultureInfo.InvariantCulture); - - using (var draw = new DrawingWand()) - { - using (PixelWand pixel = new PixelWand()) - { - pixel.Color = "#52B54B"; - pixel.Opacity = 0.2; - draw.FillColor = pixel; - draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20); - - pixel.Opacity = 0; - pixel.Color = "white"; - draw.FillColor = pixel; - draw.Font = PlayedIndicatorDrawer.ExtractFont("robotoregular.ttf", _appPaths, _fileSystem); - draw.FontStyle = FontStyleType.NormalStyle; - draw.TextAlignment = TextAlignType.CenterAlign; - draw.FontWeight = FontWeightType.RegularStyle; - draw.TextAntialias = true; - - var fontSize = 30; - var y = OffsetFromTopRightCorner + 11; - - if (text.Length == 1) - { - x += 1; - } - else if (text.Length == 2) - { - x += 1; - } - else if (text.Length >= 3) - { - //x += 1; - y -= 2; - fontSize = 24; - } - - draw.FontSize = fontSize; - draw.DrawAnnotation(x, y, text); - - draw.FillColor = pixel; - wand.CurrentImage.DrawImage(draw); - } - - } - } - } -} diff --git a/Emby.Drawing.Net/DynamicImageHelpers.cs b/Emby.Drawing.Net/DynamicImageHelpers.cs deleted file mode 100644 index 1910f7840d..0000000000 --- a/Emby.Drawing.Net/DynamicImageHelpers.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System.Collections.Generic; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; - -namespace Emby.Drawing.Net -{ - public static class DynamicImageHelpers - { - public static void CreateThumbCollage(List files, - IFileSystem fileSystem, - string file, - int width, - int height) - { - const int numStrips = 4; - files = ImageHelpers.ProjectPaths(files, numStrips); - - const int rows = 1; - int cols = numStrips; - - int cellWidth = 2 * (width / 3); - int cellHeight = height; - var index = 0; - - using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb)) - { - using (var graphics = Graphics.FromImage(img)) - { - graphics.CompositingQuality = CompositingQuality.HighQuality; - graphics.SmoothingMode = SmoothingMode.HighQuality; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - - // SourceCopy causes the image to be blank in OSX - //graphics.CompositingMode = CompositingMode.SourceCopy; - - for (var row = 0; row < rows; row++) - { - for (var col = 0; col < cols; col++) - { - var x = col * (cellWidth / 2); - var y = row * cellHeight; - - if (files.Count > index) - { - using (var imgtemp = Image.FromFile(files[index])) - { - graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight); - } - } - - index++; - } - } - img.Save(file); - } - } - } - - public static void CreateSquareCollage(List files, - IFileSystem fileSystem, - string file, - int width, - int height) - { - files = ImageHelpers.ProjectPaths(files, 4); - - const int rows = 2; - const int cols = 2; - - int singleSize = width / 2; - var index = 0; - - using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb)) - { - using (var graphics = Graphics.FromImage(img)) - { - graphics.CompositingQuality = CompositingQuality.HighQuality; - graphics.SmoothingMode = SmoothingMode.HighQuality; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - - // SourceCopy causes the image to be blank in OSX - //graphics.CompositingMode = CompositingMode.SourceCopy; - - for (var row = 0; row < rows; row++) - { - for (var col = 0; col < cols; col++) - { - var x = col * singleSize; - var y = row * singleSize; - - using (var imgtemp = Image.FromFile(files[index])) - { - graphics.DrawImage(imgtemp, x, y, singleSize, singleSize); - } - index++; - } - } - img.Save(file); - } - } - } - } -} diff --git a/Emby.Drawing.Net/Emby.Drawing.Net.csproj b/Emby.Drawing.Net/Emby.Drawing.Net.csproj deleted file mode 100644 index dc9d35dcaf..0000000000 --- a/Emby.Drawing.Net/Emby.Drawing.Net.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - netstandard2.0 - - - - - - - diff --git a/Emby.Drawing.Net/GDIImageEncoder.cs b/Emby.Drawing.Net/GDIImageEncoder.cs deleted file mode 100644 index 1639125d37..0000000000 --- a/Emby.Drawing.Net/GDIImageEncoder.cs +++ /dev/null @@ -1,282 +0,0 @@ -using MediaBrowser.Controller.Drawing; -using MediaBrowser.Model.Drawing; -using Microsoft.Extensions.Logging; -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; -using System.Linq; -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.IO; -using MediaBrowser.Model.IO; -using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat; -using Emby.Drawing; - -namespace Emby.Drawing.Net -{ - public class GDIImageEncoder : IImageEncoder - { - private readonly IFileSystem _fileSystem; - private readonly ILogger _logger; - - public GDIImageEncoder(IFileSystem fileSystem, ILogger logger) - { - _fileSystem = fileSystem; - _logger = logger; - - LogInfo(); - } - - private void LogInfo() - { - _logger.LogInformation("GDIImageEncoder starting"); - using (var stream = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".empty.png")) - { - using (var img = Image.FromStream(stream)) - { - - } - } - _logger.LogInformation("GDIImageEncoder started"); - } - - public string[] SupportedInputFormats - { - get - { - return new[] - { - "png", - "jpeg", - "jpg", - "gif", - "bmp" - }; - } - } - - public ImageFormat[] SupportedOutputFormats - { - get - { - return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; - } - } - - public ImageSize GetImageSize(string path) - { - using (var image = Image.FromFile(path)) - { - return new ImageSize - { - Width = image.Width, - Height = image.Height - }; - } - } - - private Image GetImage(string path, bool cropWhitespace) - { - if (cropWhitespace) - { - using (var originalImage = (Bitmap)Image.FromFile(path)) - { - return originalImage.CropWhitespace(); - } - } - - return Image.FromFile(path); - } - - public void EncodeImage(string inputPath, ImageSize? originalImageSize, string outputPath, bool autoOrient, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat) - { - using (var originalImage = GetImage(inputPath, options.CropWhiteSpace)) - { - if (options.CropWhiteSpace || !originalImageSize.HasValue) - { - originalImageSize = new ImageSize(originalImage.Width, originalImage.Height); - } - - var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize); - - var newWidth = Convert.ToInt32(Math.Round(newImageSize.Width)); - var newHeight = Convert.ToInt32(Math.Round(newImageSize.Height)); - - // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here - // Also, Webp only supports Format32bppArgb and Format32bppRgb - var pixelFormat = selectedOutputFormat == ImageFormat.Webp - ? PixelFormat.Format32bppArgb - : PixelFormat.Format32bppPArgb; - - using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat)) - { - // Mono throw an exeception if assign 0 to SetResolution - if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0) - { - // Preserve the original resolution - thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution); - } - - using (var thumbnailGraph = Graphics.FromImage(thumbnail)) - { - thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; - thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; - thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; - thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; - - // SourceCopy causes the image to be blank in OSX - //thumbnailGraph.CompositingMode = !hasPostProcessing ? - // CompositingMode.SourceCopy : - // CompositingMode.SourceOver; - - SetBackgroundColor(thumbnailGraph, options); - - thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight); - - DrawIndicator(thumbnailGraph, newWidth, newHeight, options); - - var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat); - - // Save to the cache location - using (var cacheFileStream = _fileSystem.GetFileStream(outputPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, false)) - { - // Save to the memory stream - thumbnail.Save(outputFormat, cacheFileStream, quality); - } - } - } - - } - } - - /// - /// Sets the color of the background. - /// - /// The graphics. - /// The options. - private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options) - { - var color = options.BackgroundColor; - - if (!string.IsNullOrEmpty(color)) - { - Color drawingColor; - - try - { - drawingColor = ColorTranslator.FromHtml(color); - } - catch - { - drawingColor = ColorTranslator.FromHtml("#" + color); - } - - graphics.Clear(drawingColor); - } - } - - /// - /// Draws the indicator. - /// - /// The graphics. - /// Width of the image. - /// Height of the image. - /// The options. - private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options) - { - if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0)) - { - return; - } - - try - { - if (options.AddPlayedIndicator) - { - var currentImageSize = new Size(imageWidth, imageHeight); - - new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize); - } - else if (options.UnplayedCount.HasValue) - { - var currentImageSize = new Size(imageWidth, imageHeight); - - new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value); - } - - if (options.PercentPlayed > 0) - { - var currentImageSize = new Size(imageWidth, imageHeight); - - new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error drawing indicator overlay"); - } - } - - /// - /// Gets the output format. - /// - /// The image. - /// The output format. - /// ImageFormat. - private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat) - { - switch (outputFormat) - { - case ImageFormat.Bmp: - return System.Drawing.Imaging.ImageFormat.Bmp; - case ImageFormat.Gif: - return System.Drawing.Imaging.ImageFormat.Gif; - case ImageFormat.Jpg: - return System.Drawing.Imaging.ImageFormat.Jpeg; - case ImageFormat.Png: - return System.Drawing.Imaging.ImageFormat.Png; - default: - return image.RawFormat; - } - } - - public void CreateImageCollage(ImageCollageOptions options) - { - double ratio = options.Width; - ratio /= options.Height; - - if (ratio >= 1.4) - { - DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height); - } - else if (ratio >= .9) - { - DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height); - } - else - { - DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width); - } - } - - public void Dispose() - { - } - - public string Name - { - get { return "GDI"; } - } - - public bool SupportsImageCollageCreation - { - get { return true; } - } - - public bool SupportsImageEncoding - { - get { return true; } - } - } -} diff --git a/Emby.Drawing.Net/ImageExtensions.cs b/Emby.Drawing.Net/ImageExtensions.cs deleted file mode 100644 index dec2613d0f..0000000000 --- a/Emby.Drawing.Net/ImageExtensions.cs +++ /dev/null @@ -1,217 +0,0 @@ -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; - -namespace Emby.Drawing.Net -{ - public static class ImageExtensions - { - /// - /// Saves the image. - /// - /// The output format. - /// The image. - /// To stream. - /// The quality. - public static void Save(this Image image, ImageFormat outputFormat, Stream toStream, int quality) - { - // Use special save methods for jpeg and png that will result in a much higher quality image - // All other formats use the generic Image.Save - if (ImageFormat.Jpeg.Equals(outputFormat)) - { - SaveAsJpeg(image, toStream, quality); - } - else if (ImageFormat.Png.Equals(outputFormat)) - { - image.Save(toStream, ImageFormat.Png); - } - else - { - image.Save(toStream, outputFormat); - } - } - - /// - /// Saves the JPEG. - /// - /// The image. - /// The target. - /// The quality. - public static void SaveAsJpeg(this Image image, Stream target, int quality) - { - using (var encoderParameters = new EncoderParameters(1)) - { - encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality); - image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters); - } - } - - private static readonly ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders(); - - /// - /// Gets the image codec info. - /// - /// Type of the MIME. - /// ImageCodecInfo. - private static ImageCodecInfo GetImageCodecInfo(string mimeType) - { - foreach (var encoder in Encoders) - { - if (string.Equals(encoder.MimeType, mimeType, StringComparison.OrdinalIgnoreCase)) - { - return encoder; - } - } - - return Encoders.Length == 0 ? null : Encoders[0]; - } - - /// - /// Crops an image by removing whitespace and transparency from the edges - /// - /// The BMP. - /// Bitmap. - /// - public static Bitmap CropWhitespace(this Bitmap bmp) - { - var width = bmp.Width; - var height = bmp.Height; - - var topmost = 0; - for (int row = 0; row < height; ++row) - { - if (IsAllWhiteRow(bmp, row, width)) - topmost = row; - else break; - } - - int bottommost = 0; - for (int row = height - 1; row >= 0; --row) - { - if (IsAllWhiteRow(bmp, row, width)) - bottommost = row; - else break; - } - - int leftmost = 0, rightmost = 0; - for (int col = 0; col < width; ++col) - { - if (IsAllWhiteColumn(bmp, col, height)) - leftmost = col; - else - break; - } - - for (int col = width - 1; col >= 0; --col) - { - if (IsAllWhiteColumn(bmp, col, height)) - rightmost = col; - else - break; - } - - if (rightmost == 0) rightmost = width; // As reached left - if (bottommost == 0) bottommost = height; // As reached top. - - var croppedWidth = rightmost - leftmost; - var croppedHeight = bottommost - topmost; - - if (croppedWidth == 0) // No border on left or right - { - leftmost = 0; - croppedWidth = width; - } - - if (croppedHeight == 0) // No border on top or bottom - { - topmost = 0; - croppedHeight = height; - } - - // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here - var thumbnail = new Bitmap(croppedWidth, croppedHeight, PixelFormat.Format32bppPArgb); - - // Preserve the original resolution - TrySetResolution(thumbnail, bmp.HorizontalResolution, bmp.VerticalResolution); - - using (var thumbnailGraph = Graphics.FromImage(thumbnail)) - { - thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; - thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; - thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; - thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; - thumbnailGraph.CompositingMode = CompositingMode.SourceCopy; - - thumbnailGraph.DrawImage(bmp, - new RectangleF(0, 0, croppedWidth, croppedHeight), - new RectangleF(leftmost, topmost, croppedWidth, croppedHeight), - GraphicsUnit.Pixel); - } - return thumbnail; - } - - /// - /// Tries the set resolution. - /// - /// The BMP. - /// The x. - /// The y. - private static void TrySetResolution(Bitmap bmp, float x, float y) - { - if (x > 0 && y > 0) - { - bmp.SetResolution(x, y); - } - } - - /// - /// Determines whether or not a row of pixels is all whitespace - /// - /// The BMP. - /// The row. - /// The width. - /// true if [is all white row] [the specified BMP]; otherwise, false. - private static bool IsAllWhiteRow(Bitmap bmp, int row, int width) - { - for (var i = 0; i < width; ++i) - { - if (!IsWhiteSpace(bmp.GetPixel(i, row))) - { - return false; - } - } - return true; - } - - /// - /// Determines whether or not a column of pixels is all whitespace - /// - /// The BMP. - /// The col. - /// The height. - /// true if [is all white column] [the specified BMP]; otherwise, false. - private static bool IsAllWhiteColumn(Bitmap bmp, int col, int height) - { - for (var i = 0; i < height; ++i) - { - if (!IsWhiteSpace(bmp.GetPixel(col, i))) - { - return false; - } - } - return true; - } - - /// - /// Determines if a color is whitespace - /// - /// The color. - /// true if [is white space] [the specified color]; otherwise, false. - private static bool IsWhiteSpace(Color color) - { - return (color.R == 255 && color.G == 255 && color.B == 255) || color.A == 0; - } - } -} diff --git a/Emby.Drawing.Net/ImageHelpers.cs b/Emby.Drawing.Net/ImageHelpers.cs deleted file mode 100644 index 1afc47cd03..0000000000 --- a/Emby.Drawing.Net/ImageHelpers.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Emby.Drawing.Net -{ - internal static class ImageHelpers - { - internal static List ProjectPaths(List paths, int count) - { - if (count <= 0) - { - throw new ArgumentOutOfRangeException("count"); - } - if (paths.Count == 0) - { - throw new ArgumentOutOfRangeException("paths"); - } - - var list = new List(); - - AddToList(list, paths, count); - - return list.Take(count).ToList(); - } - - private static void AddToList(List list, List paths, int count) - { - while (list.Count < count) - { - foreach (var path in paths) - { - list.Add(path); - - if (list.Count >= count) - { - return; - } - } - } - } - } -} diff --git a/Emby.Drawing.Net/PercentPlayedDrawer.cs b/Emby.Drawing.Net/PercentPlayedDrawer.cs deleted file mode 100644 index fac15ba47a..0000000000 --- a/Emby.Drawing.Net/PercentPlayedDrawer.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Drawing; - -namespace Emby.Drawing.Net -{ - public class PercentPlayedDrawer - { - private const int IndicatorHeight = 8; - - public void Process(Graphics graphics, Size imageSize, double percent) - { - var y = imageSize.Height - IndicatorHeight; - - using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 0, 0, 0))) - { - const int innerX = 0; - var innerY = y; - var innerWidth = imageSize.Width; - var innerHeight = imageSize.Height; - - graphics.FillRectangle(backdroundBrush, innerX, innerY, innerWidth, innerHeight); - - using (var foregroundBrush = new SolidBrush(Color.FromArgb(82, 181, 75))) - { - double foregroundWidth = innerWidth; - foregroundWidth *= percent; - foregroundWidth /= 100; - - graphics.FillRectangle(foregroundBrush, innerX, innerY, Convert.ToInt32(Math.Round(foregroundWidth)), innerHeight); - } - } - } - } -} diff --git a/Emby.Drawing.Net/PlayedIndicatorDrawer.cs b/Emby.Drawing.Net/PlayedIndicatorDrawer.cs deleted file mode 100644 index 53683e6f45..0000000000 --- a/Emby.Drawing.Net/PlayedIndicatorDrawer.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Drawing; - -namespace Emby.Drawing.Net -{ - public class PlayedIndicatorDrawer - { - private const int IndicatorHeight = 40; - public const int IndicatorWidth = 40; - private const int FontSize = 40; - private const int OffsetFromTopRightCorner = 10; - - public void DrawPlayedIndicator(Graphics graphics, Size imageSize) - { - var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; - - using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75))) - { - graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight); - - x = imageSize.Width - 45 - OffsetFromTopRightCorner; - - using (var font = new Font("Webdings", FontSize, FontStyle.Regular, GraphicsUnit.Pixel)) - { - using (var fontBrush = new SolidBrush(Color.White)) - { - graphics.DrawString("a", font, fontBrush, x, OffsetFromTopRightCorner - 2); - } - } - } - } - } -} diff --git a/Emby.Drawing.Net/Properties/AssemblyInfo.cs b/Emby.Drawing.Net/Properties/AssemblyInfo.cs deleted file mode 100644 index 321c3a297c..0000000000 --- a/Emby.Drawing.Net/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Emby.Drawing.Net")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Emby.Drawing.Net")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("c97a239e-a96c-4d64-a844-ccf8cc30aecb")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Emby.Drawing.Net/UnplayedCountIndicator.cs b/Emby.Drawing.Net/UnplayedCountIndicator.cs deleted file mode 100644 index a38abeb324..0000000000 --- a/Emby.Drawing.Net/UnplayedCountIndicator.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Drawing; - -namespace Emby.Drawing.Net -{ - public class UnplayedCountIndicator - { - private const int IndicatorHeight = 41; - public const int IndicatorWidth = 41; - private const int OffsetFromTopRightCorner = 10; - - public void DrawUnplayedCountIndicator(Graphics graphics, Size imageSize, int count) - { - var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; - - using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75))) - { - graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight); - - var text = count.ToString(); - - x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; - var y = OffsetFromTopRightCorner + 6; - var fontSize = 24; - - if (text.Length == 1) - { - x += 10; - } - else if (text.Length == 2) - { - x += 3; - } - else if (text.Length == 3) - { - x += 1; - y += 1; - fontSize = 20; - } - - using (var font = new Font("Sans-Serif", fontSize, FontStyle.Regular, GraphicsUnit.Pixel)) - { - using (var fontBrush = new SolidBrush(Color.White)) - { - graphics.DrawString(text, font, fontBrush, x, y); - } - } - } - } - } -} diff --git a/Emby.Drawing.Net/empty.png b/Emby.Drawing.Net/empty.png deleted file mode 100644 index 34b25c436eca940c70f3000cbed29c05d3fb09af..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-5RT~NgajamnSt@nn_3Sb Oi^0>?&t;ucLK6T^iVOh& diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index fa603a0867..8ecae1b5bf 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -35,7 +35,6 @@ - diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 9cc2fe1036..d5ed61936b 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.IO; using System.Linq; @@ -194,26 +194,13 @@ namespace Jellyfin.Server IEnvironmentInfo environment, ILocalizationManager localizationManager) { - if (!startupOptions.ContainsOption("-enablegdi")) + try { - try - { - return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); - } - catch (Exception ex) - { - logger.LogInformation(ex, "Skia not available. Will try next image processor. {0}"); - } - - try - { - return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment); - } - catch (Exception ex) - { - logger.LogInformation(ex, "ImageMagick not available. Will try next image processor."); - } - _logger.LogInformation("Falling back on NullImageEncoder"); + return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); + } + catch (Exception ex) + { + logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}"); } return new NullImageEncoder(); diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 077bc6aee7..6e9f240b07 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -3,13 +3,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{E60FB157-87E2-4A41-8B04-27EA49B63B4D}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.exe = .nuget\NuGet.exe - .nuget\NuGet.targets = .nuget\NuGet.targets - EndProjectSection -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Controller", "MediaBrowser.Controller\MediaBrowser.Controller.csproj", "{17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.Api", "MediaBrowser.Api\MediaBrowser.Api.csproj", "{4FD51AC5-2C16-4308-A993-C3A84F3B4582}" @@ -42,8 +35,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RSSDP", "RSSDP\RSSDP.csproj EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Dlna", "Emby.Dlna\Emby.Dlna.csproj", "{805844AB-E92F-45E6-9D99-4F6D48D129A5}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing.ImageMagick", "Emby.Drawing.ImageMagick\Emby.Drawing.ImageMagick.csproj", "{6CFEE013-6E7C-432B-AC37-CABF0880C69A}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Drawing.Skia", "Emby.Drawing.Skia\Emby.Drawing.Skia.csproj", "{2312DA6D-FF86-4597-9777-BCEEC32D96DD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mono.Nat", "Mono.Nat\Mono.Nat.csproj", "{CB7F2326-6497-4A3D-BA03-48513B17A7BE}" @@ -54,526 +45,131 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Notifications", "Emby. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.Naming", "Emby.Naming\Emby.Naming.csproj", "{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageMagickSharp", "ImageMagickSharp\ImageMagickSharp\ImageMagickSharp.csproj", "{124E0710-6572-497B-B2A5-696AA08AD8BB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "taglib-sharp", "ThirdParty\taglib-sharp\src\taglib-sharp.csproj", "{D45FC504-D06B-41A0-A220-C20B7E8F1304}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "taglib-sharp", "ThirdParty\taglib-sharp\src\taglib-sharp.csproj", "{D45FC504-D06B-41A0-A220-C20B7E8F1304}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj", "{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.XmlTv", "Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj", "{6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IsoMounter", "Emby.IsoMounting\IsoMounter\IsoMounter.csproj", "{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IsoMounter", "Emby.IsoMounting\IsoMounter\IsoMounter.csproj", "{9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{960295EE-4AF4-4440-A525-B4C295B01A61}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Win32.ActiveCfg = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x64.ActiveCfg = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x86.ActiveCfg = Debug|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|x86.Build.0 = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.Build.0 = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Win32.ActiveCfg = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x64.ActiveCfg = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x86.ActiveCfg = Release|Any CPU - {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|x86.Build.0 = Release|Any CPU {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|Win32.ActiveCfg = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x64.ActiveCfg = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x86.ActiveCfg = Debug|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Debug|x86.Build.0 = Debug|Any CPU {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.ActiveCfg = Release|Any CPU {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Any CPU.Build.0 = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|Win32.ActiveCfg = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x64.ActiveCfg = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x86.ActiveCfg = Release|Any CPU - {4FD51AC5-2C16-4308-A993-C3A84F3B4582}.Release|x86.Build.0 = Release|Any CPU {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|Win32.ActiveCfg = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x64.ActiveCfg = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x86.ActiveCfg = Debug|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Debug|x86.Build.0 = Debug|Any CPU {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.ActiveCfg = Release|Any CPU {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Any CPU.Build.0 = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|Win32.ActiveCfg = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x64.ActiveCfg = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x86.ActiveCfg = Release|Any CPU - {9142EEFA-7570-41E1-BFCC-468BB571AF2F}.Release|x86.Build.0 = Release|Any CPU {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|Win32.ActiveCfg = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x64.ActiveCfg = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x86.ActiveCfg = Debug|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Debug|x86.Build.0 = Debug|Any CPU {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.ActiveCfg = Release|Any CPU {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Any CPU.Build.0 = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|Win32.ActiveCfg = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x64.ActiveCfg = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x86.ActiveCfg = Release|Any CPU - {7EEEB4BB-F3E8-48FC-B4C5-70F0FFF8329B}.Release|x86.Build.0 = Release|Any CPU {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|Win32.ActiveCfg = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x64.ActiveCfg = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x86.ActiveCfg = Debug|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Debug|x86.Build.0 = Debug|Any CPU {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.ActiveCfg = Release|Any CPU {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Any CPU.Build.0 = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|Win32.ActiveCfg = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x64.ActiveCfg = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x86.ActiveCfg = Release|Any CPU - {5624B7B5-B5A7-41D8-9F10-CC5611109619}.Release|x86.Build.0 = Release|Any CPU {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|Win32.ActiveCfg = Debug|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|x64.ActiveCfg = Debug|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Debug|x86.ActiveCfg = Debug|Any CPU {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.ActiveCfg = Release|Any CPU {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Any CPU.Build.0 = Release|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|Win32.ActiveCfg = Release|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|x64.ActiveCfg = Release|Any CPU - {442B5058-DCAF-4263-BB6A-F21E31120A1B}.Release|x86.ActiveCfg = Release|Any CPU {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|Win32.ActiveCfg = Debug|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|x64.ActiveCfg = Debug|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Debug|x86.ActiveCfg = Debug|Any CPU {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.ActiveCfg = Release|Any CPU {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Any CPU.Build.0 = Release|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|Win32.ActiveCfg = Release|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|x64.ActiveCfg = Release|Any CPU - {4A4402D4-E910-443B-B8FC-2C18286A2CA0}.Release|x86.ActiveCfg = Release|Any CPU {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {23499896-B135-4527-8574-C26E926EA99E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Debug|Win32.ActiveCfg = Debug|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Debug|x64.ActiveCfg = Debug|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Debug|x86.ActiveCfg = Debug|Any CPU {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.ActiveCfg = Release|Any CPU {23499896-B135-4527-8574-C26E926EA99E}.Release|Any CPU.Build.0 = Release|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Release|Win32.ActiveCfg = Release|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Release|x64.ActiveCfg = Release|Any CPU - {23499896-B135-4527-8574-C26E926EA99E}.Release|x86.ActiveCfg = Release|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|Win32.ActiveCfg = Debug|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|x64.ActiveCfg = Debug|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Debug|x86.ActiveCfg = Debug|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.ActiveCfg = Release|Any CPU {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Any CPU.Build.0 = Release|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|Win32.ActiveCfg = Release|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x64.ActiveCfg = Release|Any CPU - {7EF9F3E0-697D-42F3-A08F-19DEB5F84392}.Release|x86.ActiveCfg = Release|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Any CPU.Build.0 = Debug|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|Win32.ActiveCfg = Debug|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|x64.ActiveCfg = Debug|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Debug|x86.ActiveCfg = Debug|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.ActiveCfg = Release|Any CPU {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Any CPU.Build.0 = Release|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|Win32.ActiveCfg = Release|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x64.ActiveCfg = Release|Any CPU - {08FFF49B-F175-4807-A2B5-73B0EBD9F716}.Release|x86.ActiveCfg = Release|Any CPU {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Win32.ActiveCfg = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|Win32.Build.0 = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x64.ActiveCfg = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x64.Build.0 = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x86.ActiveCfg = Debug|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Debug|x86.Build.0 = Debug|Any CPU {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.ActiveCfg = Release|Any CPU {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Any CPU.Build.0 = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Win32.ActiveCfg = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|Win32.Build.0 = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x64.ActiveCfg = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x64.Build.0 = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x86.ActiveCfg = Release|Any CPU - {89AB4548-770D-41FD-A891-8DAFF44F452C}.Release|x86.Build.0 = Release|Any CPU {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Win32.ActiveCfg = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|Win32.Build.0 = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x64.ActiveCfg = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x64.Build.0 = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x86.ActiveCfg = Debug|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Debug|x86.Build.0 = Debug|Any CPU {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.ActiveCfg = Release|Any CPU {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Any CPU.Build.0 = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Win32.ActiveCfg = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|Win32.Build.0 = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x64.ActiveCfg = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x64.Build.0 = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x86.ActiveCfg = Release|Any CPU - {713F42B5-878E-499D-A878-E4C652B1D5E8}.Release|x86.Build.0 = Release|Any CPU {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Win32.ActiveCfg = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|Win32.Build.0 = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x64.ActiveCfg = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x64.Build.0 = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x86.ActiveCfg = Debug|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Debug|x86.Build.0 = Debug|Any CPU {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.ActiveCfg = Release|Any CPU {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Any CPU.Build.0 = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Win32.ActiveCfg = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|Win32.Build.0 = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x64.ActiveCfg = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x64.Build.0 = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x86.ActiveCfg = Release|Any CPU - {88AE38DF-19D7-406F-A6A9-09527719A21E}.Release|x86.Build.0 = Release|Any CPU {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Win32.ActiveCfg = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|Win32.Build.0 = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x64.ActiveCfg = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x64.Build.0 = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x86.ActiveCfg = Debug|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Debug|x86.Build.0 = Debug|Any CPU {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.ActiveCfg = Release|Any CPU {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Any CPU.Build.0 = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Win32.ActiveCfg = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|Win32.Build.0 = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x64.ActiveCfg = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x64.Build.0 = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x86.ActiveCfg = Release|Any CPU - {E383961B-9356-4D5D-8233-9A1079D03055}.Release|x86.Build.0 = Release|Any CPU {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Win32.ActiveCfg = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|Win32.Build.0 = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x64.ActiveCfg = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x64.Build.0 = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x86.ActiveCfg = Debug|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Debug|x86.Build.0 = Debug|Any CPU {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.ActiveCfg = Release|Any CPU {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Any CPU.Build.0 = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Win32.ActiveCfg = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|Win32.Build.0 = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x64.ActiveCfg = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x64.Build.0 = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x86.ActiveCfg = Release|Any CPU - {21002819-C39A-4D3E-BE83-2A276A77FB1F}.Release|x86.Build.0 = Release|Any CPU {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Win32.ActiveCfg = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|Win32.Build.0 = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x64.ActiveCfg = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x64.Build.0 = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x86.ActiveCfg = Debug|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Debug|x86.Build.0 = Debug|Any CPU {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.ActiveCfg = Release|Any CPU {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Any CPU.Build.0 = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Win32.ActiveCfg = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|Win32.Build.0 = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x64.ActiveCfg = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x64.Build.0 = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x86.ActiveCfg = Release|Any CPU - {805844AB-E92F-45E6-9D99-4F6D48D129A5}.Release|x86.Build.0 = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Win32.ActiveCfg = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|Win32.Build.0 = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x64.ActiveCfg = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x64.Build.0 = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x86.ActiveCfg = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Debug|x86.Build.0 = Debug|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Any CPU.Build.0 = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Win32.ActiveCfg = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|Win32.Build.0 = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x64.ActiveCfg = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x64.Build.0 = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x86.ActiveCfg = Release|Any CPU - {6CFEE013-6E7C-432B-AC37-CABF0880C69A}.Release|x86.Build.0 = Release|Any CPU {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Win32.ActiveCfg = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|Win32.Build.0 = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x64.ActiveCfg = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x64.Build.0 = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x86.ActiveCfg = Debug|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Debug|x86.Build.0 = Debug|Any CPU {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Any CPU.Build.0 = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Win32.ActiveCfg = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|Win32.Build.0 = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x64.ActiveCfg = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x64.Build.0 = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x86.ActiveCfg = Release|Any CPU - {2312DA6D-FF86-4597-9777-BCEEC32D96DD}.Release|x86.Build.0 = Release|Any CPU {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Win32.ActiveCfg = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|Win32.Build.0 = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x64.ActiveCfg = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x64.Build.0 = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x86.ActiveCfg = Debug|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Debug|x86.Build.0 = Debug|Any CPU {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Any CPU.Build.0 = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Win32.ActiveCfg = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|Win32.Build.0 = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x64.ActiveCfg = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x64.Build.0 = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x86.ActiveCfg = Release|Any CPU - {CB7F2326-6497-4A3D-BA03-48513B17A7BE}.Release|x86.Build.0 = Release|Any CPU {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Win32.ActiveCfg = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|Win32.Build.0 = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x64.ActiveCfg = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x64.Build.0 = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x86.ActiveCfg = Debug|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Debug|x86.Build.0 = Debug|Any CPU {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.ActiveCfg = Release|Any CPU {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Any CPU.Build.0 = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Win32.ActiveCfg = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|Win32.Build.0 = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x64.ActiveCfg = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x64.Build.0 = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x86.ActiveCfg = Release|Any CPU - {1D74413B-E7CF-455B-B021-F52BDF881542}.Release|x86.Build.0 = Release|Any CPU {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Win32.ActiveCfg = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|Win32.Build.0 = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x64.ActiveCfg = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x64.Build.0 = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x86.ActiveCfg = Debug|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Debug|x86.Build.0 = Debug|Any CPU {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Any CPU.Build.0 = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Win32.ActiveCfg = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|Win32.Build.0 = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x64.ActiveCfg = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x64.Build.0 = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x86.ActiveCfg = Release|Any CPU - {2E030C33-6923-4530-9E54-FA29FA6AD1A9}.Release|x86.Build.0 = Release|Any CPU {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Win32.ActiveCfg = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|Win32.Build.0 = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x64.ActiveCfg = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x64.Build.0 = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x86.ActiveCfg = Debug|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Debug|x86.Build.0 = Debug|Any CPU {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Any CPU.Build.0 = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Win32.ActiveCfg = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|Win32.Build.0 = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x64.ActiveCfg = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x64.Build.0 = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x86.ActiveCfg = Release|Any CPU - {E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}.Release|x86.Build.0 = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Win32.ActiveCfg = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|Win32.Build.0 = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x64.ActiveCfg = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x64.Build.0 = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x86.ActiveCfg = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Debug|x86.Build.0 = Debug|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Any CPU.Build.0 = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Win32.ActiveCfg = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|Win32.Build.0 = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x64.ActiveCfg = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x64.Build.0 = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x86.ActiveCfg = Release|Any CPU - {124E0710-6572-497B-B2A5-696AA08AD8BB}.Release|x86.Build.0 = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Win32.ActiveCfg = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Win32.Build.0 = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x64.ActiveCfg = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x64.Build.0 = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x86.ActiveCfg = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|x86.Build.0 = Debug|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.Build.0 = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Win32.ActiveCfg = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Win32.Build.0 = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x64.ActiveCfg = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x64.Build.0 = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x86.ActiveCfg = Release|Any CPU - {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|x86.Build.0 = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Win32.ActiveCfg = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Win32.Build.0 = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x64.ActiveCfg = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x64.Build.0 = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x86.ActiveCfg = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|x86.Build.0 = Debug|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.Build.0 = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Win32.ActiveCfg = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Win32.Build.0 = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x64.ActiveCfg = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x64.Build.0 = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x86.ActiveCfg = Release|Any CPU - {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|x86.Build.0 = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Win32.ActiveCfg = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Win32.Build.0 = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x64.ActiveCfg = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x64.Build.0 = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x86.ActiveCfg = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|x86.Build.0 = Debug|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Win32.ActiveCfg = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Win32.Build.0 = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x64.ActiveCfg = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x64.Build.0 = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.ActiveCfg = Release|Any CPU - {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|x86.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Win32.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Win32.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x64.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x64.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x86.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|x86.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Win32.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Win32.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x64.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x64.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|x86.Build.0 = Release|Any CPU {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Debug|Any CPU.Build.0 = Debug|Any CPU {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Release|Any CPU.ActiveCfg = Release|Any CPU {D45FC504-D06B-41A0-A220-C20B7E8F1304}.Release|Any CPU.Build.0 = Release|Any CPU + {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6EAFA7F0-8A82-49E6-B2FA-086C5CAEA95B}.Release|Any CPU.Build.0 = Release|Any CPU + {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9BA471D2-6DB9-4DBF-B3A0-9FB3171F94A6}.Release|Any CPU.Build.0 = Release|Any CPU + {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU + {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU + {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 22adb838e6364839647a60731c17b464e494538a Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Thu, 3 Jan 2019 21:35:08 +0100 Subject: [PATCH 082/125] Removed last using. --- Jellyfin.Server/Program.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index d5ed61936b..2dd4d9af66 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -8,7 +8,6 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Emby.Drawing; -using Emby.Drawing.ImageMagick; using Emby.Drawing.Skia; using Emby.Server.Implementations; using Emby.Server.Implementations.EnvironmentInfo; From 6a8b94b0c795b42aa894136445996df4557e8387 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 21:54:59 +0100 Subject: [PATCH 083/125] Remove SMB support This doesn't mean you can't use an SMB share to store your files for Jellyfin. You will just have to connect to it on the OS level. --- .../IO/ManagedFileSystem.cs | 189 - .../IO/SharpCifs/Config.cs | 409 -- .../IO/SharpCifs/Dcerpc/DcerpcBind.cs | 102 - .../IO/SharpCifs/Dcerpc/DcerpcBinding.cs | 122 - .../IO/SharpCifs/Dcerpc/DcerpcConstants.cs | 40 - .../IO/SharpCifs/Dcerpc/DcerpcError.cs | 48 - .../IO/SharpCifs/Dcerpc/DcerpcException.cs | 93 - .../IO/SharpCifs/Dcerpc/DcerpcHandle.cs | 332 -- .../IO/SharpCifs/Dcerpc/DcerpcMessage.cs | 150 - .../IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs | 135 - .../Dcerpc/DcerpcSecurityProvider.cs | 29 - .../SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs | 43 - .../SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs | 34 - .../IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs | 1161 ----- .../Dcerpc/Msrpc/MsrpcDfsRootEnum.cs | 43 - .../Msrpc/MsrpcEnumerateAliasesInDomain.cs | 29 - .../Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs | 29 - .../SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs | 34 - .../Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs | 35 - .../Msrpc/MsrpcQueryInformationPolicy.cs | 30 - .../Dcerpc/Msrpc/MsrpcSamrConnect2.cs | 28 - .../Dcerpc/Msrpc/MsrpcSamrConnect4.cs | 28 - .../Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs | 28 - .../Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs | 28 - .../SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs | 55 - .../Dcerpc/Msrpc/MsrpcShareGetInfo.cs | 43 - .../IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs | 616 --- .../IO/SharpCifs/Dcerpc/Msrpc/Samr.cs | 579 --- .../SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs | 40 - .../Dcerpc/Msrpc/SamrDomainHandle.cs | 41 - .../Dcerpc/Msrpc/SamrPolicyHandle.cs | 49 - .../IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs | 734 ---- .../IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs | 305 -- .../IO/SharpCifs/Dcerpc/Ndr/NdrException.cs | 32 - .../IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs | 40 - .../IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs | 40 - .../IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs | 27 - .../IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs | 40 - .../IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs | 40 - .../IO/SharpCifs/Dcerpc/Rpc.cs | 285 -- .../IO/SharpCifs/Dcerpc/UUID.cs | 148 - .../IO/SharpCifs/Dcerpc/UnicodeString.cs | 65 - .../IO/SharpCifs/Netbios/Lmhosts.cs | 202 - .../IO/SharpCifs/Netbios/Name.cs | 269 -- .../IO/SharpCifs/Netbios/NameQueryRequest.cs | 52 - .../IO/SharpCifs/Netbios/NameQueryResponse.cs | 68 - .../IO/SharpCifs/Netbios/NameServiceClient.cs | 664 --- .../IO/SharpCifs/Netbios/NameServicePacket.cs | 448 -- .../IO/SharpCifs/Netbios/NbtAddress.cs | 920 ---- .../IO/SharpCifs/Netbios/NbtException.cs | 164 - .../IO/SharpCifs/Netbios/NodeStatusRequest.cs | 59 - .../SharpCifs/Netbios/NodeStatusResponse.cs | 140 - .../SharpCifs/Netbios/SessionRequestPacket.cs | 63 - .../Netbios/SessionRetargetResponsePacket.cs | 54 - .../SharpCifs/Netbios/SessionServicePacket.cs | 156 - .../IO/SharpCifs/Ntlmssp/NtlmFlags.cs | 197 - .../IO/SharpCifs/Ntlmssp/NtlmMessage.cs | 140 - .../IO/SharpCifs/Ntlmssp/Type1Message.cs | 249 -- .../IO/SharpCifs/Ntlmssp/Type2Message.cs | 438 -- .../IO/SharpCifs/Ntlmssp/Type3Message.cs | 677 --- .../IO/SharpCifs/Smb/ACE.cs | 287 -- .../IO/SharpCifs/Smb/AllocInfo.cs | 25 - .../SharpCifs/Smb/AndXServerMessageBlock.cs | 221 - .../IO/SharpCifs/Smb/BufferCache.cs | 80 - .../IO/SharpCifs/Smb/Dfs.cs | 389 -- .../IO/SharpCifs/Smb/DfsReferral.cs | 67 - .../IO/SharpCifs/Smb/DosError.cs | 64 - .../IO/SharpCifs/Smb/DosFileFilter.cs | 37 - .../IO/SharpCifs/Smb/FileEntry.cs | 33 - .../IO/SharpCifs/Smb/IInfo.cs | 29 - .../IO/SharpCifs/Smb/NetServerEnum2.cs | 122 - .../SharpCifs/Smb/NetServerEnum2Response.cs | 157 - .../IO/SharpCifs/Smb/NetShareEnum.cs | 95 - .../IO/SharpCifs/Smb/NetShareEnumResponse.cs | 94 - .../IO/SharpCifs/Smb/NtStatus.cs | 202 - .../SharpCifs/Smb/NtTransQuerySecurityDesc.cs | 88 - .../Smb/NtTransQuerySecurityDescResponse.cs | 78 - .../IO/SharpCifs/Smb/NtlmAuthenticator.cs | 93 - .../IO/SharpCifs/Smb/NtlmChallenge.cs | 40 - .../IO/SharpCifs/Smb/NtlmContext.cs | 206 - .../Smb/NtlmPasswordAuthentication.cs | 807 ---- .../IO/SharpCifs/Smb/Principal.cs | 28 - .../IO/SharpCifs/Smb/SID.cs | 900 ---- .../IO/SharpCifs/Smb/SecurityDescriptor.cs | 101 - .../IO/SharpCifs/Smb/ServerMessageBlock.cs | 692 --- .../IO/SharpCifs/Smb/SigningDigest.cs | 257 -- .../IO/SharpCifs/Smb/SmbAuthException.cs | 36 - .../IO/SharpCifs/Smb/SmbComBlankResponse.cs | 47 - .../IO/SharpCifs/Smb/SmbComClose.cs | 62 - .../IO/SharpCifs/Smb/SmbComCreateDirectory.cs | 57 - .../IO/SharpCifs/Smb/SmbComDelete.cs | 63 - .../IO/SharpCifs/Smb/SmbComDeleteDirectory.cs | 57 - .../IO/SharpCifs/Smb/SmbComFindClose2.cs | 56 - .../IO/SharpCifs/Smb/SmbComLogoffAndX.cs | 52 - .../IO/SharpCifs/Smb/SmbComNTCreateAndX.cs | 193 - .../Smb/SmbComNTCreateAndXResponse.cs | 116 - .../IO/SharpCifs/Smb/SmbComNegotiate.cs | 70 - .../SharpCifs/Smb/SmbComNegotiateResponse.cs | 164 - .../IO/SharpCifs/Smb/SmbComNtTransaction.cs | 93 - .../Smb/SmbComNtTransactionResponse.cs | 63 - .../IO/SharpCifs/Smb/SmbComOpenAndX.cs | 190 - .../SharpCifs/Smb/SmbComOpenAndXResponse.cs | 87 - .../SharpCifs/Smb/SmbComQueryInformation.cs | 57 - .../Smb/SmbComQueryInformationResponse.cs | 95 - .../IO/SharpCifs/Smb/SmbComReadAndX.cs | 107 - .../SharpCifs/Smb/SmbComReadAndXResponse.cs | 87 - .../IO/SharpCifs/Smb/SmbComRename.cs | 75 - .../SharpCifs/Smb/SmbComSessionSetupAndX.cs | 234 -- .../Smb/SmbComSessionSetupAndXResponse.cs | 92 - .../IO/SharpCifs/Smb/SmbComTransaction.cs | 346 -- .../Smb/SmbComTransactionResponse.cs | 206 - .../IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs | 226 - .../Smb/SmbComTreeConnectAndXResponse.cs | 84 - .../IO/SharpCifs/Smb/SmbComTreeDisconnect.cs | 52 - .../IO/SharpCifs/Smb/SmbComWrite.cs | 106 - .../IO/SharpCifs/Smb/SmbComWriteAndX.cs | 150 - .../SharpCifs/Smb/SmbComWriteAndXResponse.cs | 50 - .../IO/SharpCifs/Smb/SmbComWriteResponse.cs | 50 - .../IO/SharpCifs/Smb/SmbConstants.cs | 302 -- .../IO/SharpCifs/Smb/SmbException.cs | 212 - .../IO/SharpCifs/Smb/SmbFile.cs | 3735 ----------------- .../IO/SharpCifs/Smb/SmbFileExtensions.cs | 133 - .../IO/SharpCifs/Smb/SmbFileFilter.cs | 24 - .../IO/SharpCifs/Smb/SmbFileInputStream.cs | 339 -- .../IO/SharpCifs/Smb/SmbFileOutputStream.cs | 335 -- .../IO/SharpCifs/Smb/SmbFilenameFilter.cs | 24 - .../IO/SharpCifs/Smb/SmbNamedPipe.cs | 210 - .../IO/SharpCifs/Smb/SmbRandomAccessFile.cs | 506 --- .../IO/SharpCifs/Smb/SmbSession.cs | 570 --- .../IO/SharpCifs/Smb/SmbShareInfo.cs | 104 - .../IO/SharpCifs/Smb/SmbTransport.cs | 977 ----- .../IO/SharpCifs/Smb/SmbTree.cs | 250 -- .../IO/SharpCifs/Smb/Trans2FindFirst2.cs | 146 - .../SharpCifs/Smb/Trans2FindFirst2Response.cs | 262 -- .../IO/SharpCifs/Smb/Trans2FindNext2.cs | 109 - .../IO/SharpCifs/Smb/Trans2GetDfsReferral.cs | 78 - .../Smb/Trans2GetDfsReferralResponse.cs | 179 - .../SharpCifs/Smb/Trans2QueryFSInformation.cs | 80 - .../Smb/Trans2QueryFSInformationResponse.cs | 192 - .../Smb/Trans2QueryPathInformation.cs | 85 - .../Smb/Trans2QueryPathInformationResponse.cs | 227 - .../SharpCifs/Smb/Trans2SetFileInformation.cs | 105 - .../Smb/Trans2SetFileInformationResponse.cs | 63 - .../IO/SharpCifs/Smb/TransCallNamedPipe.cs | 97 - .../Smb/TransCallNamedPipeResponse.cs | 77 - .../IO/SharpCifs/Smb/TransPeekNamedPipe.cs | 78 - .../Smb/TransPeekNamedPipeResponse.cs | 84 - .../SharpCifs/Smb/TransTransactNamedPipe.cs | 97 - .../Smb/TransTransactNamedPipeResponse.cs | 77 - .../IO/SharpCifs/Smb/TransWaitNamedPipe.cs | 76 - .../Smb/TransWaitNamedPipeResponse.cs | 59 - .../Smb/TransactNamedPipeInputStream.cs | 180 - .../Smb/TransactNamedPipeOutputStream.cs | 86 - .../IO/SharpCifs/Smb/WinError.cs | 49 - .../IO/SharpCifs/UniAddress.cs | 591 --- .../IO/SharpCifs/Util/Base64.cs | 110 - .../IO/SharpCifs/Util/DES.cs | 568 --- .../IO/SharpCifs/Util/Encdec.cs | 401 -- .../IO/SharpCifs/Util/HMACT64.cs | 146 - .../IO/SharpCifs/Util/Hexdump.cs | 191 - .../IO/SharpCifs/Util/LogStream.cs | 78 - .../IO/SharpCifs/Util/MD4.cs | 347 -- .../IO/SharpCifs/Util/RC4.cs | 68 - .../IO/SharpCifs/Util/Sharpen/AbstractMap.cs | 151 - .../IO/SharpCifs/Util/Sharpen/Arrays.cs | 59 - .../SharpCifs/Util/Sharpen/BufferedReader.cs | 11 - .../SharpCifs/Util/Sharpen/BufferedWriter.cs | 58 - .../IO/SharpCifs/Util/Sharpen/CharBuffer.cs | 19 - .../IO/SharpCifs/Util/Sharpen/CharSequence.cs | 32 - .../IO/SharpCifs/Util/Sharpen/Collections.cs | 147 - .../Util/Sharpen/ConcurrentHashMap.cs | 122 - .../IO/SharpCifs/Util/Sharpen/DateFormat.cs | 37 - .../Util/Sharpen/EnumeratorWrapper.cs | 55 - .../IO/SharpCifs/Util/Sharpen/Exceptions.cs | 217 - .../IO/SharpCifs/Util/Sharpen/Extensions.cs | 696 --- .../SharpCifs/Util/Sharpen/FileInputStream.cs | 20 - .../Util/Sharpen/FileOutputStream.cs | 33 - .../IO/SharpCifs/Util/Sharpen/FilePath.cs | 313 -- .../IO/SharpCifs/Util/Sharpen/FileReader.cs | 13 - .../IO/SharpCifs/Util/Sharpen/FileWriter.cs | 18 - .../Util/Sharpen/FilterInputStream.cs | 57 - .../Util/Sharpen/FilterOutputStream.cs | 37 - .../IO/SharpCifs/Util/Sharpen/Hashtable.cs | 20 - .../Util/Sharpen/HttpURLConnection.cs | 37 - .../IO/SharpCifs/Util/Sharpen/ICallable.cs | 7 - .../SharpCifs/Util/Sharpen/IConcurrentMap.cs | 11 - .../IO/SharpCifs/Util/Sharpen/IExecutor.cs | 7 - .../SharpCifs/Util/Sharpen/IFilenameFilter.cs | 7 - .../IO/SharpCifs/Util/Sharpen/IFuture.cs | 8 - .../Util/Sharpen/IPrivilegedAction.cs | 7 - .../IO/SharpCifs/Util/Sharpen/IRunnable.cs | 7 - .../IO/SharpCifs/Util/Sharpen/InputStream.cs | 169 - .../Util/Sharpen/InputStreamReader.cs | 25 - .../IO/SharpCifs/Util/Sharpen/Iterator.cs | 53 - .../IO/SharpCifs/Util/Sharpen/LinkageError.cs | 11 - .../IO/SharpCifs/Util/Sharpen/MD5.cs | 275 -- .../IO/SharpCifs/Util/Sharpen/MD5Managed.cs | 91 - .../IO/SharpCifs/Util/Sharpen/Matcher.cs | 83 - .../SharpCifs/Util/Sharpen/MessageDigest.cs | 118 - .../SharpCifs/Util/Sharpen/NetworkStream.cs | 72 - .../Util/Sharpen/ObjectInputStream.cs | 25 - .../Util/Sharpen/ObjectOutputStream.cs | 19 - .../IO/SharpCifs/Util/Sharpen/OutputStream.cs | 86 - .../Util/Sharpen/OutputStreamWriter.cs | 20 - .../Util/Sharpen/PipedInputStream.cs | 172 - .../Util/Sharpen/PipedOutputStream.cs | 37 - .../IO/SharpCifs/Util/Sharpen/PrintWriter.cs | 231 - .../IO/SharpCifs/Util/Sharpen/Properties.cs | 86 - .../Util/Sharpen/RandomAccessFile.cs | 87 - .../SharpCifs/Util/Sharpen/ReentrantLock.cs | 22 - .../IO/SharpCifs/Util/Sharpen/Reference.cs | 7 - .../IO/SharpCifs/Util/Sharpen/Runtime.cs | 212 - .../Util/Sharpen/SimpleDateFormat.cs | 62 - .../IO/SharpCifs/Util/Sharpen/SocketEx.cs | 161 - .../SharpCifs/Util/Sharpen/StringTokenizer.cs | 32 - .../Util/Sharpen/SynchronizedList.cs | 106 - .../IO/SharpCifs/Util/Sharpen/Thread.cs | 193 - .../SharpCifs/Util/Sharpen/ThreadFactory.cs | 13 - .../Util/Sharpen/ThreadPoolExecutor.cs | 166 - .../Util/Sharpen/WrappedSystemStream.cs | 139 - .../IO/SharpCifs/Util/Transport/Request.cs | 22 - .../IO/SharpCifs/Util/Transport/Response.cs | 25 - .../IO/SharpCifs/Util/Transport/Transport.cs | 454 -- .../Util/Transport/TransportException.cs | 63 - .../IO/SharpCifsFileSystem.cs | 621 --- 225 files changed, 38824 deletions(-) delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Config.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs delete mode 100644 Emby.Server.Implementations/IO/SharpCifsFileSystem.cs diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 8819449b5c..0f85e0642b 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -24,7 +24,6 @@ namespace Emby.Server.Implementations.IO private string _tempPath; - private SharpCifsFileSystem _sharpCifsFileSystem; private IEnvironmentInfo _environmentInfo; private bool _isEnvironmentCaseInsensitive; @@ -43,8 +42,6 @@ namespace Emby.Server.Implementations.IO SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows); - _sharpCifsFileSystem = new SharpCifsFileSystem(environmentInfo.OperatingSystem); - _isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows; } @@ -233,11 +230,6 @@ namespace Emby.Server.Implementations.IO /// property will be set to true and all other properties will reflect the properties of the directory. public FileSystemMetadata GetFileSystemInfo(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileSystemInfo(path); - } - // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists if (Path.HasExtension(path)) { @@ -273,11 +265,6 @@ namespace Emby.Server.Implementations.IO /// For automatic handling of files and directories, use . public FileSystemMetadata GetFileInfo(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileInfo(path); - } - var fileInfo = new FileInfo(path); return GetFileSystemMetadata(fileInfo); @@ -293,11 +280,6 @@ namespace Emby.Server.Implementations.IO /// For automatic handling of files and directories, use . public FileSystemMetadata GetDirectoryInfo(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetDirectoryInfo(path); - } - var fileInfo = new DirectoryInfo(path); return GetFileSystemMetadata(fileInfo); @@ -460,11 +442,6 @@ namespace Emby.Server.Implementations.IO /// FileStream. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileStream(path, mode, access, share); - } - if (_supportsAsyncFileStreams && isAsync) { return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous); @@ -475,11 +452,6 @@ namespace Emby.Server.Implementations.IO public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileStream(path, mode, access, share); - } - var defaultBufferSize = 4096; return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions)); } @@ -550,12 +522,6 @@ namespace Emby.Server.Implementations.IO return; } - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.SetHidden(path, isHidden); - return; - } - var info = GetExtendedFileSystemInfo(path); if (info.Exists && info.IsHidden != isHidden) @@ -580,12 +546,6 @@ namespace Emby.Server.Implementations.IO return; } - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.SetReadOnly(path, isReadOnly); - return; - } - var info = GetExtendedFileSystemInfo(path); if (info.Exists && info.IsReadOnly != isReadOnly) @@ -610,12 +570,6 @@ namespace Emby.Server.Implementations.IO return; } - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.SetAttributes(path, isHidden, isReadOnly); - return; - } - var info = GetExtendedFileSystemInfo(path); if (!info.Exists) @@ -688,11 +642,6 @@ namespace Emby.Server.Implementations.IO private char GetDirectorySeparatorChar(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetDirectorySeparatorChar(path); - } - return Path.DirectorySeparatorChar; } @@ -732,11 +681,6 @@ namespace Emby.Server.Implementations.IO public string GetDirectoryName(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetDirectoryName(path); - } - return Path.GetDirectoryName(path); } @@ -747,11 +691,6 @@ namespace Emby.Server.Implementations.IO throw new ArgumentNullException("path"); } - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.NormalizePath(path); - } - if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase)) { return path; @@ -794,11 +733,6 @@ namespace Emby.Server.Implementations.IO { // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\ - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return true; - } - if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 && !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) { @@ -812,35 +746,17 @@ namespace Emby.Server.Implementations.IO public void DeleteFile(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.DeleteFile(path); - return; - } - SetAttributes(path, false, false); File.Delete(path); } public void DeleteDirectory(string path, bool recursive) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.DeleteDirectory(path, recursive); - return; - } - Directory.Delete(path, recursive); } public void CreateDirectory(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.CreateDirectory(path); - return; - } - Directory.CreateDirectory(path); } @@ -863,11 +779,6 @@ namespace Emby.Server.Implementations.IO public IEnumerable GetDirectories(string path, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetDirectories(path, recursive); - } - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption)); @@ -880,11 +791,6 @@ namespace Emby.Server.Implementations.IO public IEnumerable GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive); - } - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; // On linux and osx the search pattern is case sensitive @@ -914,11 +820,6 @@ namespace Emby.Server.Implementations.IO public IEnumerable GetFileSystemEntries(string path, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive); - } - var directoryInfo = new DirectoryInfo(path); var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; @@ -938,29 +839,16 @@ namespace Emby.Server.Implementations.IO public string[] ReadAllLines(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.ReadAllLines(path); - } return File.ReadAllLines(path); } public void WriteAllLines(string path, IEnumerable lines) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.WriteAllLines(path, lines); - return; - } File.WriteAllLines(path, lines); } public Stream OpenRead(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.OpenRead(path); - } return File.OpenRead(path); } @@ -977,128 +865,61 @@ namespace Emby.Server.Implementations.IO public void CopyFile(string source, string target, bool overwrite) { - var enableSharpCifsForSource = _sharpCifsFileSystem.IsEnabledForPath(source); - - if (enableSharpCifsForSource != _sharpCifsFileSystem.IsEnabledForPath(target)) - { - CopyFileUsingStreams(source, target, overwrite); - return; - } - - if (enableSharpCifsForSource) - { - _sharpCifsFileSystem.CopyFile(source, target, overwrite); - return; - } File.Copy(source, target, overwrite); } public void MoveFile(string source, string target) { - if (_sharpCifsFileSystem.IsEnabledForPath(source)) - { - _sharpCifsFileSystem.MoveFile(source, target); - return; - } File.Move(source, target); } public void MoveDirectory(string source, string target) { - if (_sharpCifsFileSystem.IsEnabledForPath(source)) - { - _sharpCifsFileSystem.MoveDirectory(source, target); - return; - } Directory.Move(source, target); } public bool DirectoryExists(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.DirectoryExists(path); - } return Directory.Exists(path); } public bool FileExists(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.FileExists(path); - } return File.Exists(path); } public string ReadAllText(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.ReadAllText(path); - } return File.ReadAllText(path); } public byte[] ReadAllBytes(string path) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.ReadAllBytes(path); - } return File.ReadAllBytes(path); } public void WriteAllText(string path, string text, Encoding encoding) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.WriteAllText(path, text, encoding); - return; - } - File.WriteAllText(path, text, encoding); } public void WriteAllText(string path, string text) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.WriteAllText(path, text); - return; - } - File.WriteAllText(path, text); } public void WriteAllBytes(string path, byte[] bytes) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - _sharpCifsFileSystem.WriteAllBytes(path, bytes); - return; - } - File.WriteAllBytes(path, bytes); } public string ReadAllText(string path, Encoding encoding) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.ReadAllText(path, encoding); - } - return File.ReadAllText(path, encoding); } public IEnumerable GetDirectoryPaths(string path, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive); - } - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; return Directory.EnumerateDirectories(path, "*", searchOption); } @@ -1110,11 +931,6 @@ namespace Emby.Server.Implementations.IO public IEnumerable GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive); - } - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; // On linux and osx the search pattern is case sensitive @@ -1144,11 +960,6 @@ namespace Emby.Server.Implementations.IO public IEnumerable GetFileSystemEntryPaths(string path, bool recursive = false) { - if (_sharpCifsFileSystem.IsEnabledForPath(path)) - { - return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive); - } - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; return Directory.EnumerateFileSystemEntries(path, "*", searchOption); } diff --git a/Emby.Server.Implementations/IO/SharpCifs/Config.cs b/Emby.Server.Implementations/IO/SharpCifs/Config.cs deleted file mode 100644 index 324a9c494d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Config.cs +++ /dev/null @@ -1,409 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using System.Net; -using System.Security; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs -{ - /// - /// This class uses a static - /// Sharpen.Properties - /// to act - /// as a cental repository for all jCIFS configuration properties. It cannot be - /// instantiated. Similar to System properties the namespace - /// is global therefore property names should be unique. Before use, - /// the load method should be called with the name of a - /// Properties file (or null indicating no - /// file) to initialize the Config. The System - /// properties will then populate the Config as well potentially - /// overwriting properties from the file. Thus properties provided on the - /// commandline with the -Dproperty.name=value VM parameter - /// will override properties from the configuration file. - /// - /// There are several ways to set jCIFS properties. See - /// the overview page of the API - /// documentation for details. - /// - public class Config - { - - /// The static Properties. - /// The static Properties. - private static Properties _prp = new Properties(); - - private static LogStream _log; - - public static string DefaultOemEncoding = "UTF-8"; //"Cp850"; - - static Config() - { - int level; - FileInputStream fis = null; - _log = LogStream.GetInstance(); - - try - { - string filename = Runtime.GetProperty("jcifs.properties"); - if (filename != null && filename.Length > 1) - { - fis = new FileInputStream(filename); - } - Load(fis); - if (fis != null) - { - fis.Close(); - } - } - catch (IOException ioe) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(ioe, _log); - } - } - - if ((level = GetInt("jcifs.util.loglevel", -1)) != -1) - { - _log.SetLevel(level); - } - - try - { - Runtime.GetBytesForString(string.Empty, DefaultOemEncoding); - } - catch (Exception) - { - if (_log.Level >= 2) - { - _log.WriteLine("WARNING: The default OEM encoding " + DefaultOemEncoding + " does not appear to be supported by this JRE. The default encoding will be US-ASCII." - ); - } - - //DEFAULT_OEM_ENCODING = "US-ASCII"; - } - - if (_log.Level >= 4) - { - try - { - _prp.Store(_log); - } - catch (IOException) - { - } - } - } - - /// - /// This static method registers the SMB URL protocol handler which is - /// required to use SMB URLs with the java.net.URL class. - /// - /// - /// This static method registers the SMB URL protocol handler which is - /// required to use SMB URLs with the java.net.URL class. If this - /// method is not called before attempting to create an SMB URL with the - /// URL class the following exception will occur: - ///
-        /// Exception MalformedURLException: unknown protocol: smb
-        /// at java.net.URL.(URL.java:480)
-        /// at java.net.URL.(URL.java:376)
-        /// at java.net.URL.(URL.java:330)
-        /// at jcifs.smb.SmbFile.(SmbFile.java:355)
-        /// ...
-        /// 
- /// - public static void RegisterSmbURLHandler() - { - throw new NotImplementedException(); - } - - // supress javadoc constructor summary by removing 'protected' - /// Set the default properties of the static Properties used by Config. - /// - /// - /// Set the default properties of the static Properties used by Config. This permits - /// a different Properties object/file to be used as the source of properties for - /// use by the jCIFS library. The Properties must be set before jCIFS - /// classes are accessed as most jCIFS classes load properties statically once. - /// Using this method will also override properties loaded - /// using the -Djcifs.properties= commandline parameter. - /// - public static void SetProperties(Properties prp) - { - Config._prp = new Properties(prp); - try - { - Config._prp.PutAll(Runtime.GetProperties()); - } - catch (SecurityException) - { - if (_log.Level > 1) - { - _log.WriteLine("SecurityException: jcifs will ignore System properties"); - } - } - } - - /// - /// Load the Config with properties from the stream - /// in from a Properties file. - /// - /// - /// Load the Config with properties from the stream - /// in from a Properties file. - /// - /// - public static void Load(InputStream input) - { - if (input != null) - { - _prp.Load(input); - } - try - { - _prp.PutAll(Runtime.GetProperties()); - } - catch (SecurityException) - { - if (_log.Level > 1) - { - _log.WriteLine("SecurityException: jcifs will ignore System properties"); - } - } - } - - /// - public static void Store(OutputStream output, string header) - { - _prp.Store(output); - } - - /// Add a property. - /// Add a property. - public static void SetProperty(string key, string value) - { - _prp.SetProperty(key, value); - } - - /// Retrieve a property as an Object. - /// Retrieve a property as an Object. - public static object Get(string key) - { - return _prp.GetProperty(key); - } - - /// Retrieve a String. - /// - /// Retrieve a String. If the key cannot be found, - /// the provided def default parameter will be returned. - /// - public static string GetProperty(string key, string def) - { - return (string)_prp.GetProperty(key, def); - } - - /// Retrieve a String. - /// Retrieve a String. If the property is not found, null is returned. - /// - public static string GetProperty(string key) - { - return (string)_prp.GetProperty(key); - } - - /// Retrieve an int. - /// - /// Retrieve an int. If the key does not exist or - /// cannot be converted to an int, the provided default - /// argument will be returned. - /// - public static int GetInt(string key, int def) - { - string s = (string)_prp.GetProperty(key); - if (s != null) - { - try - { - def = Convert.ToInt32(s); - } - catch (FormatException nfe) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(nfe, _log); - } - } - } - return def; - } - - /// Retrieve an int. - /// Retrieve an int. If the property is not found, -1 is returned. - /// - public static int GetInt(string key) - { - string s = (string)_prp.GetProperty(key); - int result = -1; - if (s != null) - { - try - { - result = Convert.ToInt32(s); - } - catch (FormatException nfe) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(nfe, _log); - } - } - } - return result; - } - - /// Retrieve a long. - /// - /// Retrieve a long. If the key does not exist or - /// cannot be converted to a long, the provided default - /// argument will be returned. - /// - public static long GetLong(string key, long def) - { - string s = (string)_prp.GetProperty(key); - if (s != null) - { - try - { - def = long.Parse(s); - } - catch (FormatException nfe) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(nfe, _log); - } - } - } - return def; - } - - /// Retrieve an InetAddress. - /// - /// Retrieve an InetAddress. If the address is not - /// an IP address and cannot be resolved null will - /// be returned. - /// - public static IPAddress GetInetAddress(string key, IPAddress def) - { - string addr = (string)_prp.GetProperty(key); - if (addr != null) - { - try - { - def = Extensions.GetAddressByName(addr); - } - catch (UnknownHostException uhe) - { - if (_log.Level > 0) - { - _log.WriteLine(addr); - Runtime.PrintStackTrace(uhe, _log); - } - } - } - return def; - } - - public static IPAddress GetLocalHost() - { - string addr = (string)_prp.GetProperty("jcifs.smb.client.laddr"); - if (addr != null) - { - try - { - return Extensions.GetAddressByName(addr); - } - catch (UnknownHostException uhe) - { - if (_log.Level > 0) - { - _log.WriteLine("Ignoring jcifs.smb.client.laddr address: " + addr); - Runtime.PrintStackTrace(uhe, _log); - } - } - } - return null; - } - - /// Retrieve a boolean value. - /// Retrieve a boolean value. If the property is not found, the value of def is returned. - /// - public static bool GetBoolean(string key, bool def) - { - string b = GetProperty(key); - if (b != null) - { - def = b.ToLower().Equals("true"); - } - return def; - } - - /// - /// Retrieve an array of InetAddress created from a property - /// value containting a delim separated list of hostnames and/or - /// ipaddresses. - /// - /// - /// Retrieve an array of InetAddress created from a property - /// value containting a delim separated list of hostnames and/or - /// ipaddresses. - /// - public static IPAddress[] GetInetAddressArray(string key, string delim, IPAddress - [] def) - { - string p = GetProperty(key); - if (p != null) - { - StringTokenizer tok = new StringTokenizer(p, delim); - int len = tok.CountTokens(); - IPAddress[] arr = new IPAddress[len]; - for (int i = 0; i < len; i++) - { - string addr = tok.NextToken(); - try - { - arr[i] = Extensions.GetAddressByName(addr); - } - catch (UnknownHostException uhe) - { - if (_log.Level > 0) - { - _log.WriteLine(addr); - Runtime.PrintStackTrace(uhe, _log); - } - return def; - } - } - return arr; - } - return def; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs deleted file mode 100644 index 1d8d13c08c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs +++ /dev/null @@ -1,102 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; -using SharpCifs.Util; - -namespace SharpCifs.Dcerpc -{ - public class DcerpcBind : DcerpcMessage - { - internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED" - , "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED" - }; - - internal static string GetResultMessage(int result) - { - return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4 - ); - } - - public override DcerpcException GetResult() - { - if (Result != 0) - { - return new DcerpcException(GetResultMessage(Result)); - } - return null; - } - - internal DcerpcBinding Binding; - - internal int MaxXmit; - - internal int MaxRecv; - - public DcerpcBind() - { - } - - internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle) - { - this.Binding = binding; - MaxXmit = handle.MaxXmit; - MaxRecv = handle.MaxRecv; - Ptype = 11; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - - public override int GetOpnum() - { - return 0; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_short(MaxXmit); - dst.Enc_ndr_short(MaxRecv); - dst.Enc_ndr_long(0); - dst.Enc_ndr_small(1); - dst.Enc_ndr_small(0); - dst.Enc_ndr_short(0); - dst.Enc_ndr_short(0); - dst.Enc_ndr_small(1); - dst.Enc_ndr_small(0); - Binding.Uuid.Encode(dst); - dst.Enc_ndr_short(Binding.Major); - dst.Enc_ndr_short(Binding.Minor); - DcerpcConstants.DcerpcUuidSyntaxNdr.Encode(dst); - dst.Enc_ndr_long(2); - } - - /// - public override void Decode_out(NdrBuffer src) - { - src.Dec_ndr_short(); - src.Dec_ndr_short(); - src.Dec_ndr_long(); - int n = src.Dec_ndr_short(); - src.Advance(n); - src.Align(4); - src.Dec_ndr_small(); - src.Align(4); - Result = src.Dec_ndr_short(); - src.Dec_ndr_short(); - src.Advance(20); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs deleted file mode 100644 index 2341506642..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs +++ /dev/null @@ -1,122 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Dcerpc.Msrpc; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Dcerpc -{ - public class DcerpcBinding - { - private static Hashtable _interfaces; - - static DcerpcBinding() - { - _interfaces = new Hashtable(); - _interfaces.Put("srvsvc", Srvsvc.GetSyntax()); - _interfaces.Put("lsarpc", Lsarpc.GetSyntax()); - _interfaces.Put("samr", Samr.GetSyntax()); - _interfaces.Put("netdfs", Netdfs.GetSyntax()); - } - - public static void AddInterface(string name, string syntax) - { - _interfaces.Put(name, syntax); - } - - internal string Proto; - - internal string Server; - - internal string Endpoint; - - internal Hashtable Options; - - internal Uuid Uuid; - - internal int Major; - - internal int Minor; - - internal DcerpcBinding(string proto, string server) - { - this.Proto = proto; - this.Server = server; - } - - /// - internal virtual void SetOption(string key, object val) - { - if (key.Equals("endpoint")) - { - Endpoint = val.ToString().ToLower(); - if (Endpoint.StartsWith("\\pipe\\")) - { - string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6)); - if (iface != null) - { - int c; - int p; - c = iface.IndexOf(':'); - p = iface.IndexOf('.', c + 1); - Uuid = new Uuid(Runtime.Substring(iface, 0, c)); - Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p)); - Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1)); - return; - } - } - throw new DcerpcException("Bad endpoint: " + Endpoint); - } - if (Options == null) - { - Options = new Hashtable(); - } - Options.Put(key, val); - } - - internal virtual object GetOption(string key) - { - if (key.Equals("endpoint")) - { - return Endpoint; - } - if (Options != null) - { - return Options.Get(key); - } - return null; - } - - public override string ToString() - { - /* string ret = proto + ":" + server + "[" + endpoint; - if (options != null) - { - Iterator iter = (Iterator) options.Keys.GetEnumerator(); - while (iter.HasNext()) - { - object key = iter.Next(); - object val = options.Get(key); - ret += "," + key + "=" + val; - } - } - ret += "]"; - return ret; */ - return null; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs deleted file mode 100644 index 5b69c5c2ec..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcConstants.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc -{ - public static class DcerpcConstants - { - public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860" - ); - - public static int DcerpcFirstFrag = unchecked(0x01); - - public static int DcerpcLastFrag = unchecked(0x02); - - public static int DcerpcPendingCancel = unchecked(0x04); - - public static int DcerpcReserved1 = unchecked(0x08); - - public static int DcerpcConcMpx = unchecked(0x10); - - public static int DcerpcDidNotExecute = unchecked(0x20); - - public static int DcerpcMaybe = unchecked(0x40); - - public static int DcerpcObjectUuid = unchecked(0x80); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs deleted file mode 100644 index 55c0610650..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcError.cs +++ /dev/null @@ -1,48 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc -{ - public static class DcerpcError - { - public static int DcerpcFaultOther = unchecked(0x00000001); - - public static int DcerpcFaultAccessDenied = unchecked(0x00000005); - - public static int DcerpcFaultCantPerform = unchecked(0x000006D8); - - public static int DcerpcFaultNdr = unchecked(0x000006F7); - - public static int DcerpcFaultInvalidTag = unchecked(0x1C000006); - - public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A); - - public static int DcerpcFaultOpRngError = unchecked(0x1C010002); - - public static int DcerpcFaultUnkIf = unchecked(0x1C010003); - - public static int DcerpcFaultProtoError = unchecked(0x1c01000b); - - public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied - , DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch - , DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError }; - - public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER" - , "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR", - "DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR" - , "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" }; - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs deleted file mode 100644 index 13c4f0d0cd..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcException.cs +++ /dev/null @@ -1,93 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Dcerpc -{ - - public class DcerpcException : IOException - { - internal static string GetMessageByDcerpcError(int errcode) - { - int min = 0; - int max = DcerpcError.DcerpcFaultCodes.Length; - while (max >= min) - { - int mid = (min + max) / 2; - if (errcode > DcerpcError.DcerpcFaultCodes[mid]) - { - min = mid + 1; - } - else - { - if (errcode < DcerpcError.DcerpcFaultCodes[mid]) - { - max = mid - 1; - } - else - { - return DcerpcError.DcerpcFaultMessages[mid]; - } - } - } - return "0x" + Hexdump.ToHexString(errcode, 8); - } - - private int _error; - - private Exception _rootCause; - - internal DcerpcException(int error) : base(GetMessageByDcerpcError(error)) - { - this._error = error; - } - - public DcerpcException(string msg) : base(msg) - { - } - - public DcerpcException(string msg, Exception rootCause) : base(msg) - { - this._rootCause = rootCause; - } - - public virtual int GetErrorCode() - { - return _error; - } - - public virtual Exception GetRootCause() - { - return _rootCause; - } - - public override string ToString() - { - if (_rootCause != null) - { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - Runtime.PrintStackTrace(_rootCause, pw); - return base.ToString() + "\n" + sw; - } - return base.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs deleted file mode 100644 index e82af2b0cf..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs +++ /dev/null @@ -1,332 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Dcerpc.Ndr; -using SharpCifs.Smb; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Dcerpc -{ - public abstract class DcerpcHandle - { - /// - protected internal static DcerpcBinding ParseBinding(string str) - { - int state; - int mark; - int si; - char[] arr = str.ToCharArray(); - string proto = null; - string key = null; - DcerpcBinding binding = null; - state = mark = si = 0; - do - { - char ch = arr[si]; - switch (state) - { - case 0: - { - if (ch == ':') - { - proto = Runtime.Substring(str, mark, si); - mark = si + 1; - state = 1; - } - break; - } - - case 1: - { - if (ch == '\\') - { - mark = si + 1; - break; - } - state = 2; - goto case 2; - } - - case 2: - { - if (ch == '[') - { - string server = Runtime.Substring(str, mark, si).Trim(); - if (server.Length == 0) - { - server = "127.0.0.1"; - } - binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si)); - mark = si + 1; - state = 5; - } - break; - } - - case 5: - { - if (ch == '=') - { - key = Runtime.Substring(str, mark, si).Trim(); - mark = si + 1; - } - else - { - if (ch == ',' || ch == ']') - { - string val = Runtime.Substring(str, mark, si).Trim(); - if (key == null) - { - key = "endpoint"; - } - binding.SetOption(key, val); - key = null; - } - } - break; - } - - default: - { - si = arr.Length; - break; - } - } - si++; - } - while (si < arr.Length); - if (binding == null || binding.Endpoint == null) - { - throw new DcerpcException("Invalid binding URL: " + str); - } - return binding; - } - - protected internal DcerpcBinding Binding; - - protected internal int MaxXmit = 4280; - - protected internal int MaxRecv; - - protected internal int State; - - protected internal IDcerpcSecurityProvider SecurityProvider; - - private static int _callId = 1; - - /// - /// - /// - public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth) - { - if (url.StartsWith("ncacn_np:")) - { - return new DcerpcPipeHandle(url, auth); - } - throw new DcerpcException("DCERPC transport not supported: " + url); - } - - /// - /// - public virtual void Bind() - { - lock (this) - { - try - { - State = 1; - DcerpcMessage bind = new DcerpcBind(Binding, this); - Sendrecv(bind); - } - catch (IOException) - { - State = 0; - throw; - } - } - } - - /// - /// - public virtual void Sendrecv(DcerpcMessage msg) - { - byte[] stub; - byte[] frag; - NdrBuffer buf; - NdrBuffer fbuf; - bool isLast; - bool isDirect; - DcerpcException de; - if (State == 0) - { - Bind(); - } - isDirect = true; - stub = BufferCache.GetBuffer(); - try - { - int off; - int tot; - int n; - buf = new NdrBuffer(stub, 0); - msg.Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - msg.CallId = _callId++; - msg.Encode(buf); - if (SecurityProvider != null) - { - buf.SetIndex(0); - SecurityProvider.Wrap(buf); - } - tot = buf.GetLength() - 24; - off = 0; - while (off < tot) - { - n = tot - off; - if ((24 + n) > MaxXmit) - { - msg.Flags &= ~DcerpcConstants.DcerpcLastFrag; - n = MaxXmit - 24; - } - else - { - msg.Flags |= DcerpcConstants.DcerpcLastFrag; - isDirect = false; - msg.AllocHint = n; - } - msg.Length = 24 + n; - if (off > 0) - { - msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag; - } - if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag | - DcerpcConstants.DcerpcLastFrag)) - { - buf.Start = off; - buf.Reset(); - msg.Encode_header(buf); - buf.Enc_ndr_long(msg.AllocHint); - buf.Enc_ndr_short(0); - buf.Enc_ndr_short(msg.GetOpnum()); - } - DoSendFragment(stub, off, msg.Length, isDirect); - off += n; - } - DoReceiveFragment(stub, isDirect); - buf.Reset(); - buf.SetIndex(8); - buf.SetLength(buf.Dec_ndr_short()); - if (SecurityProvider != null) - { - SecurityProvider.Unwrap(buf); - } - buf.SetIndex(0); - msg.Decode_header(buf); - off = 24; - if (msg.Ptype == 2 && msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false) - { - off = msg.Length; - } - frag = null; - fbuf = null; - while (msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false) - { - int stubFragLen; - if (frag == null) - { - frag = new byte[MaxRecv]; - fbuf = new NdrBuffer(frag, 0); - } - DoReceiveFragment(frag, isDirect); - fbuf.Reset(); - fbuf.SetIndex(8); - fbuf.SetLength(fbuf.Dec_ndr_short()); - if (SecurityProvider != null) - { - SecurityProvider.Unwrap(fbuf); - } - fbuf.Reset(); - msg.Decode_header(fbuf); - stubFragLen = msg.Length - 24; - if ((off + stubFragLen) > stub.Length) - { - // shouldn't happen if alloc_hint is correct or greater - byte[] tmp = new byte[off + stubFragLen]; - Array.Copy(stub, 0, tmp, 0, off); - stub = tmp; - } - Array.Copy(frag, 24, stub, off, stubFragLen); - off += stubFragLen; - } - buf = new NdrBuffer(stub, 0); - msg.Decode(buf); - } - finally - { - BufferCache.ReleaseBuffer(stub); - } - if ((de = msg.GetResult()) != null) - { - throw de; - } - } - - public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider - ) - { - this.SecurityProvider = securityProvider; - } - - public virtual string GetServer() - { - if (this is DcerpcPipeHandle) - { - return ((DcerpcPipeHandle)this).Pipe.GetServer(); - } - return null; - } - - public virtual Principal GetPrincipal() - { - if (this is DcerpcPipeHandle) - { - return ((DcerpcPipeHandle)this).Pipe.GetPrincipal(); - } - return null; - } - - public override string ToString() - { - return Binding.ToString(); - } - - /// - protected internal abstract void DoSendFragment(byte[] buf, int off, int length, - bool isDirect); - - /// - protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect); - - /// - public abstract void Close(); - - public DcerpcHandle() - { - MaxRecv = MaxXmit; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs deleted file mode 100644 index 543dd72dd0..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs +++ /dev/null @@ -1,150 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc -{ - public abstract class DcerpcMessage : NdrObject - { - protected internal int Ptype = -1; - - protected internal int Flags; - - protected internal int Length; - - protected internal int CallId; - - protected internal int AllocHint; - - protected internal int Result; - - public virtual bool IsFlagSet(int flag) - { - return (Flags & flag) == flag; - } - - public virtual void UnsetFlag(int flag) - { - Flags &= ~flag; - } - - public virtual void SetFlag(int flag) - { - Flags |= flag; - } - - public virtual DcerpcException GetResult() - { - if (Result != 0) - { - return new DcerpcException(Result); - } - return null; - } - - internal virtual void Encode_header(NdrBuffer buf) - { - buf.Enc_ndr_small(5); - buf.Enc_ndr_small(0); - buf.Enc_ndr_small(Ptype); - buf.Enc_ndr_small(Flags); - buf.Enc_ndr_long(unchecked(0x00000010)); - buf.Enc_ndr_short(Length); - buf.Enc_ndr_short(0); - buf.Enc_ndr_long(CallId); - } - - /// - internal virtual void Decode_header(NdrBuffer buf) - { - if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0) - { - throw new NdrException("DCERPC version not supported"); - } - Ptype = buf.Dec_ndr_small(); - Flags = buf.Dec_ndr_small(); - if (buf.Dec_ndr_long() != unchecked(0x00000010)) - { - throw new NdrException("Data representation not supported"); - } - Length = buf.Dec_ndr_short(); - if (buf.Dec_ndr_short() != 0) - { - throw new NdrException("DCERPC authentication not supported"); - } - CallId = buf.Dec_ndr_long(); - } - - /// - public override void Encode(NdrBuffer buf) - { - int start = buf.GetIndex(); - int allocHintIndex = 0; - buf.Advance(16); - if (Ptype == 0) - { - allocHintIndex = buf.GetIndex(); - buf.Enc_ndr_long(0); - buf.Enc_ndr_short(0); - buf.Enc_ndr_short(GetOpnum()); - } - Encode_in(buf); - Length = buf.GetIndex() - start; - if (Ptype == 0) - { - buf.SetIndex(allocHintIndex); - AllocHint = Length - allocHintIndex; - buf.Enc_ndr_long(AllocHint); - } - buf.SetIndex(start); - Encode_header(buf); - buf.SetIndex(start + Length); - } - - /// - public override void Decode(NdrBuffer buf) - { - Decode_header(buf); - if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13) - { - throw new NdrException("Unexpected ptype: " + Ptype); - } - if (Ptype == 2 || Ptype == 3) - { - AllocHint = buf.Dec_ndr_long(); - buf.Dec_ndr_short(); - buf.Dec_ndr_short(); - } - if (Ptype == 3 || Ptype == 13) - { - Result = buf.Dec_ndr_long(); - } - else - { - Decode_out(buf); - } - } - - public abstract int GetOpnum(); - - /// - public abstract void Encode_in(NdrBuffer dst); - - /// - public abstract void Decode_out(NdrBuffer src); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs deleted file mode 100644 index 0399578cd8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcPipeHandle.cs +++ /dev/null @@ -1,135 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Smb; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Dcerpc -{ - public class DcerpcPipeHandle : DcerpcHandle - { - internal SmbNamedPipe Pipe; - - internal SmbFileInputStream In; - - internal SmbFileOutputStream Out; - - internal bool IsStart = true; - - /// - /// - /// - public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth) - { - Binding = ParseBinding(url); - url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint - , 6); - string @params = string.Empty; - string server; - string address; - server = (string)Binding.GetOption("server"); - if (server != null) - { - @params += "&server=" + server; - } - address = (string)Binding.GetOption("address"); - if (server != null) - { - @params += "&address=" + address; - } - if (@params.Length > 0) - { - url += "?" + Runtime.Substring(@params, 1); - } - Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr - | SmbNamedPipe.PipeTypeDceTransact, auth); - } - - /// - protected internal override void DoSendFragment(byte[] buf, int off, int length, - bool isDirect) - { - if (Out != null && Out.IsOpen() == false) - { - throw new IOException("DCERPC pipe is no longer open"); - } - if (In == null) - { - In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream(); - } - if (Out == null) - { - Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream(); - } - if (isDirect) - { - Out.WriteDirect(buf, off, length, 1); - return; - } - Out.Write(buf, off, length); - } - - /// - protected internal override void DoReceiveFragment(byte[] buf, bool isDirect) - { - int off; - int flags; - int length; - if (buf.Length < MaxRecv) - { - throw new ArgumentException("buffer too small"); - } - if (IsStart && !isDirect) - { - // start of new frag, do trans - off = In.Read(buf, 0, 1024); - } - else - { - off = In.ReadDirect(buf, 0, buf.Length); - } - if (buf[0] != 5 && buf[1] != 0) - { - throw new IOException("Unexpected DCERPC PDU header"); - } - flags = buf[3] & unchecked(0xFF); - // next read is start of new frag - IsStart = (flags & DcerpcConstants.DcerpcLastFrag) == DcerpcConstants.DcerpcLastFrag; - length = Encdec.Dec_uint16le(buf, 8); - if (length > MaxRecv) - { - throw new IOException("Unexpected fragment length: " + length); - } - while (off < length) - { - off += In.ReadDirect(buf, off, length - off); - } - } - - /// - public override void Close() - { - State = 0; - if (Out != null) - { - Out.Close(); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs deleted file mode 100644 index cc46902f11..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcSecurityProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc -{ - public interface IDcerpcSecurityProvider - { - /// - void Wrap(NdrBuffer outgoing); - - /// - void Unwrap(NdrBuffer incoming); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs deleted file mode 100644 index 03964fcc77..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsaPolicyHandle.cs +++ /dev/null @@ -1,43 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class LsaPolicyHandle : Rpc.PolicyHandle - { - /// - public LsaPolicyHandle(DcerpcHandle handle, string server, int access) - { - if (server == null) - { - server = "\\\\"; - } - MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - } - - /// - public virtual void Close() - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs deleted file mode 100644 index ef09bb16e4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/LsarSidArrayX.cs +++ /dev/null @@ -1,34 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - internal class LsarSidArrayX : Lsarpc.LsarSidArray - { - internal LsarSidArrayX(Sid[] sids) - { - NumSids = sids.Length; - this.Sids = new Lsarpc.LsarSidPtr[sids.Length]; - for (int si = 0; si < sids.Length; si++) - { - this.Sids[si] = new Lsarpc.LsarSidPtr(); - this.Sids[si].Sid = sids[si]; - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs deleted file mode 100644 index 1ae85c4730..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs +++ /dev/null @@ -1,1161 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class Lsarpc - { - public static string GetSyntax() - { - return "12345778-1234-abcd-ef00-0123456789ab:0.0"; - } - - public class LsarQosInfo : NdrObject - { - public int Length; - - public short ImpersonationLevel; - - public byte ContextMode; - - public byte EffectiveOnly; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Length); - dst.Enc_ndr_short(ImpersonationLevel); - dst.Enc_ndr_small(ContextMode); - dst.Enc_ndr_small(EffectiveOnly); - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Length = src.Dec_ndr_long(); - ImpersonationLevel = (short)src.Dec_ndr_short(); - ContextMode = unchecked((byte)src.Dec_ndr_small()); - EffectiveOnly = unchecked((byte)src.Dec_ndr_small()); - } - } - - public class LsarObjectAttributes : NdrObject - { - public int Length; - - public NdrSmall RootDirectory; - - public Rpc.Unicode_string ObjectName; - - public int Attributes; - - public int SecurityDescriptor; - - public LsarQosInfo SecurityQualityOfService; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Length); - dst.Enc_ndr_referent(RootDirectory, 1); - dst.Enc_ndr_referent(ObjectName, 1); - dst.Enc_ndr_long(Attributes); - dst.Enc_ndr_long(SecurityDescriptor); - dst.Enc_ndr_referent(SecurityQualityOfService, 1); - if (RootDirectory != null) - { - dst = dst.Deferred; - RootDirectory.Encode(dst); - } - if (ObjectName != null) - { - dst = dst.Deferred; - ObjectName.Encode(dst); - } - if (SecurityQualityOfService != null) - { - dst = dst.Deferred; - SecurityQualityOfService.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Length = src.Dec_ndr_long(); - int rootDirectoryp = src.Dec_ndr_long(); - int objectNamep = src.Dec_ndr_long(); - Attributes = src.Dec_ndr_long(); - SecurityDescriptor = src.Dec_ndr_long(); - int securityQualityOfServicep = src.Dec_ndr_long(); - if (rootDirectoryp != 0) - { - src = src.Deferred; - RootDirectory.Decode(src); - } - if (objectNamep != 0) - { - if (ObjectName == null) - { - ObjectName = new Rpc.Unicode_string(); - } - src = src.Deferred; - ObjectName.Decode(src); - } - if (securityQualityOfServicep != 0) - { - if (SecurityQualityOfService == null) - { - SecurityQualityOfService = new LsarQosInfo(); - } - src = src.Deferred; - SecurityQualityOfService.Decode(src); - } - } - } - - public class LsarDomainInfo : NdrObject - { - public Rpc.Unicode_string Name; - - public Rpc.SidT Sid; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(Name.Length); - dst.Enc_ndr_short(Name.MaximumLength); - dst.Enc_ndr_referent(Name.Buffer, 1); - dst.Enc_ndr_referent(Sid, 1); - if (Name.Buffer != null) - { - dst = dst.Deferred; - int nameBufferl = Name.Length / 2; - int nameBuffers = Name.MaximumLength / 2; - dst.Enc_ndr_long(nameBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(nameBufferl); - int nameBufferi = dst.Index; - dst.Advance(2 * nameBufferl); - dst = dst.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - dst.Enc_ndr_short(Name.Buffer[i]); - } - } - if (Sid != null) - { - dst = dst.Deferred; - Sid.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - src.Align(4); - if (Name == null) - { - Name = new Rpc.Unicode_string(); - } - Name.Length = (short)src.Dec_ndr_short(); - Name.MaximumLength = (short)src.Dec_ndr_short(); - int nameBufferp = src.Dec_ndr_long(); - int sidp = src.Dec_ndr_long(); - if (nameBufferp != 0) - { - src = src.Deferred; - int nameBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int nameBufferl = src.Dec_ndr_long(); - int nameBufferi = src.Index; - src.Advance(2 * nameBufferl); - if (Name.Buffer == null) - { - if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Name.Buffer = new short[nameBuffers]; - } - src = src.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - Name.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - if (sidp != 0) - { - if (Sid == null) - { - Sid = new Rpc.SidT(); - } - src = src.Deferred; - Sid.Decode(src); - } - } - } - - public class LsarDnsDomainInfo : NdrObject - { - public Rpc.Unicode_string Name; - - public Rpc.Unicode_string DnsDomain; - - public Rpc.Unicode_string DnsForest; - - public Rpc.UuidT DomainGuid; - - public Rpc.SidT Sid; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(Name.Length); - dst.Enc_ndr_short(Name.MaximumLength); - dst.Enc_ndr_referent(Name.Buffer, 1); - dst.Enc_ndr_short(DnsDomain.Length); - dst.Enc_ndr_short(DnsDomain.MaximumLength); - dst.Enc_ndr_referent(DnsDomain.Buffer, 1); - dst.Enc_ndr_short(DnsForest.Length); - dst.Enc_ndr_short(DnsForest.MaximumLength); - dst.Enc_ndr_referent(DnsForest.Buffer, 1); - dst.Enc_ndr_long(DomainGuid.TimeLow); - dst.Enc_ndr_short(DomainGuid.TimeMid); - dst.Enc_ndr_short(DomainGuid.TimeHiAndVersion); - dst.Enc_ndr_small(DomainGuid.ClockSeqHiAndReserved); - dst.Enc_ndr_small(DomainGuid.ClockSeqLow); - int domainGuidNodes = 6; - int domainGuidNodei = dst.Index; - dst.Advance(1 * domainGuidNodes); - dst.Enc_ndr_referent(Sid, 1); - if (Name.Buffer != null) - { - dst = dst.Deferred; - int nameBufferl = Name.Length / 2; - int nameBuffers = Name.MaximumLength / 2; - dst.Enc_ndr_long(nameBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(nameBufferl); - int nameBufferi = dst.Index; - dst.Advance(2 * nameBufferl); - dst = dst.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - dst.Enc_ndr_short(Name.Buffer[i]); - } - } - if (DnsDomain.Buffer != null) - { - dst = dst.Deferred; - int dnsDomainBufferl = DnsDomain.Length / 2; - int dnsDomainBuffers = DnsDomain.MaximumLength / 2; - dst.Enc_ndr_long(dnsDomainBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(dnsDomainBufferl); - int dnsDomainBufferi = dst.Index; - dst.Advance(2 * dnsDomainBufferl); - dst = dst.Derive(dnsDomainBufferi); - for (int i = 0; i < dnsDomainBufferl; i++) - { - dst.Enc_ndr_short(DnsDomain.Buffer[i]); - } - } - if (DnsForest.Buffer != null) - { - dst = dst.Deferred; - int dnsForestBufferl = DnsForest.Length / 2; - int dnsForestBuffers = DnsForest.MaximumLength / 2; - dst.Enc_ndr_long(dnsForestBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(dnsForestBufferl); - int dnsForestBufferi = dst.Index; - dst.Advance(2 * dnsForestBufferl); - dst = dst.Derive(dnsForestBufferi); - for (int i = 0; i < dnsForestBufferl; i++) - { - dst.Enc_ndr_short(DnsForest.Buffer[i]); - } - } - dst = dst.Derive(domainGuidNodei); - for (int i1 = 0; i1 < domainGuidNodes; i1++) - { - dst.Enc_ndr_small(DomainGuid.Node[i1]); - } - if (Sid != null) - { - dst = dst.Deferred; - Sid.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - src.Align(4); - if (Name == null) - { - Name = new Rpc.Unicode_string(); - } - Name.Length = (short)src.Dec_ndr_short(); - Name.MaximumLength = (short)src.Dec_ndr_short(); - int nameBufferp = src.Dec_ndr_long(); - src.Align(4); - if (DnsDomain == null) - { - DnsDomain = new Rpc.Unicode_string(); - } - DnsDomain.Length = (short)src.Dec_ndr_short(); - DnsDomain.MaximumLength = (short)src.Dec_ndr_short(); - int dnsDomainBufferp = src.Dec_ndr_long(); - src.Align(4); - if (DnsForest == null) - { - DnsForest = new Rpc.Unicode_string(); - } - DnsForest.Length = (short)src.Dec_ndr_short(); - DnsForest.MaximumLength = (short)src.Dec_ndr_short(); - int dnsForestBufferp = src.Dec_ndr_long(); - src.Align(4); - if (DomainGuid == null) - { - DomainGuid = new Rpc.UuidT(); - } - DomainGuid.TimeLow = src.Dec_ndr_long(); - DomainGuid.TimeMid = (short)src.Dec_ndr_short(); - DomainGuid.TimeHiAndVersion = (short)src.Dec_ndr_short(); - DomainGuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small()); - DomainGuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small()); - int domainGuidNodes = 6; - int domainGuidNodei = src.Index; - src.Advance(1 * domainGuidNodes); - int sidp = src.Dec_ndr_long(); - if (nameBufferp != 0) - { - src = src.Deferred; - int nameBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int nameBufferl = src.Dec_ndr_long(); - int nameBufferi = src.Index; - src.Advance(2 * nameBufferl); - if (Name.Buffer == null) - { - if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Name.Buffer = new short[nameBuffers]; - } - src = src.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - Name.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - if (dnsDomainBufferp != 0) - { - src = src.Deferred; - int dnsDomainBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int dnsDomainBufferl = src.Dec_ndr_long(); - int dnsDomainBufferi = src.Index; - src.Advance(2 * dnsDomainBufferl); - if (DnsDomain.Buffer == null) - { - if (dnsDomainBuffers < 0 || dnsDomainBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - DnsDomain.Buffer = new short[dnsDomainBuffers]; - } - src = src.Derive(dnsDomainBufferi); - for (int i = 0; i < dnsDomainBufferl; i++) - { - DnsDomain.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - if (dnsForestBufferp != 0) - { - src = src.Deferred; - int dnsForestBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int dnsForestBufferl = src.Dec_ndr_long(); - int dnsForestBufferi = src.Index; - src.Advance(2 * dnsForestBufferl); - if (DnsForest.Buffer == null) - { - if (dnsForestBuffers < 0 || dnsForestBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - DnsForest.Buffer = new short[dnsForestBuffers]; - } - src = src.Derive(dnsForestBufferi); - for (int i = 0; i < dnsForestBufferl; i++) - { - DnsForest.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - if (DomainGuid.Node == null) - { - if (domainGuidNodes < 0 || domainGuidNodes > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - DomainGuid.Node = new byte[domainGuidNodes]; - } - src = src.Derive(domainGuidNodei); - for (int i1 = 0; i1 < domainGuidNodes; i1++) - { - DomainGuid.Node[i1] = unchecked((byte)src.Dec_ndr_small()); - } - if (sidp != 0) - { - if (Sid == null) - { - Sid = new Rpc.SidT(); - } - src = src.Deferred; - Sid.Decode(src); - } - } - } - - public const int PolicyInfoAuditEvents = 2; - - public const int PolicyInfoPrimaryDomain = 3; - - public const int PolicyInfoAccountDomain = 5; - - public const int PolicyInfoServerRole = 6; - - public const int PolicyInfoModification = 9; - - public const int PolicyInfoDnsDomain = 12; - - public class LsarSidPtr : NdrObject - { - public Rpc.SidT Sid; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(Sid, 1); - if (Sid != null) - { - dst = dst.Deferred; - Sid.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int sidp = src.Dec_ndr_long(); - if (sidp != 0) - { - if (Sid == null) - { - Sid = new Rpc.SidT(); - } - src = src.Deferred; - Sid.Decode(src); - } - } - } - - public class LsarSidArray : NdrObject - { - public int NumSids; - - public LsarSidPtr[] Sids; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(NumSids); - dst.Enc_ndr_referent(Sids, 1); - if (Sids != null) - { - dst = dst.Deferred; - int sidss = NumSids; - dst.Enc_ndr_long(sidss); - int sidsi = dst.Index; - dst.Advance(4 * sidss); - dst = dst.Derive(sidsi); - for (int i = 0; i < sidss; i++) - { - Sids[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - NumSids = src.Dec_ndr_long(); - int sidsp = src.Dec_ndr_long(); - if (sidsp != 0) - { - src = src.Deferred; - int sidss = src.Dec_ndr_long(); - int sidsi = src.Index; - src.Advance(4 * sidss); - if (Sids == null) - { - if (sidss < 0 || sidss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Sids = new LsarSidPtr[sidss]; - } - src = src.Derive(sidsi); - for (int i = 0; i < sidss; i++) - { - if (Sids[i] == null) - { - Sids[i] = new LsarSidPtr(); - } - Sids[i].Decode(src); - } - } - } - } - - public const int SidNameUseNone = 0; - - public const int SidNameUser = 1; - - public const int SidNameDomGrp = 2; - - public const int SidNameDomain = 3; - - public const int SidNameAlias = 4; - - public const int SidNameWknGrp = 5; - - public const int SidNameDeleted = 6; - - public const int SidNameInvalid = 7; - - public const int SidNameUnknown = 8; - - public class LsarTranslatedSid : NdrObject - { - public int SidType; - - public int Rid; - - public int SidIndex; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(SidType); - dst.Enc_ndr_long(Rid); - dst.Enc_ndr_long(SidIndex); - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - SidType = src.Dec_ndr_short(); - Rid = src.Dec_ndr_long(); - SidIndex = src.Dec_ndr_long(); - } - } - - public class LsarTransSidArray : NdrObject - { - public int Count; - - public LsarTranslatedSid[] Sids; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Sids, 1); - if (Sids != null) - { - dst = dst.Deferred; - int sidss = Count; - dst.Enc_ndr_long(sidss); - int sidsi = dst.Index; - dst.Advance(12 * sidss); - dst = dst.Derive(sidsi); - for (int i = 0; i < sidss; i++) - { - Sids[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int sidsp = src.Dec_ndr_long(); - if (sidsp != 0) - { - src = src.Deferred; - int sidss = src.Dec_ndr_long(); - int sidsi = src.Index; - src.Advance(12 * sidss); - if (Sids == null) - { - if (sidss < 0 || sidss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Sids = new LsarTranslatedSid[sidss]; - } - src = src.Derive(sidsi); - for (int i = 0; i < sidss; i++) - { - if (Sids[i] == null) - { - Sids[i] = new LsarTranslatedSid(); - } - Sids[i].Decode(src); - } - } - } - } - - public class LsarTrustInformation : NdrObject - { - public Rpc.Unicode_string Name; - - public Rpc.SidT Sid; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(Name.Length); - dst.Enc_ndr_short(Name.MaximumLength); - dst.Enc_ndr_referent(Name.Buffer, 1); - dst.Enc_ndr_referent(Sid, 1); - if (Name.Buffer != null) - { - dst = dst.Deferred; - int nameBufferl = Name.Length / 2; - int nameBuffers = Name.MaximumLength / 2; - dst.Enc_ndr_long(nameBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(nameBufferl); - int nameBufferi = dst.Index; - dst.Advance(2 * nameBufferl); - dst = dst.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - dst.Enc_ndr_short(Name.Buffer[i]); - } - } - if (Sid != null) - { - dst = dst.Deferred; - Sid.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - src.Align(4); - if (Name == null) - { - Name = new Rpc.Unicode_string(); - } - Name.Length = (short)src.Dec_ndr_short(); - Name.MaximumLength = (short)src.Dec_ndr_short(); - int nameBufferp = src.Dec_ndr_long(); - int sidp = src.Dec_ndr_long(); - if (nameBufferp != 0) - { - src = src.Deferred; - int nameBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int nameBufferl = src.Dec_ndr_long(); - int nameBufferi = src.Index; - src.Advance(2 * nameBufferl); - if (Name.Buffer == null) - { - if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Name.Buffer = new short[nameBuffers]; - } - src = src.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - Name.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - if (sidp != 0) - { - if (Sid == null) - { - Sid = new Rpc.SidT(); - } - src = src.Deferred; - Sid.Decode(src); - } - } - } - - public class LsarRefDomainList : NdrObject - { - public int Count; - - public LsarTrustInformation[] Domains; - - public int MaxCount; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Domains, 1); - dst.Enc_ndr_long(MaxCount); - if (Domains != null) - { - dst = dst.Deferred; - int domainss = Count; - dst.Enc_ndr_long(domainss); - int domainsi = dst.Index; - dst.Advance(12 * domainss); - dst = dst.Derive(domainsi); - for (int i = 0; i < domainss; i++) - { - Domains[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int domainsp = src.Dec_ndr_long(); - MaxCount = src.Dec_ndr_long(); - if (domainsp != 0) - { - src = src.Deferred; - int domainss = src.Dec_ndr_long(); - int domainsi = src.Index; - src.Advance(12 * domainss); - if (Domains == null) - { - if (domainss < 0 || domainss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Domains = new LsarTrustInformation[domainss]; - } - src = src.Derive(domainsi); - for (int i = 0; i < domainss; i++) - { - if (Domains[i] == null) - { - Domains[i] = new LsarTrustInformation(); - } - Domains[i].Decode(src); - } - } - } - } - - public class LsarTranslatedName : NdrObject - { - public short SidType; - - public Rpc.Unicode_string Name; - - public int SidIndex; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(SidType); - dst.Enc_ndr_short(Name.Length); - dst.Enc_ndr_short(Name.MaximumLength); - dst.Enc_ndr_referent(Name.Buffer, 1); - dst.Enc_ndr_long(SidIndex); - if (Name.Buffer != null) - { - dst = dst.Deferred; - int nameBufferl = Name.Length / 2; - int nameBuffers = Name.MaximumLength / 2; - dst.Enc_ndr_long(nameBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(nameBufferl); - int nameBufferi = dst.Index; - dst.Advance(2 * nameBufferl); - dst = dst.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - dst.Enc_ndr_short(Name.Buffer[i]); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - SidType = (short)src.Dec_ndr_short(); - src.Align(4); - if (Name == null) - { - Name = new Rpc.Unicode_string(); - } - Name.Length = (short)src.Dec_ndr_short(); - Name.MaximumLength = (short)src.Dec_ndr_short(); - int nameBufferp = src.Dec_ndr_long(); - SidIndex = src.Dec_ndr_long(); - if (nameBufferp != 0) - { - src = src.Deferred; - int nameBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int nameBufferl = src.Dec_ndr_long(); - int nameBufferi = src.Index; - src.Advance(2 * nameBufferl); - if (Name.Buffer == null) - { - if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Name.Buffer = new short[nameBuffers]; - } - src = src.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - Name.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - } - } - - public class LsarTransNameArray : NdrObject - { - public int Count; - - public LsarTranslatedName[] Names; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Names, 1); - if (Names != null) - { - dst = dst.Deferred; - int namess = Count; - dst.Enc_ndr_long(namess); - int namesi = dst.Index; - dst.Advance(16 * namess); - dst = dst.Derive(namesi); - for (int i = 0; i < namess; i++) - { - Names[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int namesp = src.Dec_ndr_long(); - if (namesp != 0) - { - src = src.Deferred; - int namess = src.Dec_ndr_long(); - int namesi = src.Index; - src.Advance(16 * namess); - if (Names == null) - { - if (namess < 0 || namess > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Names = new LsarTranslatedName[namess]; - } - src = src.Derive(namesi); - for (int i = 0; i < namess; i++) - { - if (Names[i] == null) - { - Names[i] = new LsarTranslatedName(); - } - Names[i].Decode(src); - } - } - } - } - - public class LsarClose : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x00); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public LsarClose(Rpc.PolicyHandle handle) - { - this.Handle = handle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Handle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class LsarQueryInformationPolicy : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x07); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public short Level; - - public NdrObject Info; - - public LsarQueryInformationPolicy(Rpc.PolicyHandle handle, short level, NdrObject - info) - { - this.Handle = handle; - this.Level = level; - this.Info = info; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - dst.Enc_ndr_short(Level); - } - - /// - public override void Decode_out(NdrBuffer src) - { - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - src.Dec_ndr_short(); - Info.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - - public class LsarLookupSids : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x0f); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public LsarSidArray Sids; - - public LsarRefDomainList Domains; - - public LsarTransNameArray Names; - - public short Level; - - public int Count; - - public LsarLookupSids(Rpc.PolicyHandle handle, LsarSidArray sids, LsarRefDomainList - domains, LsarTransNameArray names, short level, int count) - { - this.Handle = handle; - this.Sids = sids; - this.Domains = domains; - this.Names = names; - this.Level = level; - this.Count = count; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - Sids.Encode(dst); - Names.Encode(dst); - dst.Enc_ndr_short(Level); - dst.Enc_ndr_long(Count); - } - - /// - public override void Decode_out(NdrBuffer src) - { - int domainsp = src.Dec_ndr_long(); - if (domainsp != 0) - { - if (Domains == null) - { - Domains = new LsarRefDomainList(); - } - Domains.Decode(src); - } - Names.Decode(src); - Count = src.Dec_ndr_long(); - Retval = src.Dec_ndr_long(); - } - } - - public class LsarOpenPolicy2 : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x2c); - } - - public int Retval; - - public string SystemName; - - public LsarObjectAttributes ObjectAttributes; - - public int DesiredAccess; - - public Rpc.PolicyHandle PolicyHandle; - - public LsarOpenPolicy2(string systemName, LsarObjectAttributes objectAttributes - , int desiredAccess, Rpc.PolicyHandle policyHandle) - { - this.SystemName = systemName; - this.ObjectAttributes = objectAttributes; - this.DesiredAccess = desiredAccess; - this.PolicyHandle = policyHandle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(SystemName, 1); - if (SystemName != null) - { - dst.Enc_ndr_string(SystemName); - } - ObjectAttributes.Encode(dst); - dst.Enc_ndr_long(DesiredAccess); - } - - /// - public override void Decode_out(NdrBuffer src) - { - PolicyHandle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class LsarQueryInformationPolicy2 : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x2e); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public short Level; - - public NdrObject Info; - - public LsarQueryInformationPolicy2(Rpc.PolicyHandle handle, short level, NdrObject - info) - { - this.Handle = handle; - this.Level = level; - this.Info = info; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - dst.Enc_ndr_short(Level); - } - - /// - public override void Decode_out(NdrBuffer src) - { - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - src.Dec_ndr_short(); - Info.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs deleted file mode 100644 index 6a9d4302a7..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcDfsRootEnum.cs +++ /dev/null @@ -1,43 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx - { - public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0)) - { - Info.Level = Level; - Info.E = new Netdfs.DfsEnumArray200(); - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - - public virtual IFileEntry[] GetEntries() - { - Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E; - SmbShareInfo[] entries = new SmbShareInfo[a200.Count]; - for (int i = 0; i < a200.Count; i++) - { - entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null); - } - return entries; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs deleted file mode 100644 index d9c0afb344..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcEnumerateAliasesInDomain.cs +++ /dev/null @@ -1,29 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain - { - public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags - , Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0) - { - this.Sam = sam; - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs deleted file mode 100644 index 77b2ee3751..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcGetMembersInAlias.cs +++ /dev/null @@ -1,29 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias - { - public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids - ) : base(aliasHandle, sids) - { - this.Sids = sids; - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs deleted file mode 100644 index 0aaf310267..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLookupSids.cs +++ /dev/null @@ -1,34 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcLookupSids : Lsarpc.LsarLookupSids - { - internal Sid[] sids; - - public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle - , new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray - (), 1, sids.Length) - { - this.sids = sids; - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs deleted file mode 100644 index 9d2c2a0f40..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcLsarOpenPolicy2.cs +++ /dev/null @@ -1,35 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2 - { - public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle - ) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle) - { - ObjectAttributes.Length = 24; - Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo(); - qos.Length = 12; - qos.ImpersonationLevel = 2; - qos.ContextMode = 1; - qos.EffectiveOnly = 0; - ObjectAttributes.SecurityQualityOfService = qos; - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs deleted file mode 100644 index 820d81ab24..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcQueryInformationPolicy.cs +++ /dev/null @@ -1,30 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy - { - public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject - info) : base(policyHandle, level, info) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs deleted file mode 100644 index 80c45257c2..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect2.cs +++ /dev/null @@ -1,28 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcSamrConnect2 : Samr.SamrConnect2 - { - public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle - ) : base(server, access, policyHandle) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs deleted file mode 100644 index 0f2603e9ce..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrConnect4.cs +++ /dev/null @@ -1,28 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcSamrConnect4 : Samr.SamrConnect4 - { - public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle - ) : base(server, 2, access, policyHandle) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs deleted file mode 100644 index e0b9b68d39..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenAlias.cs +++ /dev/null @@ -1,28 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias - { - public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle - aliasHandle) : base(handle, access, rid, aliasHandle) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs deleted file mode 100644 index 2ac6bceed0..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcSamrOpenDomain.cs +++ /dev/null @@ -1,28 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain - { - public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle - domainHandle) : base(handle, access, sid, domainHandle) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs deleted file mode 100644 index 7c7b64abff..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareEnum.cs +++ /dev/null @@ -1,55 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcShareEnum : Srvsvc.ShareEnumAll - { - internal class MsrpcShareInfo1 : SmbShareInfo - { - internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1) - { - this._enclosing = enclosing; - NetName = info1.Netname; - Type = info1.Type; - Remark = info1.Remark; - } - - private readonly MsrpcShareEnum _enclosing; - } - - public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1 - (), -1, 0, 0) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - - public virtual IFileEntry[] GetEntries() - { - Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info; - MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr - .Count]; - for (int i = 0; i < ctr.Count; i++) - { - entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]); - } - return entries; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs deleted file mode 100644 index 802ed61a3a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/MsrpcShareGetInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo - { - public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename - , 502, new Srvsvc.ShareInfo502()) - { - Ptype = 0; - Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; - } - - /// - public virtual Ace[] GetSecurity() - { - Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info; - if (info502.SecurityDescriptor != null) - { - SecurityDescriptor sd; - sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize); - return sd.Aces; - } - return null; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs deleted file mode 100644 index a338b28858..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs +++ /dev/null @@ -1,616 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class Netdfs - { - public static string GetSyntax() - { - return "4fc742e0-4a10-11cf-8273-00aa004ae673:3.0"; - } - - public const int DfsVolumeFlavorStandalone = unchecked(0x100); - - public const int DfsVolumeFlavorAdBlob = unchecked(0x200); - - public const int DfsStorageStateOffline = unchecked(0x0001); - - public const int DfsStorageStateOnline = unchecked(0x0002); - - public const int DfsStorageStateActive = unchecked(0x0004); - - public class DfsInfo1 : NdrObject - { - public string EntryPath; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(EntryPath, 1); - if (EntryPath != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(EntryPath); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int entryPathp = src.Dec_ndr_long(); - if (entryPathp != 0) - { - src = src.Deferred; - EntryPath = src.Dec_ndr_string(); - } - } - } - - public class DfsEnumArray1 : NdrObject - { - public int Count; - - public DfsInfo1[] S; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(S, 1); - if (S != null) - { - dst = dst.Deferred; - int ss = Count; - dst.Enc_ndr_long(ss); - int si = dst.Index; - dst.Advance(4 * ss); - dst = dst.Derive(si); - for (int i = 0; i < ss; i++) - { - S[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int sp = src.Dec_ndr_long(); - if (sp != 0) - { - src = src.Deferred; - int ss = src.Dec_ndr_long(); - int si = src.Index; - src.Advance(4 * ss); - if (S == null) - { - if (ss < 0 || ss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - S = new DfsInfo1[ss]; - } - src = src.Derive(si); - for (int i = 0; i < ss; i++) - { - if (S[i] == null) - { - S[i] = new DfsInfo1(); - } - S[i].Decode(src); - } - } - } - } - - public class DfsStorageInfo : NdrObject - { - public int State; - - public string ServerName; - - public string ShareName; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(State); - dst.Enc_ndr_referent(ServerName, 1); - dst.Enc_ndr_referent(ShareName, 1); - if (ServerName != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(ServerName); - } - if (ShareName != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(ShareName); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - State = src.Dec_ndr_long(); - int serverNamep = src.Dec_ndr_long(); - int shareNamep = src.Dec_ndr_long(); - if (serverNamep != 0) - { - src = src.Deferred; - ServerName = src.Dec_ndr_string(); - } - if (shareNamep != 0) - { - src = src.Deferred; - ShareName = src.Dec_ndr_string(); - } - } - } - - public class DfsInfo3 : NdrObject - { - public string Path; - - public string Comment; - - public int State; - - public int NumStores; - - public DfsStorageInfo[] Stores; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(Path, 1); - dst.Enc_ndr_referent(Comment, 1); - dst.Enc_ndr_long(State); - dst.Enc_ndr_long(NumStores); - dst.Enc_ndr_referent(Stores, 1); - if (Path != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Path); - } - if (Comment != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Comment); - } - if (Stores != null) - { - dst = dst.Deferred; - int storess = NumStores; - dst.Enc_ndr_long(storess); - int storesi = dst.Index; - dst.Advance(12 * storess); - dst = dst.Derive(storesi); - for (int i = 0; i < storess; i++) - { - Stores[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int pathp = src.Dec_ndr_long(); - int commentp = src.Dec_ndr_long(); - State = src.Dec_ndr_long(); - NumStores = src.Dec_ndr_long(); - int storesp = src.Dec_ndr_long(); - if (pathp != 0) - { - src = src.Deferred; - Path = src.Dec_ndr_string(); - } - if (commentp != 0) - { - src = src.Deferred; - Comment = src.Dec_ndr_string(); - } - if (storesp != 0) - { - src = src.Deferred; - int storess = src.Dec_ndr_long(); - int storesi = src.Index; - src.Advance(12 * storess); - if (Stores == null) - { - if (storess < 0 || storess > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Stores = new DfsStorageInfo[storess]; - } - src = src.Derive(storesi); - for (int i = 0; i < storess; i++) - { - if (Stores[i] == null) - { - Stores[i] = new DfsStorageInfo(); - } - Stores[i].Decode(src); - } - } - } - } - - public class DfsEnumArray3 : NdrObject - { - public int Count; - - public DfsInfo3[] S; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(S, 1); - if (S != null) - { - dst = dst.Deferred; - int ss = Count; - dst.Enc_ndr_long(ss); - int si = dst.Index; - dst.Advance(20 * ss); - dst = dst.Derive(si); - for (int i = 0; i < ss; i++) - { - S[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int sp = src.Dec_ndr_long(); - if (sp != 0) - { - src = src.Deferred; - int ss = src.Dec_ndr_long(); - int si = src.Index; - src.Advance(20 * ss); - if (S == null) - { - if (ss < 0 || ss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - S = new DfsInfo3[ss]; - } - src = src.Derive(si); - for (int i = 0; i < ss; i++) - { - if (S[i] == null) - { - S[i] = new DfsInfo3(); - } - S[i].Decode(src); - } - } - } - } - - public class DfsInfo200 : NdrObject - { - public string DfsName; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(DfsName, 1); - if (DfsName != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(DfsName); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int dfsNamep = src.Dec_ndr_long(); - if (dfsNamep != 0) - { - src = src.Deferred; - DfsName = src.Dec_ndr_string(); - } - } - } - - public class DfsEnumArray200 : NdrObject - { - public int Count; - - public DfsInfo200[] S; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(S, 1); - if (S != null) - { - dst = dst.Deferred; - int ss = Count; - dst.Enc_ndr_long(ss); - int si = dst.Index; - dst.Advance(4 * ss); - dst = dst.Derive(si); - for (int i = 0; i < ss; i++) - { - S[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int sp = src.Dec_ndr_long(); - if (sp != 0) - { - src = src.Deferred; - int ss = src.Dec_ndr_long(); - int si = src.Index; - src.Advance(4 * ss); - if (S == null) - { - if (ss < 0 || ss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - S = new DfsInfo200[ss]; - } - src = src.Derive(si); - for (int i = 0; i < ss; i++) - { - if (S[i] == null) - { - S[i] = new DfsInfo200(); - } - S[i].Decode(src); - } - } - } - } - - public class DfsInfo300 : NdrObject - { - public int Flags; - - public string DfsName; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Flags); - dst.Enc_ndr_referent(DfsName, 1); - if (DfsName != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(DfsName); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Flags = src.Dec_ndr_long(); - int dfsNamep = src.Dec_ndr_long(); - if (dfsNamep != 0) - { - src = src.Deferred; - DfsName = src.Dec_ndr_string(); - } - } - } - - public class DfsEnumArray300 : NdrObject - { - public int Count; - - public DfsInfo300[] S; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(S, 1); - if (S != null) - { - dst = dst.Deferred; - int ss = Count; - dst.Enc_ndr_long(ss); - int si = dst.Index; - dst.Advance(8 * ss); - dst = dst.Derive(si); - for (int i = 0; i < ss; i++) - { - S[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int sp = src.Dec_ndr_long(); - if (sp != 0) - { - src = src.Deferred; - int ss = src.Dec_ndr_long(); - int si = src.Index; - src.Advance(8 * ss); - if (S == null) - { - if (ss < 0 || ss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - S = new DfsInfo300[ss]; - } - src = src.Derive(si); - for (int i = 0; i < ss; i++) - { - if (S[i] == null) - { - S[i] = new DfsInfo300(); - } - S[i].Decode(src); - } - } - } - } - - public class DfsEnumStruct : NdrObject - { - public int Level; - - public NdrObject E; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Level); - int descr = Level; - dst.Enc_ndr_long(descr); - dst.Enc_ndr_referent(E, 1); - if (E != null) - { - dst = dst.Deferred; - E.Encode(dst); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Level = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int ep = src.Dec_ndr_long(); - if (ep != 0) - { - if (E == null) - { - E = new DfsEnumArray1(); - } - src = src.Deferred; - E.Decode(src); - } - } - } - - public class NetrDfsEnumEx : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x15); - } - - public int Retval; - - public string DfsName; - - public int Level; - - public int Prefmaxlen; - - public DfsEnumStruct Info; - - public NdrLong Totalentries; - - public NetrDfsEnumEx(string dfsName, int level, int prefmaxlen, DfsEnumStruct - info, NdrLong totalentries) - { - this.DfsName = dfsName; - this.Level = level; - this.Prefmaxlen = prefmaxlen; - this.Info = info; - this.Totalentries = totalentries; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_string(DfsName); - dst.Enc_ndr_long(Level); - dst.Enc_ndr_long(Prefmaxlen); - dst.Enc_ndr_referent(Info, 1); - if (Info != null) - { - Info.Encode(dst); - } - dst.Enc_ndr_referent(Totalentries, 1); - if (Totalentries != null) - { - Totalentries.Encode(dst); - } - } - - /// - public override void Decode_out(NdrBuffer src) - { - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - if (Info == null) - { - Info = new DfsEnumStruct(); - } - Info.Decode(src); - } - int totalentriesp = src.Dec_ndr_long(); - if (totalentriesp != 0) - { - Totalentries.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs deleted file mode 100644 index bdc71695ed..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs +++ /dev/null @@ -1,579 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class Samr - { - public static string GetSyntax() - { - return "12345778-1234-abcd-ef00-0123456789ac:1.0"; - } - - public const int AcbDisabled = 1; - - public const int AcbHomdirreq = 2; - - public const int AcbPwnotreq = 4; - - public const int AcbTempdup = 8; - - public const int AcbNormal = 16; - - public const int AcbMns = 32; - - public const int AcbDomtrust = 64; - - public const int AcbWstrust = 128; - - public const int AcbSvrtrust = 256; - - public const int AcbPwnoexp = 512; - - public const int AcbAutolock = 1024; - - public const int AcbEncTxtPwdAllowed = 2048; - - public const int AcbSmartcardRequired = 4096; - - public const int AcbTrustedForDelegation = 8192; - - public const int AcbNotDelegated = 16384; - - public const int AcbUseDesKeyOnly = 32768; - - public const int AcbDontRequirePreauth = 65536; - - public class SamrCloseHandle : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x01); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public SamrCloseHandle(Rpc.PolicyHandle handle) - { - this.Handle = handle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Retval = src.Dec_ndr_long(); - } - } - - public class SamrConnect2 : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x39); - } - - public int Retval; - - public string SystemName; - - public int AccessMask; - - public Rpc.PolicyHandle Handle; - - public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle - ) - { - this.SystemName = systemName; - this.AccessMask = accessMask; - this.Handle = handle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(SystemName, 1); - if (SystemName != null) - { - dst.Enc_ndr_string(SystemName); - } - dst.Enc_ndr_long(AccessMask); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Handle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class SamrConnect4 : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x3e); - } - - public int Retval; - - public string SystemName; - - public int Unknown; - - public int AccessMask; - - public Rpc.PolicyHandle Handle; - - public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle - handle) - { - this.SystemName = systemName; - this.Unknown = unknown; - this.AccessMask = accessMask; - this.Handle = handle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(SystemName, 1); - if (SystemName != null) - { - dst.Enc_ndr_string(SystemName); - } - dst.Enc_ndr_long(Unknown); - dst.Enc_ndr_long(AccessMask); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Handle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class SamrOpenDomain : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x07); - } - - public int Retval; - - public Rpc.PolicyHandle Handle; - - public int AccessMask; - - public Rpc.SidT Sid; - - public Rpc.PolicyHandle DomainHandle; - - public SamrOpenDomain(Rpc.PolicyHandle handle, int accessMask, Rpc.SidT sid, Rpc.PolicyHandle - domainHandle) - { - this.Handle = handle; - this.AccessMask = accessMask; - this.Sid = sid; - this.DomainHandle = domainHandle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - Handle.Encode(dst); - dst.Enc_ndr_long(AccessMask); - Sid.Encode(dst); - } - - /// - public override void Decode_out(NdrBuffer src) - { - DomainHandle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class SamrSamEntry : NdrObject - { - public int Idx; - - public Rpc.Unicode_string Name; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Idx); - dst.Enc_ndr_short(Name.Length); - dst.Enc_ndr_short(Name.MaximumLength); - dst.Enc_ndr_referent(Name.Buffer, 1); - if (Name.Buffer != null) - { - dst = dst.Deferred; - int nameBufferl = Name.Length / 2; - int nameBuffers = Name.MaximumLength / 2; - dst.Enc_ndr_long(nameBuffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(nameBufferl); - int nameBufferi = dst.Index; - dst.Advance(2 * nameBufferl); - dst = dst.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - dst.Enc_ndr_short(Name.Buffer[i]); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Idx = src.Dec_ndr_long(); - src.Align(4); - if (Name == null) - { - Name = new Rpc.Unicode_string(); - } - Name.Length = (short)src.Dec_ndr_short(); - Name.MaximumLength = (short)src.Dec_ndr_short(); - int nameBufferp = src.Dec_ndr_long(); - if (nameBufferp != 0) - { - src = src.Deferred; - int nameBuffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int nameBufferl = src.Dec_ndr_long(); - int nameBufferi = src.Index; - src.Advance(2 * nameBufferl); - if (Name.Buffer == null) - { - if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Name.Buffer = new short[nameBuffers]; - } - src = src.Derive(nameBufferi); - for (int i = 0; i < nameBufferl; i++) - { - Name.Buffer[i] = (short)src.Dec_ndr_short(); - } - } - } - } - - public class SamrSamArray : NdrObject - { - public int Count; - - public SamrSamEntry[] Entries; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Entries, 1); - if (Entries != null) - { - dst = dst.Deferred; - int entriess = Count; - dst.Enc_ndr_long(entriess); - int entriesi = dst.Index; - dst.Advance(12 * entriess); - dst = dst.Derive(entriesi); - for (int i = 0; i < entriess; i++) - { - Entries[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int entriesp = src.Dec_ndr_long(); - if (entriesp != 0) - { - src = src.Deferred; - int entriess = src.Dec_ndr_long(); - int entriesi = src.Index; - src.Advance(12 * entriess); - if (Entries == null) - { - if (entriess < 0 || entriess > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Entries = new SamrSamEntry[entriess]; - } - src = src.Derive(entriesi); - for (int i = 0; i < entriess; i++) - { - if (Entries[i] == null) - { - Entries[i] = new SamrSamEntry(); - } - Entries[i].Decode(src); - } - } - } - } - - public class SamrEnumerateAliasesInDomain : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x0f); - } - - public int Retval; - - public Rpc.PolicyHandle DomainHandle; - - public int ResumeHandle; - - public int AcctFlags; - - public SamrSamArray Sam; - - public int NumEntries; - - public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, int resumeHandle - , int acctFlags, SamrSamArray sam, int numEntries) - { - this.DomainHandle = domainHandle; - this.ResumeHandle = resumeHandle; - this.AcctFlags = acctFlags; - this.Sam = sam; - this.NumEntries = numEntries; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - DomainHandle.Encode(dst); - dst.Enc_ndr_long(ResumeHandle); - dst.Enc_ndr_long(AcctFlags); - } - - /// - public override void Decode_out(NdrBuffer src) - { - ResumeHandle = src.Dec_ndr_long(); - int samp = src.Dec_ndr_long(); - if (samp != 0) - { - if (Sam == null) - { - Sam = new SamrSamArray(); - } - Sam.Decode(src); - } - NumEntries = src.Dec_ndr_long(); - Retval = src.Dec_ndr_long(); - } - } - - public class SamrOpenAlias : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x1b); - } - - public int Retval; - - public Rpc.PolicyHandle DomainHandle; - - public int AccessMask; - - public int Rid; - - public Rpc.PolicyHandle AliasHandle; - - public SamrOpenAlias(Rpc.PolicyHandle domainHandle, int accessMask, int rid, Rpc.PolicyHandle - aliasHandle) - { - this.DomainHandle = domainHandle; - this.AccessMask = accessMask; - this.Rid = rid; - this.AliasHandle = aliasHandle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - DomainHandle.Encode(dst); - dst.Enc_ndr_long(AccessMask); - dst.Enc_ndr_long(Rid); - } - - /// - public override void Decode_out(NdrBuffer src) - { - AliasHandle.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public class SamrGetMembersInAlias : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x21); - } - - public int Retval; - - public Rpc.PolicyHandle AliasHandle; - - public Lsarpc.LsarSidArray Sids; - - public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray - sids) - { - this.AliasHandle = aliasHandle; - this.Sids = sids; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - AliasHandle.Encode(dst); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Sids.Decode(src); - Retval = src.Dec_ndr_long(); - } - } - - public const int SeGroupMandatory = 1; - - public const int SeGroupEnabledByDefault = 2; - - public const int SeGroupEnabled = 4; - - public const int SeGroupOwner = 8; - - public const int SeGroupUseForDenyOnly = 16; - - public const int SeGroupResource = 536870912; - - public const int SeGroupLogonId = -1073741824; - - public class SamrRidWithAttribute : NdrObject - { - public int Rid; - - public int Attributes; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Rid); - dst.Enc_ndr_long(Attributes); - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Rid = src.Dec_ndr_long(); - Attributes = src.Dec_ndr_long(); - } - } - - public class SamrRidWithAttributeArray : NdrObject - { - public int Count; - - public SamrRidWithAttribute[] Rids; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Rids, 1); - if (Rids != null) - { - dst = dst.Deferred; - int ridss = Count; - dst.Enc_ndr_long(ridss); - int ridsi = dst.Index; - dst.Advance(8 * ridss); - dst = dst.Derive(ridsi); - for (int i = 0; i < ridss; i++) - { - Rids[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int ridsp = src.Dec_ndr_long(); - if (ridsp != 0) - { - src = src.Deferred; - int ridss = src.Dec_ndr_long(); - int ridsi = src.Index; - src.Advance(8 * ridss); - if (Rids == null) - { - if (ridss < 0 || ridss > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Rids = new SamrRidWithAttribute[ridss]; - } - src = src.Derive(ridsi); - for (int i = 0; i < ridss; i++) - { - if (Rids[i] == null) - { - Rids[i] = new SamrRidWithAttribute(); - } - Rids[i].Decode(src); - } - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs deleted file mode 100644 index d4ebdacc49..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrAliasHandle.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class SamrAliasHandle : Rpc.PolicyHandle - { - /// - public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access - , int rid) - { - MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - } - - /// - public virtual void Close() - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs deleted file mode 100644 index d44c798861..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrDomainHandle.cs +++ /dev/null @@ -1,41 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Smb; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class SamrDomainHandle : Rpc.PolicyHandle - { - /// - public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access - , Rpc.SidT sid) - { - MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this - ); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - } - - /// - public virtual void Close() - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs deleted file mode 100644 index 0cd3f9369c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/SamrPolicyHandle.cs +++ /dev/null @@ -1,49 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Msrpc -{ - public class SamrPolicyHandle : Rpc.PolicyHandle - { - /// - public SamrPolicyHandle(DcerpcHandle handle, string server, int access) - { - if (server == null) - { - server = "\\\\"; - } - MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this); - try - { - handle.Sendrecv(rpc); - } - catch (DcerpcException de) - { - if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError) - { - throw; - } - MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this); - handle.Sendrecv(rpc2); - } - } - - /// - public virtual void Close() - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs deleted file mode 100644 index f33f483278..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs +++ /dev/null @@ -1,734 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc.Msrpc -{ - public class Srvsvc - { - public static string GetSyntax() - { - return "4b324fc8-1670-01d3-1278-5a47bf6ee188:3.0"; - } - - public class ShareInfo0 : NdrObject - { - public string Netname; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(Netname, 1); - if (Netname != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Netname); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int netnamep = src.Dec_ndr_long(); - if (netnamep != 0) - { - src = src.Deferred; - Netname = src.Dec_ndr_string(); - } - } - } - - public class ShareInfoCtr0 : NdrObject - { - public int Count; - - public ShareInfo0[] Array; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Array, 1); - if (Array != null) - { - dst = dst.Deferred; - int arrays = Count; - dst.Enc_ndr_long(arrays); - int arrayi = dst.Index; - dst.Advance(4 * arrays); - dst = dst.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - Array[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int arrayp = src.Dec_ndr_long(); - if (arrayp != 0) - { - src = src.Deferred; - int arrays = src.Dec_ndr_long(); - int arrayi = src.Index; - src.Advance(4 * arrays); - if (Array == null) - { - if (arrays < 0 || arrays > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Array = new ShareInfo0[arrays]; - } - src = src.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - if (Array[i] == null) - { - Array[i] = new ShareInfo0(); - } - Array[i].Decode(src); - } - } - } - } - - public class ShareInfo1 : NdrObject - { - public string Netname; - - public int Type; - - public string Remark; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(Netname, 1); - dst.Enc_ndr_long(Type); - dst.Enc_ndr_referent(Remark, 1); - if (Netname != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Netname); - } - if (Remark != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Remark); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int netnamep = src.Dec_ndr_long(); - Type = src.Dec_ndr_long(); - int remarkp = src.Dec_ndr_long(); - if (netnamep != 0) - { - src = src.Deferred; - Netname = src.Dec_ndr_string(); - } - if (remarkp != 0) - { - src = src.Deferred; - Remark = src.Dec_ndr_string(); - } - } - } - - public class ShareInfoCtr1 : NdrObject - { - public int Count; - - public ShareInfo1[] Array; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Array, 1); - if (Array != null) - { - dst = dst.Deferred; - int arrays = Count; - dst.Enc_ndr_long(arrays); - int arrayi = dst.Index; - dst.Advance(12 * arrays); - dst = dst.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - Array[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int arrayp = src.Dec_ndr_long(); - if (arrayp != 0) - { - src = src.Deferred; - int arrays = src.Dec_ndr_long(); - int arrayi = src.Index; - src.Advance(12 * arrays); - if (Array == null) - { - if (arrays < 0 || arrays > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Array = new ShareInfo1[arrays]; - } - src = src.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - if (Array[i] == null) - { - Array[i] = new ShareInfo1(); - } - Array[i].Decode(src); - } - } - } - } - - public class ShareInfo502 : NdrObject - { - public string Netname; - - public int Type; - - public string Remark; - - public int Permissions; - - public int MaxUses; - - public int CurrentUses; - - public string Path; - - public string Password; - - public int SdSize; - - public byte[] SecurityDescriptor; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_referent(Netname, 1); - dst.Enc_ndr_long(Type); - dst.Enc_ndr_referent(Remark, 1); - dst.Enc_ndr_long(Permissions); - dst.Enc_ndr_long(MaxUses); - dst.Enc_ndr_long(CurrentUses); - dst.Enc_ndr_referent(Path, 1); - dst.Enc_ndr_referent(Password, 1); - dst.Enc_ndr_long(SdSize); - dst.Enc_ndr_referent(SecurityDescriptor, 1); - if (Netname != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Netname); - } - if (Remark != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Remark); - } - if (Path != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Path); - } - if (Password != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Password); - } - if (SecurityDescriptor != null) - { - dst = dst.Deferred; - int securityDescriptors = SdSize; - dst.Enc_ndr_long(securityDescriptors); - int securityDescriptori = dst.Index; - dst.Advance(1 * securityDescriptors); - dst = dst.Derive(securityDescriptori); - for (int i = 0; i < securityDescriptors; i++) - { - dst.Enc_ndr_small(SecurityDescriptor[i]); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int netnamep = src.Dec_ndr_long(); - Type = src.Dec_ndr_long(); - int remarkp = src.Dec_ndr_long(); - Permissions = src.Dec_ndr_long(); - MaxUses = src.Dec_ndr_long(); - CurrentUses = src.Dec_ndr_long(); - int pathp = src.Dec_ndr_long(); - int passwordp = src.Dec_ndr_long(); - SdSize = src.Dec_ndr_long(); - int securityDescriptorp = src.Dec_ndr_long(); - if (netnamep != 0) - { - src = src.Deferred; - Netname = src.Dec_ndr_string(); - } - if (remarkp != 0) - { - src = src.Deferred; - Remark = src.Dec_ndr_string(); - } - if (pathp != 0) - { - src = src.Deferred; - Path = src.Dec_ndr_string(); - } - if (passwordp != 0) - { - src = src.Deferred; - Password = src.Dec_ndr_string(); - } - if (securityDescriptorp != 0) - { - src = src.Deferred; - int securityDescriptors = src.Dec_ndr_long(); - int securityDescriptori = src.Index; - src.Advance(1 * securityDescriptors); - if (SecurityDescriptor == null) - { - if (securityDescriptors < 0 || securityDescriptors > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - SecurityDescriptor = new byte[securityDescriptors]; - } - src = src.Derive(securityDescriptori); - for (int i = 0; i < securityDescriptors; i++) - { - SecurityDescriptor[i] = unchecked((byte)src.Dec_ndr_small()); - } - } - } - } - - public class ShareInfoCtr502 : NdrObject - { - public int Count; - - public ShareInfo502[] Array; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Count); - dst.Enc_ndr_referent(Array, 1); - if (Array != null) - { - dst = dst.Deferred; - int arrays = Count; - dst.Enc_ndr_long(arrays); - int arrayi = dst.Index; - dst.Advance(40 * arrays); - dst = dst.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - Array[i].Encode(dst); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Count = src.Dec_ndr_long(); - int arrayp = src.Dec_ndr_long(); - if (arrayp != 0) - { - src = src.Deferred; - int arrays = src.Dec_ndr_long(); - int arrayi = src.Index; - src.Advance(40 * arrays); - if (Array == null) - { - if (arrays < 0 || arrays > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Array = new ShareInfo502[arrays]; - } - src = src.Derive(arrayi); - for (int i = 0; i < arrays; i++) - { - if (Array[i] == null) - { - Array[i] = new ShareInfo502(); - } - Array[i].Decode(src); - } - } - } - } - - public class ShareEnumAll : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x0f); - } - - public int Retval; - - public string Servername; - - public int Level; - - public NdrObject Info; - - public int Prefmaxlen; - - public int Totalentries; - - public int ResumeHandle; - - public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen, - int totalentries, int resumeHandle) - { - this.Servername = servername; - this.Level = level; - this.Info = info; - this.Prefmaxlen = prefmaxlen; - this.Totalentries = totalentries; - this.ResumeHandle = resumeHandle; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(Servername, 1); - if (Servername != null) - { - dst.Enc_ndr_string(Servername); - } - dst.Enc_ndr_long(Level); - int descr = Level; - dst.Enc_ndr_long(descr); - dst.Enc_ndr_referent(Info, 1); - if (Info != null) - { - dst = dst.Deferred; - Info.Encode(dst); - } - dst.Enc_ndr_long(Prefmaxlen); - dst.Enc_ndr_long(ResumeHandle); - } - - /// - public override void Decode_out(NdrBuffer src) - { - Level = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - if (Info == null) - { - Info = new ShareInfoCtr0(); - } - src = src.Deferred; - Info.Decode(src); - } - Totalentries = src.Dec_ndr_long(); - ResumeHandle = src.Dec_ndr_long(); - Retval = src.Dec_ndr_long(); - } - } - - public class ShareGetInfo : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x10); - } - - public int Retval; - - public string Servername; - - public string Sharename; - - public int Level; - - public NdrObject Info; - - public ShareGetInfo(string servername, string sharename, int level, NdrObject info - ) - { - this.Servername = servername; - this.Sharename = sharename; - this.Level = level; - this.Info = info; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(Servername, 1); - if (Servername != null) - { - dst.Enc_ndr_string(Servername); - } - dst.Enc_ndr_string(Sharename); - dst.Enc_ndr_long(Level); - } - - /// - public override void Decode_out(NdrBuffer src) - { - src.Dec_ndr_long(); - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - if (Info == null) - { - Info = new ShareInfo0(); - } - src = src.Deferred; - Info.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - - public class ServerInfo100 : NdrObject - { - public int PlatformId; - - public string Name; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(PlatformId); - dst.Enc_ndr_referent(Name, 1); - if (Name != null) - { - dst = dst.Deferred; - dst.Enc_ndr_string(Name); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - PlatformId = src.Dec_ndr_long(); - int namep = src.Dec_ndr_long(); - if (namep != 0) - { - src = src.Deferred; - Name = src.Dec_ndr_string(); - } - } - } - - public class ServerGetInfo : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x15); - } - - public int Retval; - - public string Servername; - - public int Level; - - public NdrObject Info; - - public ServerGetInfo(string servername, int level, NdrObject info) - { - this.Servername = servername; - this.Level = level; - this.Info = info; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(Servername, 1); - if (Servername != null) - { - dst.Enc_ndr_string(Servername); - } - dst.Enc_ndr_long(Level); - } - - /// - public override void Decode_out(NdrBuffer src) - { - src.Dec_ndr_long(); - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - if (Info == null) - { - Info = new ServerInfo100(); - } - src = src.Deferred; - Info.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - - public class TimeOfDayInfo : NdrObject - { - public int Elapsedt; - - public int Msecs; - - public int Hours; - - public int Mins; - - public int Secs; - - public int Hunds; - - public int Timezone; - - public int Tinterval; - - public int Day; - - public int Month; - - public int Year; - - public int Weekday; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Elapsedt); - dst.Enc_ndr_long(Msecs); - dst.Enc_ndr_long(Hours); - dst.Enc_ndr_long(Mins); - dst.Enc_ndr_long(Secs); - dst.Enc_ndr_long(Hunds); - dst.Enc_ndr_long(Timezone); - dst.Enc_ndr_long(Tinterval); - dst.Enc_ndr_long(Day); - dst.Enc_ndr_long(Month); - dst.Enc_ndr_long(Year); - dst.Enc_ndr_long(Weekday); - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Elapsedt = src.Dec_ndr_long(); - Msecs = src.Dec_ndr_long(); - Hours = src.Dec_ndr_long(); - Mins = src.Dec_ndr_long(); - Secs = src.Dec_ndr_long(); - Hunds = src.Dec_ndr_long(); - Timezone = src.Dec_ndr_long(); - Tinterval = src.Dec_ndr_long(); - Day = src.Dec_ndr_long(); - Month = src.Dec_ndr_long(); - Year = src.Dec_ndr_long(); - Weekday = src.Dec_ndr_long(); - } - } - - public class RemoteTod : DcerpcMessage - { - public override int GetOpnum() - { - return unchecked(0x1c); - } - - public int Retval; - - public string Servername; - - public TimeOfDayInfo Info; - - public RemoteTod(string servername, TimeOfDayInfo info) - { - this.Servername = servername; - this.Info = info; - } - - /// - public override void Encode_in(NdrBuffer dst) - { - dst.Enc_ndr_referent(Servername, 1); - if (Servername != null) - { - dst.Enc_ndr_string(Servername); - } - } - - /// - public override void Decode_out(NdrBuffer src) - { - int infop = src.Dec_ndr_long(); - if (infop != 0) - { - if (Info == null) - { - Info = new TimeOfDayInfo(); - } - Info.Decode(src); - } - Retval = src.Dec_ndr_long(); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs deleted file mode 100644 index 0a47de799e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs +++ /dev/null @@ -1,305 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Dcerpc.Ndr -{ - public class NdrBuffer - { - internal int Referent; - - internal Hashtable Referents; - - internal class Entry - { - internal int Referent; - - internal object Obj; - } - - public byte[] Buf; - - public int Start; - - public int Index; - - public int Length; - - public NdrBuffer Deferred; - - public NdrBuffer(byte[] buf, int start) - { - this.Buf = buf; - this.Start = Index = start; - Length = 0; - Deferred = this; - } - - public virtual NdrBuffer Derive(int idx) - { - NdrBuffer nb = new NdrBuffer(Buf, Start); - nb.Index = idx; - nb.Deferred = Deferred; - return nb; - } - - public virtual void Reset() - { - Index = Start; - Length = 0; - Deferred = this; - } - - public virtual int GetIndex() - { - return Index; - } - - public virtual void SetIndex(int index) - { - this.Index = index; - } - - public virtual int GetCapacity() - { - return Buf.Length - Start; - } - - public virtual int GetTailSpace() - { - return Buf.Length - Index; - } - - public virtual byte[] GetBuffer() - { - return Buf; - } - - public virtual int Align(int boundary, byte value) - { - int n = Align(boundary); - int i = n; - while (i > 0) - { - Buf[Index - i] = value; - i--; - } - return n; - } - - public virtual void WriteOctetArray(byte[] b, int i, int l) - { - Array.Copy(b, i, Buf, Index, l); - Advance(l); - } - - public virtual void ReadOctetArray(byte[] b, int i, int l) - { - Array.Copy(Buf, Index, b, i, l); - Advance(l); - } - - public virtual int GetLength() - { - return Deferred.Length; - } - - public virtual void SetLength(int length) - { - Deferred.Length = length; - } - - public virtual void Advance(int n) - { - Index += n; - if ((Index - Start) > Deferred.Length) - { - Deferred.Length = Index - Start; - } - } - - public virtual int Align(int boundary) - { - int m = boundary - 1; - int i = Index - Start; - int n = ((i + m) & ~m) - i; - Advance(n); - return n; - } - - public virtual void Enc_ndr_small(int s) - { - Buf[Index] = unchecked((byte)(s & unchecked(0xFF))); - Advance(1); - } - - public virtual int Dec_ndr_small() - { - int val = Buf[Index] & unchecked(0xFF); - Advance(1); - return val; - } - - public virtual void Enc_ndr_short(int s) - { - Align(2); - Encdec.Enc_uint16le((short)s, Buf, Index); - Advance(2); - } - - public virtual int Dec_ndr_short() - { - Align(2); - int val = Encdec.Dec_uint16le(Buf, Index); - Advance(2); - return val; - } - - public virtual void Enc_ndr_long(int l) - { - Align(4); - Encdec.Enc_uint32le(l, Buf, Index); - Advance(4); - } - - public virtual int Dec_ndr_long() - { - Align(4); - int val = Encdec.Dec_uint32le(Buf, Index); - Advance(4); - return val; - } - - public virtual void Enc_ndr_hyper(long h) - { - Align(8); - Encdec.Enc_uint64le(h, Buf, Index); - Advance(8); - } - - public virtual long Dec_ndr_hyper() - { - Align(8); - long val = Encdec.Dec_uint64le(Buf, Index); - Advance(8); - return val; - } - - public virtual void Enc_ndr_string(string s) - { - Align(4); - int i = Index; - int len = s.Length; - Encdec.Enc_uint32le(len + 1, Buf, i); - i += 4; - Encdec.Enc_uint32le(0, Buf, i); - i += 4; - Encdec.Enc_uint32le(len + 1, Buf, i); - i += 4; - try - { - Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len - * 2); - } - catch (UnsupportedEncodingException) - { - } - i += len * 2; - Buf[i++] = unchecked((byte)('\0')); - Buf[i++] = unchecked((byte)('\0')); - Advance(i - Index); - } - - /// - public virtual string Dec_ndr_string() - { - Align(4); - int i = Index; - string val = null; - int len = Encdec.Dec_uint32le(Buf, i); - i += 12; - if (len != 0) - { - len--; - int size = len * 2; - try - { - if (size < 0 || size > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE"); - i += size + 2; - } - catch (UnsupportedEncodingException) - { - } - } - Advance(i - Index); - return val; - } - - private int GetDceReferent(object obj) - { - Entry e; - if (Referents == null) - { - Referents = new Hashtable(); - Referent = 1; - } - if ((e = (Entry)Referents.Get(obj)) == null) - { - e = new Entry(); - e.Referent = Referent++; - e.Obj = obj; - Referents.Put(obj, e); - } - return e.Referent; - } - - public virtual void Enc_ndr_referent(object obj, int type) - { - if (obj == null) - { - Enc_ndr_long(0); - return; - } - switch (type) - { - case 1: - case 3: - { - Enc_ndr_long(Runtime.IdentityHashCode(obj)); - return; - } - - case 2: - { - Enc_ndr_long(GetDceReferent(obj)); - return; - } - } - } - - public override string ToString() - { - return "start=" + Start + ",index=" + Index + ",length=" + GetLength(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs deleted file mode 100644 index 7757735f8b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrException.cs +++ /dev/null @@ -1,32 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; - -namespace SharpCifs.Dcerpc.Ndr -{ - - public class NdrException : IOException - { - public static readonly string NoNullRef = "ref pointer cannot be null"; - - public static readonly string InvalidConformance = "invalid array conformance"; - - public NdrException(string msg) : base(msg) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs deleted file mode 100644 index 9e2932337b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrHyper.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Ndr -{ - public class NdrHyper : NdrObject - { - public long Value; - - public NdrHyper(long value) - { - this.Value = value; - } - - /// - public override void Encode(NdrBuffer dst) - { - dst.Enc_ndr_hyper(Value); - } - - /// - public override void Decode(NdrBuffer src) - { - Value = src.Dec_ndr_hyper(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs deleted file mode 100644 index 74d90465e9..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrLong.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Ndr -{ - public class NdrLong : NdrObject - { - public int Value; - - public NdrLong(int value) - { - this.Value = value; - } - - /// - public override void Encode(NdrBuffer dst) - { - dst.Enc_ndr_long(Value); - } - - /// - public override void Decode(NdrBuffer src) - { - Value = src.Dec_ndr_long(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs deleted file mode 100644 index 8951fa2024..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrObject.cs +++ /dev/null @@ -1,27 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Ndr -{ - public abstract class NdrObject - { - /// - public abstract void Encode(NdrBuffer dst); - - /// - public abstract void Decode(NdrBuffer src); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs deleted file mode 100644 index e2ea8c65b4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrShort.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Ndr -{ - public class NdrShort : NdrObject - { - public int Value; - - public NdrShort(int value) - { - this.Value = value & unchecked(0xFF); - } - - /// - public override void Encode(NdrBuffer dst) - { - dst.Enc_ndr_short(Value); - } - - /// - public override void Decode(NdrBuffer src) - { - Value = src.Dec_ndr_short(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs deleted file mode 100644 index 8309dea660..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrSmall.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc.Ndr -{ - public class NdrSmall : NdrObject - { - public int Value; - - public NdrSmall(int value) - { - this.Value = value & unchecked(0xFF); - } - - /// - public override void Encode(NdrBuffer dst) - { - dst.Enc_ndr_small(Value); - } - - /// - public override void Decode(NdrBuffer src) - { - Value = src.Dec_ndr_small(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs deleted file mode 100644 index aa33d35224..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs +++ /dev/null @@ -1,285 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Dcerpc.Ndr; - -namespace SharpCifs.Dcerpc -{ - public class Rpc - { - public class UuidT : NdrObject - { - public int TimeLow; - - public short TimeMid; - - public short TimeHiAndVersion; - - public byte ClockSeqHiAndReserved; - - public byte ClockSeqLow; - - public byte[] Node; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(TimeLow); - dst.Enc_ndr_short(TimeMid); - dst.Enc_ndr_short(TimeHiAndVersion); - dst.Enc_ndr_small(ClockSeqHiAndReserved); - dst.Enc_ndr_small(ClockSeqLow); - int nodes = 6; - int nodei = dst.Index; - dst.Advance(1 * nodes); - dst = dst.Derive(nodei); - for (int i = 0; i < nodes; i++) - { - dst.Enc_ndr_small(Node[i]); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - TimeLow = src.Dec_ndr_long(); - TimeMid = (short)src.Dec_ndr_short(); - TimeHiAndVersion = (short)src.Dec_ndr_short(); - ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small()); - ClockSeqLow = unchecked((byte)src.Dec_ndr_small()); - int nodes = 6; - int nodei = src.Index; - src.Advance(1 * nodes); - if (Node == null) - { - if (nodes < 0 || nodes > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Node = new byte[nodes]; - } - src = src.Derive(nodei); - for (int i = 0; i < nodes; i++) - { - Node[i] = unchecked((byte)src.Dec_ndr_small()); - } - } - } - - public class PolicyHandle : NdrObject - { - public int Type; - - public UuidT Uuid; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_long(Type); - dst.Enc_ndr_long(Uuid.TimeLow); - dst.Enc_ndr_short(Uuid.TimeMid); - dst.Enc_ndr_short(Uuid.TimeHiAndVersion); - dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved); - dst.Enc_ndr_small(Uuid.ClockSeqLow); - int uuidNodes = 6; - int uuidNodei = dst.Index; - dst.Advance(1 * uuidNodes); - dst = dst.Derive(uuidNodei); - for (int i = 0; i < uuidNodes; i++) - { - dst.Enc_ndr_small(Uuid.Node[i]); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Type = src.Dec_ndr_long(); - src.Align(4); - if (Uuid == null) - { - Uuid = new UuidT(); - } - Uuid.TimeLow = src.Dec_ndr_long(); - Uuid.TimeMid = (short)src.Dec_ndr_short(); - Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short(); - Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small()); - Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small()); - int uuidNodes = 6; - int uuidNodei = src.Index; - src.Advance(1 * uuidNodes); - if (Uuid.Node == null) - { - if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Uuid.Node = new byte[uuidNodes]; - } - src = src.Derive(uuidNodei); - for (int i = 0; i < uuidNodes; i++) - { - Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small()); - } - } - } - - public class Unicode_string : NdrObject - { - public short Length; - - public short MaximumLength; - - public short[] Buffer; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - dst.Enc_ndr_short(Length); - dst.Enc_ndr_short(MaximumLength); - dst.Enc_ndr_referent(Buffer, 1); - if (Buffer != null) - { - dst = dst.Deferred; - int bufferl = Length / 2; - int buffers = MaximumLength / 2; - dst.Enc_ndr_long(buffers); - dst.Enc_ndr_long(0); - dst.Enc_ndr_long(bufferl); - int bufferi = dst.Index; - dst.Advance(2 * bufferl); - dst = dst.Derive(bufferi); - for (int i = 0; i < bufferl; i++) - { - dst.Enc_ndr_short(Buffer[i]); - } - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - Length = (short)src.Dec_ndr_short(); - MaximumLength = (short)src.Dec_ndr_short(); - int bufferp = src.Dec_ndr_long(); - if (bufferp != 0) - { - src = src.Deferred; - int buffers = src.Dec_ndr_long(); - src.Dec_ndr_long(); - int bufferl = src.Dec_ndr_long(); - int bufferi = src.Index; - src.Advance(2 * bufferl); - if (Buffer == null) - { - if (buffers < 0 || buffers > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - Buffer = new short[buffers]; - } - src = src.Derive(bufferi); - for (int i = 0; i < bufferl; i++) - { - Buffer[i] = (short)src.Dec_ndr_short(); - } - } - } - } - - public class SidT : NdrObject - { - public byte Revision; - - public byte SubAuthorityCount; - - public byte[] IdentifierAuthority; - - public int[] SubAuthority; - - /// - public override void Encode(NdrBuffer dst) - { - dst.Align(4); - int subAuthoritys = SubAuthorityCount; - dst.Enc_ndr_long(subAuthoritys); - dst.Enc_ndr_small(Revision); - dst.Enc_ndr_small(SubAuthorityCount); - int identifierAuthoritys = 6; - int identifierAuthorityi = dst.Index; - dst.Advance(1 * identifierAuthoritys); - int subAuthorityi = dst.Index; - dst.Advance(4 * subAuthoritys); - dst = dst.Derive(identifierAuthorityi); - for (int i = 0; i < identifierAuthoritys; i++) - { - dst.Enc_ndr_small(IdentifierAuthority[i]); - } - dst = dst.Derive(subAuthorityi); - for (int i1 = 0; i1 < subAuthoritys; i1++) - { - dst.Enc_ndr_long(SubAuthority[i1]); - } - } - - /// - public override void Decode(NdrBuffer src) - { - src.Align(4); - int subAuthoritys = src.Dec_ndr_long(); - Revision = unchecked((byte)src.Dec_ndr_small()); - SubAuthorityCount = unchecked((byte)src.Dec_ndr_small()); - int identifierAuthoritys = 6; - int identifierAuthorityi = src.Index; - src.Advance(1 * identifierAuthoritys); - int subAuthorityi = src.Index; - src.Advance(4 * subAuthoritys); - if (IdentifierAuthority == null) - { - if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - IdentifierAuthority = new byte[identifierAuthoritys]; - } - src = src.Derive(identifierAuthorityi); - for (int i = 0; i < identifierAuthoritys; i++) - { - IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small()); - } - if (SubAuthority == null) - { - if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF)) - { - throw new NdrException(NdrException.InvalidConformance); - } - SubAuthority = new int[subAuthoritys]; - } - src = src.Derive(subAuthorityi); - for (int i1 = 0; i1 < subAuthoritys; i1++) - { - SubAuthority[i1] = src.Dec_ndr_long(); - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs deleted file mode 100644 index bef4be214d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs +++ /dev/null @@ -1,148 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Dcerpc -{ - public class Uuid : Rpc.UuidT - { - public static int Hex_to_bin(char[] arr, int offset, int length) - { - int value = 0; - int ai; - int count; - count = 0; - for (ai = offset; ai < arr.Length && count < length; ai++) - { - value <<= 4; - switch (arr[ai]) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - value += arr[ai] - '0'; - break; - } - - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - { - value += 10 + (arr[ai] - 'A'); - break; - } - - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - { - value += 10 + (arr[ai] - 'a'); - break; - } - - default: - { - throw new ArgumentException(new string(arr, offset, length)); - } - } - count++; - } - return value; - } - - internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4', - '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - public static string Bin_to_hex(int value, int length) - { - char[] arr = new char[length]; - int ai = arr.Length; - while (ai-- > 0) - { - arr[ai] = Hexchars[value & unchecked(0xF)]; - value = (int)(((uint)value) >> 4); - } - return new string(arr); - } - - private static byte B(int i) - { - return unchecked((byte)(i & unchecked(0xFF))); - } - - private static short S(int i) - { - return (short)(i & unchecked(0xFFFF)); - } - - public Uuid(Rpc.UuidT uuid) - { - TimeLow = uuid.TimeLow; - TimeMid = uuid.TimeMid; - TimeHiAndVersion = uuid.TimeHiAndVersion; - ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved; - ClockSeqLow = uuid.ClockSeqLow; - Node = new byte[6]; - Node[0] = uuid.Node[0]; - Node[1] = uuid.Node[1]; - Node[2] = uuid.Node[2]; - Node[3] = uuid.Node[3]; - Node[4] = uuid.Node[4]; - Node[5] = uuid.Node[5]; - } - - public Uuid(string str) - { - char[] arr = str.ToCharArray(); - TimeLow = Hex_to_bin(arr, 0, 8); - TimeMid = S(Hex_to_bin(arr, 9, 4)); - TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4)); - ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2)); - ClockSeqLow = B(Hex_to_bin(arr, 21, 2)); - Node = new byte[6]; - Node[0] = B(Hex_to_bin(arr, 24, 2)); - Node[1] = B(Hex_to_bin(arr, 26, 2)); - Node[2] = B(Hex_to_bin(arr, 28, 2)); - Node[3] = B(Hex_to_bin(arr, 30, 2)); - Node[4] = B(Hex_to_bin(arr, 32, 2)); - Node[5] = B(Hex_to_bin(arr, 34, 2)); - } - - public override string ToString() - { - return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex - (TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex - (ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex - (Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node - [5], 2); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs b/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs deleted file mode 100644 index b0c36898ca..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UnicodeString.cs +++ /dev/null @@ -1,65 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Dcerpc -{ - public class UnicodeString : Rpc.Unicode_string - { - internal bool Zterm; - - public UnicodeString(bool zterm) - { - this.Zterm = zterm; - } - - public UnicodeString(Rpc.Unicode_string rus, bool zterm) - { - Length = rus.Length; - MaximumLength = rus.MaximumLength; - Buffer = rus.Buffer; - this.Zterm = zterm; - } - - public UnicodeString(string str, bool zterm) - { - this.Zterm = zterm; - int len = str.Length; - int zt = zterm ? 1 : 0; - Length = MaximumLength = (short)((len + zt) * 2); - Buffer = new short[len + zt]; - int i; - for (i = 0; i < len; i++) - { - Buffer[i] = (short)str[i]; - } - if (zterm) - { - Buffer[i] = 0; - } - } - - public override string ToString() - { - int len = Length / 2 - (Zterm ? 1 : 0); - char[] ca = new char[len]; - for (int i = 0; i < len; i++) - { - ca[i] = (char)Buffer[i]; - } - return new string(ca, 0, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs deleted file mode 100644 index c94d0a2600..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs +++ /dev/null @@ -1,202 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Smb; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - public class Lmhosts - { - private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts" - ); - - private static readonly Hashtable Tab = new Hashtable(); - - private static long _lastModified = 1L; - - private static int _alt; - - private static LogStream _log = LogStream.GetInstance(); - - /// - /// This is really just for - /// Jcifs.UniAddress - /// . It does - /// not throw an - /// Sharpen.UnknownHostException - /// because this - /// is queried frequently and exceptions would be rather costly to - /// throw on a regular basis here. - /// - public static NbtAddress GetByName(string host) - { - lock (typeof(Lmhosts)) - { - return GetByName(new Name(host, 0x20, null)); - } - } - - internal static NbtAddress GetByName(Name name) - { - lock (typeof(Lmhosts)) - { - NbtAddress result = null; - try - { - if (Filename != null) - { - FilePath f = new FilePath(Filename); - long lm; - if ((lm = f.LastModified()) > _lastModified) - { - _lastModified = lm; - Tab.Clear(); - _alt = 0; - - //path -> fileStream - //Populate(new FileReader(f)); - Populate(new FileReader(new FileStream(f, FileMode.Open))); - } - result = (NbtAddress)Tab[name]; - } - } - catch (FileNotFoundException fnfe) - { - if (_log.Level > 1) - { - _log.WriteLine("lmhosts file: " + Filename); - Runtime.PrintStackTrace(fnfe, _log); - } - } - catch (IOException ioe) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(ioe, _log); - } - } - return result; - } - } - - /// - internal static void Populate(StreamReader r) - { - string line; - BufferedReader br = new BufferedReader((InputStreamReader)r); - while ((line = br.ReadLine()) != null) - { - line = line.ToUpper().Trim(); - if (line.Length == 0) - { - } - else - { - if (line[0] == '#') - { - if (line.StartsWith("#INCLUDE ")) - { - line = Runtime.Substring(line, line.IndexOf('\\')); - string url = "smb:" + line.Replace('\\', '/'); - if (_alt > 0) - { - try - { - Populate(new InputStreamReader(new SmbFileInputStream(url))); - } - catch (IOException ioe) - { - _log.WriteLine("lmhosts URL: " + url); - Runtime.PrintStackTrace(ioe, _log); - continue; - } - _alt--; - while ((line = br.ReadLine()) != null) - { - line = line.ToUpper().Trim(); - if (line.StartsWith("#END_ALTERNATE")) - { - break; - } - } - } - else - { - Populate(new InputStreamReader(new SmbFileInputStream(url))); - } - } - else - { - if (line.StartsWith("#BEGIN_ALTERNATE")) - { - _alt++; - } - else - { - if (line.StartsWith("#END_ALTERNATE") && _alt > 0) - { - _alt--; - throw new IOException("no lmhosts alternate includes loaded"); - } - } - } - } - else - { - if (char.IsDigit(line[0])) - { - char[] data = line.ToCharArray(); - int ip; - int i; - int j; - Name name; - NbtAddress addr; - char c; - c = '.'; - ip = i = 0; - for (; i < data.Length && c == '.'; i++) - { - int b = unchecked(0x00); - for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++) - { - b = b * 10 + c - '0'; - } - ip = (ip << 8) + b; - } - while (i < data.Length && char.IsWhiteSpace(data[i])) - { - i++; - } - j = i; - while (j < data.Length && char.IsWhiteSpace(data[j]) == false) - { - j++; - } - name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null - ); - addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true - , NbtAddress.UnknownMacAddress); - Tab.Put(name, addr); - } - } - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs deleted file mode 100644 index 15ae494bea..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs +++ /dev/null @@ -1,269 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Text; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - public class Name - { - private const int TypeOffset = 31; - - private const int ScopeOffset = 33; - - private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope" - ); - - internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding" - , Runtime.GetProperty("file.encoding")); - - public string name; - - public string Scope; - - public int HexCode; - - internal int SrcHashCode; - - public Name() - { - } - - public Name(string name, int hexCode, string scope) - { - if (name.Length > 15) - { - name = Runtime.Substring(name, 0, 15); - } - this.name = name.ToUpper(); - this.HexCode = hexCode; - this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope; - SrcHashCode = 0; - } - - internal virtual int WriteWireFormat(byte[] dst, int dstIndex) - { - // write 0x20 in first byte - dst[dstIndex] = unchecked(0x20); - // write name - try - { - byte[] tmp = Runtime.GetBytesForString(name, OemEncoding - ); - int i; - for (i = 0; i < tmp.Length; i++) - { - dst[dstIndex + (2 * i + 1)] = unchecked((byte)(((tmp[i] & unchecked(0xF0)) - >> 4) + unchecked(0x41))); - dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F)) - + unchecked(0x41))); - } - for (; i < 15; i++) - { - dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43)); - dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41)); - } - dst[dstIndex + TypeOffset] = unchecked((byte)(((HexCode & unchecked(0xF0) - ) >> 4) + unchecked(0x41))); - dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41))); - } - catch (UnsupportedEncodingException) - { - } - return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset); - } - - internal virtual int ReadWireFormat(byte[] src, int srcIndex) - { - byte[] tmp = new byte[ScopeOffset]; - int length = 15; - for (int i = 0; i < 15; i++) - { - tmp[i] = unchecked((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF)) - - unchecked(0x41)) << 4)); - tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF) - ) - unchecked(0x41)) & unchecked(0x0F))); - if (tmp[i] != unchecked((byte)' ')) - { - length = i + 1; - } - } - try - { - name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding - ); - } - catch (UnsupportedEncodingException) - { - } - HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4; - HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked( - 0x41)) & unchecked(0x0F); - return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset); - } - - internal int ReadWireFormatDos(byte[] src, int srcIndex) - { - - int length = 15; - byte[] tmp = new byte[length]; - - Array.Copy(src, srcIndex, tmp, 0, length); - - try - { - name = Runtime.GetStringForBytes(tmp, 0, length).Trim(); - } - catch (Exception) - { - - } - - HexCode = src[srcIndex + length]; - - return length + 1; - } - - - internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex) - { - if (Scope == null) - { - dst[dstIndex] = unchecked(unchecked(0x00)); - return 1; - } - // copy new scope in - dst[dstIndex++] = unchecked((byte)('.')); - try - { - Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding - ), 0, dst, dstIndex, Scope.Length); - } - catch (UnsupportedEncodingException) - { - } - dstIndex += Scope.Length; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // now go over scope backwards converting '.' to label length - int i = dstIndex - 2; - int e = i - Scope.Length; - int c = 0; - do - { - if (dst[i] == '.') - { - dst[i] = unchecked((byte)c); - c = 0; - } - else - { - c++; - } - } - while (i-- > e); - return Scope.Length + 2; - } - - internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex) - { - int start = srcIndex; - int n; - StringBuilder sb; - if ((n = src[srcIndex++] & unchecked(0xFF)) == 0) - { - Scope = null; - return 1; - } - try - { - sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding)); - srcIndex += n; - while ((n = src[srcIndex++] & unchecked(0xFF)) != 0) - { - sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding)); - srcIndex += n; - } - Scope = sb.ToString(); - } - catch (UnsupportedEncodingException) - { - } - return srcIndex - start; - } - - public override int GetHashCode() - { - int result; - result = name.GetHashCode(); - result += 65599 * HexCode; - result += 65599 * SrcHashCode; - if (Scope != null && Scope.Length != 0) - { - result += Scope.GetHashCode(); - } - return result; - } - - public override bool Equals(object obj) - { - Name n; - if (!(obj is Name)) - { - return false; - } - n = (Name)obj; - if (Scope == null && n.Scope == null) - { - return name.Equals(n.name) && HexCode == n.HexCode; - } - return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope); - } - - public override string ToString() - { - StringBuilder sb = new StringBuilder(); - - //return ""; - - string n = name; - // fix MSBROWSE name - if (n == null) - { - n = "null"; - } - else - { - if (n[0] == unchecked(0x01)) - { - char[] c = n.ToCharArray(); - c[0] = '.'; - c[1] = '.'; - c[14] = '.'; - n = new string(c); - } - } - sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">"); - if (Scope != null) - { - sb.Append(".").Append(Scope); - } - return sb.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs deleted file mode 100644 index 646e65bf8d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryRequest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Netbios -{ - internal class NameQueryRequest : NameServicePacket - { - internal NameQueryRequest(Name name) - { - QuestionName = name; - QuestionType = Nb; - } - - internal override int WriteBodyWireFormat(byte[] dst, int dstIndex) - { - return WriteQuestionSectionWireFormat(dst, dstIndex); - } - - internal override int ReadBodyWireFormat(byte[] src, int srcIndex) - { - return ReadQuestionSectionWireFormat(src, srcIndex); - } - - internal override int WriteRDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadRDataWireFormat(byte[] src, int srcIndex) - { - return 0; - } - - public override string ToString() - { - return "NameQueryRequest[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs deleted file mode 100644 index c7fac8e934..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameQueryResponse.cs +++ /dev/null @@ -1,68 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Netbios -{ - internal class NameQueryResponse : NameServicePacket - { - public NameQueryResponse() - { - RecordName = new Name(); - } - - internal override int WriteBodyWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadBodyWireFormat(byte[] src, int srcIndex) - { - return ReadResourceRecordWireFormat(src, srcIndex); - } - - internal override int WriteRDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadRDataWireFormat(byte[] src, int srcIndex) - { - if (ResultCode != 0 || OpCode != Query) - { - return 0; - } - bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false; - int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5; - srcIndex += 2; - int address = ReadInt4(src, srcIndex); - if (address != 0) - { - AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType); - } - else - { - AddrEntry[AddrIndex] = null; - } - return 6; - } - - public override string ToString() - { - return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry - + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs deleted file mode 100644 index 0d7840a643..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServiceClient.cs +++ /dev/null @@ -1,664 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Linq; -using System.Threading; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -using Thread = SharpCifs.Util.Sharpen.Thread; - -namespace SharpCifs.Netbios -{ - internal class NameServiceClient : IRunnable - { - internal const int DefaultSoTimeout = 5000; - - internal const int DefaultRcvBufSize = 576; - - internal const int DefaultSndBufSize = 576; - - internal const int NameServiceUdpPort = 137; - - internal const int DefaultRetryCount = 2; - - internal const int DefaultRetryTimeout = 3000; - - internal const int ResolverLmhosts = 1; - - internal const int ResolverBcast = 2; - - internal const int ResolverWins = 3; - - private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size" - , DefaultSndBufSize); - - private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size" - , DefaultRcvBufSize); - - private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout", - DefaultSoTimeout); - - private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount" - , DefaultRetryCount); - - private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout" - , DefaultRetryTimeout); - - private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137); - - private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr" - , null); - - private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder"); - - private static LogStream _log = LogStream.GetInstance(); - - private readonly object _lock = new object(); - - private int _lport; - - private int _closeTimeout; - - private byte[] _sndBuf; - - private byte[] _rcvBuf; - - private SocketEx _socket; - - private Hashtable _responseTable = new Hashtable(); - - private Thread _thread; - - private int _nextNameTrnId; - - private int[] _resolveOrder; - - private bool _waitResponse = true; - - private AutoResetEvent _autoResetWaitReceive; - - internal IPAddress laddr; - - internal IPAddress Baddr; - - public NameServiceClient() - : this(Lport, Laddr) - { - } - - internal NameServiceClient(int lport, IPAddress laddr) - { - this._lport = lport; - - this.laddr = laddr - ?? Config.GetLocalHost() - ?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault(); - - try - { - Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255")); - } - catch (Exception) - { - - } - - _sndBuf = new byte[SndBufSize]; - _rcvBuf = new byte[RcvBufSize]; - - - if (string.IsNullOrEmpty(Ro)) - { - if (NbtAddress.GetWinsAddress() == null) - { - _resolveOrder = new int[2]; - _resolveOrder[0] = ResolverLmhosts; - _resolveOrder[1] = ResolverBcast; - } - else - { - _resolveOrder = new int[3]; - _resolveOrder[0] = ResolverLmhosts; - _resolveOrder[1] = ResolverWins; - _resolveOrder[2] = ResolverBcast; - } - } - else - { - int[] tmp = new int[3]; - StringTokenizer st = new StringTokenizer(Ro, ","); - int i = 0; - while (st.HasMoreTokens()) - { - string s = st.NextToken().Trim(); - if (Runtime.EqualsIgnoreCase(s, "LMHOSTS")) - { - tmp[i++] = ResolverLmhosts; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "WINS")) - { - if (NbtAddress.GetWinsAddress() == null) - { - if (_log.Level > 1) - { - _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set" - ); - } - continue; - } - tmp[i++] = ResolverWins; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "BCAST")) - { - tmp[i++] = ResolverBcast; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "DNS")) - { - } - else - { - // skip - if (_log.Level > 1) - { - _log.WriteLine("unknown resolver method: " + s); - } - } - } - } - } - } - _resolveOrder = new int[i]; - Array.Copy(tmp, 0, _resolveOrder, 0, i); - } - } - - internal virtual int GetNextNameTrnId() - { - if ((++_nextNameTrnId & unchecked(0xFFFF)) == 0) - { - _nextNameTrnId = 1; - } - return _nextNameTrnId; - } - - /// - internal virtual void EnsureOpen(int timeout) - { - _closeTimeout = 0; - if (SoTimeout != 0) - { - _closeTimeout = Math.Max(SoTimeout, timeout); - } - // If socket is still good, the new closeTimeout will - // be ignored; see tryClose comment. - if (_socket == null) - { - _socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - //IPAddress.`Address` property deleted - //_socket.Bind(new IPEndPoint(laddr.Address, _lport)); - _socket.Bind(new IPEndPoint(laddr, _lport)); - - if (_waitResponse) - { - _thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient"); - _thread.SetDaemon(true); - _thread.Start(); - } - } - } - - internal virtual void TryClose() - { - lock (_lock) - { - if (_socket != null) - { - //Socket.`Close` method deleted - //_socket.Close(); - _socket.Dispose(); - _socket = null; - } - _thread = null; - - if (_waitResponse) - { - _responseTable.Clear(); - } else - { - _autoResetWaitReceive.Set(); - } - } - } - - public virtual void Run() - { - int nameTrnId; - NameServicePacket response; - - try - { - - while (_thread == Thread.CurrentThread()) - { - _socket.SoTimeOut = _closeTimeout; - - int len = _socket.Receive(_rcvBuf, 0, RcvBufSize); - - if (_log.Level > 3) - { - _log.WriteLine("NetBIOS: new data read from socket"); - } - nameTrnId = NameServicePacket.ReadNameTrnId(_rcvBuf, 0); - response = (NameServicePacket)_responseTable.Get(nameTrnId); - - - if (response == null || response.Received) - { - continue; - } - - lock (response) - { - response.ReadWireFormat(_rcvBuf, 0); - - if (_log.Level > 3) - { - _log.WriteLine(response); - Hexdump.ToHexdump(_log, _rcvBuf, 0, len); - } - - if (response.IsResponse) - { - response.Received = true; - - Runtime.Notify(response); - } - } - } - - } - catch (TimeoutException) - { - - } - catch (Exception ex) - { - if (_log.Level > 2) - { - Runtime.PrintStackTrace(ex, _log); - } - } - finally - { - TryClose(); - } - } - - /// - internal virtual void Send(NameServicePacket request, NameServicePacket response, - int timeout) - { - int nid = 0; - int max = NbtAddress.Nbns.Length; - if (max == 0) - { - max = 1; - } - - lock (response) - { - - while (max-- > 0) - { - try - { - lock (_lock) - { - request.NameTrnId = GetNextNameTrnId(); - nid = request.NameTrnId; - response.Received = false; - _responseTable.Put(nid, response); - EnsureOpen(timeout + 1000); - int requestLenght = request.WriteWireFormat(_sndBuf, 0); - _socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport)); - if (_log.Level > 3) - { - _log.WriteLine(request); - Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght); - } - - } - if (_waitResponse) - { - long start = Runtime.CurrentTimeMillis(); - while (timeout > 0) - { - Runtime.Wait(response, timeout); - if (response.Received && request.QuestionType == response.RecordType) - { - return; - } - response.Received = false; - timeout -= (int)(Runtime.CurrentTimeMillis() - start); - } - } - } - catch (Exception ie) - { - throw new IOException(ie.Message); - } - finally - { - //Sharpen.Collections.Remove(responseTable, nid); - if (_waitResponse) - { - _responseTable.Remove(nid); - } - } - if (_waitResponse) - { - lock (_lock) - { - if (NbtAddress.IsWins(request.Addr) == false) - { - break; - } - if (request.Addr == NbtAddress.GetWinsAddress()) - { - NbtAddress.SwitchWins(); - } - request.Addr = NbtAddress.GetWinsAddress(); - } - } - } - } - } - - /// - internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr) - { - int n; - NameQueryRequest request = new NameQueryRequest(name); - NameQueryResponse response = new NameQueryResponse(); - request.Addr = addr ?? NbtAddress.GetWinsAddress(); - request.IsBroadcast = request.Addr == null; - if (request.IsBroadcast) - { - request.Addr = Baddr; - n = RetryCount; - } - else - { - request.IsBroadcast = false; - n = 1; - } - do - { - try - { - Send(request, response, RetryTimeout); - } - catch (IOException ioe) - { - if (_log.Level > 1) - { - Runtime.PrintStackTrace(ioe, _log); - } - throw new UnknownHostException(ioe); - } - if (response.Received && response.ResultCode == 0) - { - return response.AddrEntry; - } - } - while (--n > 0 && request.IsBroadcast); - throw new UnknownHostException(); - } - - /// - internal virtual NbtAddress GetByName(Name name, IPAddress addr) - { - int n; - - NameQueryRequest request = new NameQueryRequest(name); - NameQueryResponse response = new NameQueryResponse(); - if (addr != null) - { - request.Addr = addr; - request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked(unchecked(0xFF))); - n = RetryCount; - do - { - try - { - Send(request, response, RetryTimeout); - } - catch (IOException ioe) - { - if (_log.Level > 1) - { - Runtime.PrintStackTrace(ioe, _log); - } - throw new UnknownHostException(ioe); - } - if (response.Received && response.ResultCode == 0 - && response.IsResponse) - { - int last = response.AddrEntry.Length - 1; - response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode(); - return response.AddrEntry[last]; - } - } - while (--n > 0 && request.IsBroadcast); - throw new UnknownHostException(); - } - for (int i = 0; i < _resolveOrder.Length; i++) - { - try - { - switch (_resolveOrder[i]) - { - case ResolverLmhosts: - { - NbtAddress ans = Lmhosts.GetByName(name); - if (ans != null) - { - ans.HostName.SrcHashCode = 0; - // just has to be different - // from other methods - return ans; - } - break; - } - - case ResolverWins: - case ResolverBcast: - { - if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName - && name.HexCode != unchecked(0x1d)) - { - request.Addr = NbtAddress.GetWinsAddress(); - request.IsBroadcast = false; - } - else - { - request.Addr = Baddr; - request.IsBroadcast = true; - } - n = RetryCount; - while (n-- > 0) - { - try - { - Send(request, response, RetryTimeout); - } - catch (IOException ioe) - { - if (_log.Level > 1) - { - Runtime.PrintStackTrace(ioe, _log); - } - throw new UnknownHostException(ioe); - } - if (response.Received && response.ResultCode == 0 - && response.IsResponse) - { - - response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode(); - return response.AddrEntry[0]; - } - if (_resolveOrder[i] == ResolverWins) - { - break; - } - } - break; - } - } - } - catch (IOException) - { - } - } - throw new UnknownHostException(); - } - - /// - internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr) - { - int n; - int srcHashCode; - NodeStatusRequest request; - NodeStatusResponse response; - response = new NodeStatusResponse(addr); - request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null)); - request.Addr = addr.GetInetAddress(); - n = RetryCount; - while (n-- > 0) - { - try - { - Send(request, response, RetryTimeout); - } - catch (IOException ioe) - { - if (_log.Level > 1) - { - Runtime.PrintStackTrace(ioe, _log); - } - throw new UnknownHostException(ioe); - } - if (response.Received && response.ResultCode == 0) - { - srcHashCode = request.Addr.GetHashCode(); - for (int i = 0; i < response.AddressArray.Length; i++) - { - response.AddressArray[i].HostName.SrcHashCode = srcHashCode; - } - return response.AddressArray; - } - } - throw new UnknownHostException(); - } - - internal virtual NbtAddress[] GetHosts() - { - try - { - _waitResponse = false; - - byte[] bAddrBytes = laddr.GetAddressBytes(); - - for (int i = 1; i <= 254; i++) - { - NodeStatusRequest request; - NodeStatusResponse response; - - byte[] addrBytes = { - bAddrBytes[0], - bAddrBytes[1], - bAddrBytes[2], - (byte)i - }; - - IPAddress addr = new IPAddress(addrBytes); - - //response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName, - // (int)addr.Address, false, 0x20)); - response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName, - BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20)); - - request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x20), null)); - request.Addr = addr; - Send(request, response, 0); - } - - } - catch (IOException ioe) - { - if (_log.Level > 1) - { - Runtime.PrintStackTrace(ioe, _log); - } - throw new UnknownHostException(ioe); - } - - _autoResetWaitReceive = new AutoResetEvent(false); - _thread = new Thread(this); - _thread.SetDaemon(true); - _thread.Start(); - - _autoResetWaitReceive.WaitOne(); - - List result = new List(); - - foreach (var key in _responseTable.Keys) - { - NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key]; - - if (resp.Received && resp.ResultCode == 0) - { - foreach (var entry in resp.AddressArray) - { - if (entry.HostName.HexCode == 0x20) - { - result.Add(entry); - } - } - } - } - - _responseTable.Clear(); - - _waitResponse = true; - - return result.Count > 0 ? result.ToArray() : null; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs deleted file mode 100644 index 28e98406e4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NameServicePacket.cs +++ /dev/null @@ -1,448 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.Net; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - internal abstract class NameServicePacket - { - internal const int Query = 0; - - internal const int Wack = 7; - - internal const int FmtErr = 0x1; - - internal const int SrvErr = 0x2; - - internal const int ImpErr = 0x4; - - internal const int RfsErr = 0x5; - - internal const int ActErr = 0x6; - - internal const int CftErr = 0x7; - - internal const int NbIn = 0x00200001; - - internal const int NbstatIn = 0x00210001; - - internal const int Nb = 0x0020; - - internal const int Nbstat = 0x0021; - - internal const int In = 0x0001; - - internal const int A = 0x0001; - - internal const int Ns = 0x0002; - - internal const int Null = 0x000a; - - internal const int HeaderLength = 12; - - internal const int OpcodeOffset = 2; - - internal const int QuestionOffset = 4; - - internal const int AnswerOffset = 6; - - internal const int AuthorityOffset = 8; - - internal const int AdditionalOffset = 10; - - // opcode - // rcode - // type/class - // header field offsets - internal static void WriteInt2(int val, byte[] dst, int dstIndex) - { - dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); - dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); - } - - internal static void WriteInt4(int val, byte[] dst, int dstIndex) - { - dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); - dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); - } - - internal static int ReadInt2(byte[] src, int srcIndex) - { - return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked( - 0xFF)); - } - - internal static int ReadInt4(byte[] src, int srcIndex) - { - return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked( - 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src - [srcIndex + 3] & unchecked(0xFF)); - } - - internal static int ReadNameTrnId(byte[] src, int srcIndex) - { - return ReadInt2(src, srcIndex); - } - - internal int AddrIndex; - - internal NbtAddress[] AddrEntry; - - internal int NameTrnId; - - internal int OpCode; - - internal int ResultCode; - - internal int QuestionCount; - - internal int AnswerCount; - - internal int AuthorityCount; - - internal int AdditionalCount; - - internal bool Received; - - internal bool IsResponse; - - internal bool IsAuthAnswer; - - internal bool IsTruncated; - - internal bool IsRecurDesired; - - internal bool IsRecurAvailable; - - internal bool IsBroadcast; - - internal Name QuestionName; - - internal Name RecordName; - - internal int QuestionType; - - internal int QuestionClass; - - internal int RecordType; - - internal int RecordClass; - - internal int Ttl; - - internal int RDataLength; - - internal IPAddress Addr; - - public NameServicePacket() - { - IsRecurDesired = true; - IsBroadcast = true; - QuestionCount = 1; - QuestionClass = In; - } - - internal virtual int WriteWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dstIndex += WriteHeaderWireFormat(dst, dstIndex); - dstIndex += WriteBodyWireFormat(dst, dstIndex); - return dstIndex - start; - } - - internal virtual int ReadWireFormat(byte[] src, int srcIndex) - { - int start = srcIndex; - srcIndex += ReadHeaderWireFormat(src, srcIndex); - srcIndex += ReadBodyWireFormat(src, srcIndex); - return srcIndex - start; - } - - internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(NameTrnId, dst, dstIndex); - dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer - ? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01) - : unchecked(0x00)))); - dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked( - 0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) : - unchecked(0x00)) + (ResultCode & unchecked(0x0F)))); - WriteInt2(QuestionCount, dst, start + QuestionOffset); - WriteInt2(AnswerCount, dst, start + AnswerOffset); - WriteInt2(AuthorityCount, dst, start + AuthorityOffset); - WriteInt2(AdditionalCount, dst, start + AdditionalOffset); - return HeaderLength; - } - - internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex) - { - NameTrnId = ReadInt2(src, srcIndex); - IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false - : true; - OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3; - IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ? - false : true; - IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false - : true; - IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ? - false : true; - IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80)) - == 0) ? false : true; - IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0) - ? false : true; - ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F); - QuestionCount = ReadInt2(src, srcIndex + QuestionOffset); - AnswerCount = ReadInt2(src, srcIndex + AnswerOffset); - AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset); - AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset); - return HeaderLength; - } - - internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dstIndex += QuestionName.WriteWireFormat(dst, dstIndex); - WriteInt2(QuestionType, dst, dstIndex); - dstIndex += 2; - WriteInt2(QuestionClass, dst, dstIndex); - dstIndex += 2; - return dstIndex - start; - } - - internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex) - { - int start = srcIndex; - srcIndex += QuestionName.ReadWireFormat(src, srcIndex); - QuestionType = ReadInt2(src, srcIndex); - srcIndex += 2; - QuestionClass = ReadInt2(src, srcIndex); - srcIndex += 2; - return srcIndex - start; - } - - internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - if (RecordName == QuestionName) - { - dst[dstIndex++] = unchecked(unchecked(0xC0)); - // label string pointer to - dst[dstIndex++] = unchecked(unchecked(0x0C)); - } - else - { - // questionName (offset 12) - dstIndex += RecordName.WriteWireFormat(dst, dstIndex); - } - WriteInt2(RecordType, dst, dstIndex); - dstIndex += 2; - WriteInt2(RecordClass, dst, dstIndex); - dstIndex += 2; - WriteInt4(Ttl, dst, dstIndex); - dstIndex += 4; - RDataLength = WriteRDataWireFormat(dst, dstIndex + 2); - WriteInt2(RDataLength, dst, dstIndex); - dstIndex += 2 + RDataLength; - return dstIndex - start; - } - - internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex) - { - int start = srcIndex; - int end; - if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0)) - { - RecordName = QuestionName; - // label string pointer to questionName - srcIndex += 2; - } - else - { - srcIndex += RecordName.ReadWireFormat(src, srcIndex); - } - RecordType = ReadInt2(src, srcIndex); - srcIndex += 2; - RecordClass = ReadInt2(src, srcIndex); - srcIndex += 2; - Ttl = ReadInt4(src, srcIndex); - srcIndex += 4; - RDataLength = ReadInt2(src, srcIndex); - srcIndex += 2; - AddrEntry = new NbtAddress[RDataLength / 6]; - end = srcIndex + RDataLength; - for (AddrIndex = 0; srcIndex < end; AddrIndex++) - { - srcIndex += ReadRDataWireFormat(src, srcIndex); - } - return srcIndex - start; - } - - internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex); - - internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex); - - internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex); - - internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex); - - public override string ToString() - { - string opCodeString; - string resultCodeString; - string questionTypeString; - string recordTypeString; - - switch (OpCode) - { - case Query: - { - opCodeString = "QUERY"; - break; - } - - case Wack: - { - opCodeString = "WACK"; - break; - } - - default: - { - opCodeString = Extensions.ToString(OpCode); - break; - } - } - switch (ResultCode) - { - case FmtErr: - { - resultCodeString = "FMT_ERR"; - break; - } - - case SrvErr: - { - resultCodeString = "SRV_ERR"; - break; - } - - case ImpErr: - { - resultCodeString = "IMP_ERR"; - break; - } - - case RfsErr: - { - resultCodeString = "RFS_ERR"; - break; - } - - case ActErr: - { - resultCodeString = "ACT_ERR"; - break; - } - - case CftErr: - { - resultCodeString = "CFT_ERR"; - break; - } - - default: - { - resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1); - break; - } - } - switch (QuestionType) - { - case Nb: - { - questionTypeString = "NB"; - break; - } - - case Nbstat: - { - questionTypeString = "NBSTAT"; - break; - } - - default: - { - questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4); - break; - } - } - switch (RecordType) - { - case A: - { - recordTypeString = "A"; - break; - } - - case Ns: - { - recordTypeString = "NS"; - break; - } - - case Null: - { - recordTypeString = "NULL"; - break; - } - - case Nb: - { - recordTypeString = "NB"; - break; - } - - case Nbstat: - { - recordTypeString = "NBSTAT"; - break; - } - - default: - { - recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4); - break; - } - } - return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode=" - + opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated - + ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired - + ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount=" - + QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount - + ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType=" - + questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" + - Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType=" - + recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump - .ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs deleted file mode 100644 index c64d385f1b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs +++ /dev/null @@ -1,920 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Linq; -using System.Net; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; -using Extensions = SharpCifs.Util.Sharpen.Extensions; - -namespace SharpCifs.Netbios -{ - /// This class represents a NetBIOS over TCP/IP address. - /// - /// This class represents a NetBIOS over TCP/IP address. Under normal - /// conditions, users of jCIFS need not be concerned with this class as - /// name resolution and session services are handled internally by the smb package. - ///

Applications can use the methods getLocalHost, - /// getByName, and - /// getAllByAddress to create a new NbtAddress instance. This - /// class is symmetric with - /// System.Net.IPAddress - /// . - ///

About NetBIOS: The NetBIOS name - /// service is a dynamic distributed service that allows hosts to resolve - /// names by broadcasting a query, directing queries to a server such as - /// Samba or WINS. NetBIOS is currently the primary networking layer for - /// providing name service, datagram service, and session service to the - /// Microsoft Windows platform. A NetBIOS name can be 15 characters long - /// and hosts usually registers several names on the network. From a - /// Windows command prompt you can see - /// what names a host registers with the nbtstat command. - ///

-	/// C:\>nbtstat -a 192.168.1.15
-	/// NetBIOS Remote Machine Name Table
-	/// Name               Type         Status
-	/// ---------------------------------------------
-	/// JMORRIS2        <00>  UNIQUE      Registered
-	/// BILLING-NY      <00>  GROUP       Registered
-	/// JMORRIS2        <03>  UNIQUE      Registered
-	/// JMORRIS2        <20>  UNIQUE      Registered
-	/// BILLING-NY      <1E>  GROUP       Registered
-	/// JMORRIS         <03>  UNIQUE      Registered
-	/// MAC Address = 00-B0-34-21-FA-3B
-	/// 
- ///

The hostname of this machine is JMORRIS2. It is - /// a member of the group(a.k.a workgroup and domain) BILLING-NY. To - /// obtain an - /// System.Net.IPAddress - /// for a host one might do: - ///

-	/// InetAddress addr = NbtAddress.getByName( "jmorris2" ).getInetAddress();
-	/// 
- ///

From a UNIX platform with Samba installed you can perform similar - /// diagnostics using the nmblookup utility. - /// - /// Michael B. Allen - /// System.Net.IPAddress - /// jcifs-0.1 - public sealed class NbtAddress - { - internal static readonly string AnyHostsName = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"; - - ///

- /// This is a special name for querying the master browser that serves the - /// list of hosts found in "Network Neighborhood". - /// - /// - /// This is a special name for querying the master browser that serves the - /// list of hosts found in "Network Neighborhood". - /// - public static readonly string MasterBrowserName = "\u0001\u0002__MSBROWSE__\u0002"; - - /// - /// A special generic name specified when connecting to a host for which - /// a name is not known. - /// - /// - /// A special generic name specified when connecting to a host for which - /// a name is not known. Not all servers respond to this name. - /// - public static readonly string SmbserverName = "*SMBSERVER "; - - /// A B node only broadcasts name queries. - /// - /// A B node only broadcasts name queries. This is the default if a - /// nameserver such as WINS or Samba is not specified. - /// - public const int BNode = 0; - - /// - /// A Point-to-Point node, or P node, unicasts queries to a nameserver - /// only. - /// - /// - /// A Point-to-Point node, or P node, unicasts queries to a nameserver - /// only. Natrually the jcifs.netbios.nameserver property must - /// be set. - /// - public const int PNode = 1; - - /// - /// Try Broadcast queries first, then try to resolve the name using the - /// nameserver. - /// - /// - /// Try Broadcast queries first, then try to resolve the name using the - /// nameserver. - /// - public const int MNode = 2; - - /// A Hybrid node tries to resolve a name using the nameserver first. - /// - /// A Hybrid node tries to resolve a name using the nameserver first. If - /// that fails use the broadcast address. This is the default if a nameserver - /// is provided. This is the behavior of Microsoft Windows machines. - /// - public const int HNode = 3; - - internal static readonly IPAddress[] Nbns = Config.GetInetAddressArray("jcifs.netbios.wins" - , ",", new IPAddress[0]); - - private static readonly NameServiceClient Client = new NameServiceClient(); - - private const int DefaultCachePolicy = 30; - - private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy" - , DefaultCachePolicy); - - private const int Forever = -1; - - private static int _nbnsIndex; - - private static readonly Hashtable AddressCache = new Hashtable(); - - private static readonly Hashtable LookupTable = new Hashtable(); - - internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null); - - internal static readonly NbtAddress UnknownAddress = new NbtAddress - (UnknownName, 0, false, BNode); - - internal static readonly byte[] UnknownMacAddress = { unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)) }; - - internal sealed class CacheEntry - { - internal Name HostName; - - internal NbtAddress Address; - - internal long Expiration; - - internal CacheEntry(Name hostName, NbtAddress address, long expiration) - { - this.HostName = hostName; - this.Address = address; - this.Expiration = expiration; - } - } - - internal static NbtAddress Localhost; - - static NbtAddress() - { - IPAddress localInetAddress; - string localHostname; - Name localName; - AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress - , Forever)); - localInetAddress = Client.laddr; - if (localInetAddress == null) - { - try - { - localInetAddress = Extensions.GetAddressByName("127.0.0.1"); - } - catch (UnknownHostException) - { - - } - } - localHostname = Config.GetProperty("jcifs.netbios.hostname", null); - if (string.IsNullOrEmpty(localHostname)) - { - byte[] addr = localInetAddress.GetAddressBytes(); - - /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked( - (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked( - (int)(0xFF))), 2);*/ - localHostname = "JCIFS_127_0_0_1"; - } - localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope" - , null)); - Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode - , false, false, true, false, UnknownMacAddress); - CacheAddress(localName, Localhost, Forever); - } - - internal static void CacheAddress(Name hostName, NbtAddress addr) - { - if (CachePolicy == 0) - { - return; - } - long expiration = -1; - if (CachePolicy != Forever) - { - expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000; - } - CacheAddress(hostName, addr, expiration); - } - - internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration - ) - { - if (CachePolicy == 0) - { - return; - } - lock (AddressCache) - { - CacheEntry entry = (CacheEntry)AddressCache.Get(hostName); - if (entry == null) - { - entry = new CacheEntry(hostName, addr, expiration); - AddressCache.Put(hostName, entry); - } - else - { - entry.Address = addr; - entry.Expiration = expiration; - } - } - } - - internal static void CacheAddressArray(NbtAddress[] addrs) - { - if (CachePolicy == 0) - { - return; - } - long expiration = -1; - if (CachePolicy != Forever) - { - expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000; - } - lock (AddressCache) - { - for (int i = 0; i < addrs.Length; i++) - { - CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName - ); - if (entry == null) - { - entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration); - AddressCache.Put(addrs[i].HostName, entry); - } - else - { - entry.Address = addrs[i]; - entry.Expiration = expiration; - } - } - } - } - - internal static NbtAddress GetCachedAddress(Name hostName) - { - if (CachePolicy == 0) - { - return null; - } - lock (AddressCache) - { - CacheEntry entry = (CacheEntry)AddressCache.Get(hostName); - if (entry != null && entry.Expiration < Runtime.CurrentTimeMillis() && entry.Expiration - >= 0) - { - entry = null; - } - return entry != null ? entry.Address : null; - } - } - - /// - internal static NbtAddress DoNameQuery(Name name, IPAddress svr) - { - NbtAddress addr; - if (name.HexCode == unchecked(0x1d) && svr == null) - { - svr = Client.Baddr; - } - // bit of a hack but saves a lookup - name.SrcHashCode = svr != null ? svr.GetHashCode() : 0; - addr = GetCachedAddress(name); - if (addr == null) - { - if ((addr = (NbtAddress)CheckLookupTable(name)) == null) - { - try - { - addr = Client.GetByName(name, svr); - } - catch (UnknownHostException) - { - addr = UnknownAddress; - } - finally - { - CacheAddress(name, addr); - UpdateLookupTable(name); - } - } - } - if (addr == UnknownAddress) - { - throw new UnknownHostException(name.ToString()); - } - return addr; - } - - private static object CheckLookupTable(Name name) - { - object obj; - lock (LookupTable) - { - if (LookupTable.ContainsKey(name) == false) - { - LookupTable.Put(name, name); - return null; - } - while (LookupTable.ContainsKey(name)) - { - try - { - Runtime.Wait(LookupTable); - } - catch (Exception) - { - } - } - } - obj = GetCachedAddress(name); - if (obj == null) - { - lock (LookupTable) - { - LookupTable.Put(name, name); - } - } - return obj; - } - - private static void UpdateLookupTable(Name name) - { - lock (LookupTable) - { - //Sharpen.Collections.Remove(LOOKUP_TABLE, name); - LookupTable.Remove(name); - Runtime.NotifyAll(LookupTable); - } - } - - /// Retrieves the local host address. - /// Retrieves the local host address. - /// - /// This is not likely as the IP returned - /// by InetAddress should be available - /// - public static NbtAddress GetLocalHost() - { - return Localhost; - } - - public static NbtAddress[] GetHosts() - { - return new NameServiceClient().GetHosts(); - } - - public static Name GetLocalName() - { - return Localhost.HostName; - } - - /// Determines the address of a host given it's host name. - /// - /// Determines the address of a host given it's host name. The name can be a NetBIOS name like - /// "freto" or an IP address like "192.168.1.15". It cannot be a DNS name; - /// the analygous - /// Jcifs.UniAddress - /// or - /// System.Net.IPAddress - /// getByName methods can be used for that. - /// - /// hostname to resolve - /// if there is an error resolving the name - /// - public static NbtAddress GetByName(string host) - { - return GetByName(host, unchecked(0x00), null); - } - - /// Determines the address of a host given it's host name. - /// - /// Determines the address of a host given it's host name. NetBIOS - /// names also have a type. Types(aka Hex Codes) - /// are used to distiquish the various services on a host. <a - /// href="../../../nbtcodes.html">Here is - /// a fairly complete list of NetBIOS hex codes. Scope is not used but is - /// still functional in other NetBIOS products and so for completeness it has been - /// implemented. A scope of null or "" - /// signifies no scope. - /// - /// the name to resolve - /// the hex code of the name - /// the scope of the name - /// if there is an error resolving the name - /// - public static NbtAddress GetByName(string host, int type, string scope) - { - return GetByName(host, type, scope, null); - } - - /// - public static NbtAddress GetByName(string host, int type, string scope, IPAddress - svr) - { - if (string.IsNullOrEmpty(host)) - { - return GetLocalHost(); - } - if (!char.IsDigit(host[0])) - { - return DoNameQuery(new Name(host, type, scope), svr); - } - int ip = unchecked(0x00); - int hitDots = 0; - char[] data = host.ToCharArray(); - for (int i = 0; i < data.Length; i++) - { - char c = data[i]; - if (c < 48 || c > 57) - { - return DoNameQuery(new Name(host, type, scope), svr); - } - int b = unchecked(0x00); - while (c != '.') - { - if (c < 48 || c > 57) - { - return DoNameQuery(new Name(host, type, scope), svr); - } - b = b * 10 + c - '0'; - if (++i >= data.Length) - { - break; - } - c = data[i]; - } - if (b > unchecked(0xFF)) - { - return DoNameQuery(new Name(host, type, scope), svr); - } - ip = (ip << 8) + b; - hitDots++; - } - if (hitDots != 4 || host.EndsWith(".")) - { - return DoNameQuery(new Name(host, type, scope), svr); - } - return new NbtAddress(UnknownName, ip, false, BNode); - } - - /// - public static NbtAddress[] GetAllByName(string host, int type, string scope, IPAddress - svr) - { - return Client.GetAllByName(new Name(host, type, scope), svr); - } - - /// Retrieve all addresses of a host by it's address. - /// - /// Retrieve all addresses of a host by it's address. NetBIOS hosts can - /// have many names for a given IP address. The name and IP address make the - /// NetBIOS address. This provides a way to retrieve the other names for a - /// host with the same IP address. - /// - /// hostname to lookup all addresses for - /// if there is an error resolving the name - /// - public static NbtAddress[] GetAllByAddress(string host) - { - return GetAllByAddress(GetByName(host, unchecked(0x00), null)); - } - - /// Retrieve all addresses of a host by it's address. - /// - /// Retrieve all addresses of a host by it's address. NetBIOS hosts can - /// have many names for a given IP address. The name and IP address make - /// the NetBIOS address. This provides a way to retrieve the other names - /// for a host with the same IP address. See - /// GetByName(string) - /// for a description of type - /// and scope. - /// - /// hostname to lookup all addresses for - /// the hexcode of the name - /// the scope of the name - /// if there is an error resolving the name - /// - public static NbtAddress[] GetAllByAddress(string host, int type, string scope) - { - return GetAllByAddress(GetByName(host, type, scope)); - } - - /// Retrieve all addresses of a host by it's address. - /// - /// Retrieve all addresses of a host by it's address. NetBIOS hosts can - /// have many names for a given IP address. The name and IP address make the - /// NetBIOS address. This provides a way to retrieve the other names for a - /// host with the same IP address. - /// - /// the address to query - /// if address cannot be resolved - public static NbtAddress[] GetAllByAddress(NbtAddress addr) - { - try - { - NbtAddress[] addrs = Client.GetNodeStatus(addr); - CacheAddressArray(addrs); - return addrs; - } - catch (UnknownHostException) - { - throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr. - HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length - == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host " - + addr.GetHostAddress()); - } - } - - public static IPAddress GetWinsAddress() - { - return Nbns.Length == 0 ? null : Nbns[_nbnsIndex]; - } - - public static bool IsWins(IPAddress svr) - { - for (int i = 0; svr != null && i < Nbns.Length; i++) - { - if (svr.GetHashCode() == Nbns[i].GetHashCode()) - { - return true; - } - } - return false; - } - - internal static IPAddress SwitchWins() - { - _nbnsIndex = (_nbnsIndex + 1) < Nbns.Length ? _nbnsIndex + 1 : 0; - return Nbns.Length == 0 ? null : Nbns[_nbnsIndex]; - } - - internal Name HostName; - - internal int Address; - - internal int NodeType; - - internal bool GroupName; - - internal bool isBeingDeleted; - - internal bool isInConflict; - - internal bool isActive; - - internal bool isPermanent; - - internal bool IsDataFromNodeStatus; - - internal byte[] MacAddress; - - internal string CalledName; - - internal NbtAddress(Name hostName, int address, bool groupName, int nodeType) - { - this.HostName = hostName; - this.Address = address; - this.GroupName = groupName; - this.NodeType = nodeType; - } - - internal NbtAddress(Name hostName, int address, bool groupName, int nodeType, bool - isBeingDeleted, bool isInConflict, bool isActive, bool isPermanent, byte[] macAddress - ) - { - this.HostName = hostName; - this.Address = address; - this.GroupName = groupName; - this.NodeType = nodeType; - this.isBeingDeleted = isBeingDeleted; - this.isInConflict = isInConflict; - this.isActive = isActive; - this.isPermanent = isPermanent; - this.MacAddress = macAddress; - IsDataFromNodeStatus = true; - } - - public string FirstCalledName() - { - CalledName = HostName.name; - if (char.IsDigit(CalledName[0])) - { - int i; - int len; - int dots; - char[] data; - i = dots = 0; - len = CalledName.Length; - data = CalledName.ToCharArray(); - while (i < len && char.IsDigit(data[i++])) - { - if (i == len && dots == 3) - { - // probably an IP address - CalledName = SmbserverName; - break; - } - if (i < len && data[i] == '.') - { - dots++; - i++; - } - } - } - else - { - switch (HostName.HexCode) - { - case unchecked(0x1B): - case unchecked(0x1C): - case unchecked(0x1D): - { - CalledName = SmbserverName; - break; - } - } - } - return CalledName; - } - - public string NextCalledName() - { - if (CalledName == HostName.name) - { - CalledName = SmbserverName; - } - else - { - if (CalledName == SmbserverName) - { - NbtAddress[] addrs; - try - { - addrs = Client.GetNodeStatus(this); - if (HostName.HexCode == unchecked(0x1D)) - { - for (int i = 0; i < addrs.Length; i++) - { - if (addrs[i].HostName.HexCode == unchecked(0x20)) - { - return addrs[i].HostName.name; - } - } - return null; - } - if (IsDataFromNodeStatus) - { - CalledName = null; - return HostName.name; - } - } - catch (UnknownHostException) - { - CalledName = null; - } - } - else - { - CalledName = null; - } - } - return CalledName; - } - - /// - internal void CheckData() - { - if (HostName == UnknownName) - { - GetAllByAddress(this); - } - } - - /// - internal void CheckNodeStatusData() - { - if (IsDataFromNodeStatus == false) - { - GetAllByAddress(this); - } - } - - /// Determines if the address is a group address. - /// - /// Determines if the address is a group address. This is also - /// known as a workgroup name or group name. - /// - /// if the host cannot be resolved to find out. - /// - public bool IsGroupAddress() - { - CheckData(); - return GroupName; - } - - /// Checks the node type of this address. - /// Checks the node type of this address. - /// - /// - /// B_NODE - /// , - /// P_NODE - /// , - /// M_NODE - /// , - /// H_NODE - /// - /// if the host cannot be resolved to find out. - /// - public int GetNodeType() - { - CheckData(); - return NodeType; - } - - /// Determines if this address in the process of being deleted. - /// Determines if this address in the process of being deleted. - /// if the host cannot be resolved to find out. - /// - public bool IsBeingDeleted() - { - CheckNodeStatusData(); - return isBeingDeleted; - } - - /// Determines if this address in conflict with another address. - /// Determines if this address in conflict with another address. - /// if the host cannot be resolved to find out. - /// - public bool IsInConflict() - { - CheckNodeStatusData(); - return isInConflict; - } - - /// Determines if this address is active. - /// Determines if this address is active. - /// if the host cannot be resolved to find out. - /// - public bool IsActive() - { - CheckNodeStatusData(); - return isActive; - } - - /// Determines if this address is set to be permanent. - /// Determines if this address is set to be permanent. - /// if the host cannot be resolved to find out. - /// - public bool IsPermanent() - { - CheckNodeStatusData(); - return isPermanent; - } - - /// Retrieves the MAC address of the remote network interface. - /// Retrieves the MAC address of the remote network interface. Samba returns all zeros. - /// - /// the MAC address as an array of six bytes - /// - /// if the host cannot be resolved to - /// determine the MAC address. - /// - public byte[] GetMacAddress() - { - CheckNodeStatusData(); - return MacAddress; - } - - /// The hostname of this address. - /// - /// The hostname of this address. If the hostname is null the local machines - /// IP address is returned. - /// - /// the text representation of the hostname associated with this address - public string GetHostName() - { - if (HostName == UnknownName) - { - return GetHostAddress(); - } - return HostName.name; - } - - /// Returns the raw IP address of this NbtAddress. - /// - /// Returns the raw IP address of this NbtAddress. The result is in network - /// byte order: the highest order byte of the address is in getAddress()[0]. - /// - /// a four byte array - public byte[] GetAddress() - { - byte[] addr = new byte[4]; - addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF - ))); - addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF - ))); - addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF) - )); - addr[3] = unchecked((byte)(Address & unchecked(0xFF))); - return addr; - } - - /// To convert this address to an InetAddress. - /// To convert this address to an InetAddress. - /// - /// the - /// System.Net.IPAddress - /// representation of this address. - /// - /// - public IPAddress GetInetAddress() - { - return Extensions.GetAddressByName(GetHostAddress()); - } - - /// - /// Returns this IP adress as a - /// string - /// in the form "%d.%d.%d.%d". - /// - public string GetHostAddress() - { - return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) + "." + (((int)( - ((uint)Address) >> 16)) & unchecked(0xFF)) + "." + (((int)(((uint)Address - ) >> 8)) & unchecked(0xFF)) + "." + (((int)(((uint)Address) >> 0)) & unchecked( - 0xFF)); - } - - /// Returned the hex code associated with this name(e.g. - /// Returned the hex code associated with this name(e.g. 0x20 is for the file service) - /// - public int GetNameType() - { - return HostName.HexCode; - } - - /// Returns a hashcode for this IP address. - /// - /// Returns a hashcode for this IP address. The hashcode comes from the IP address - /// and is not generated from the string representation. So because NetBIOS nodes - /// can have many names, all names associated with an IP will have the same - /// hashcode. - /// - public override int GetHashCode() - { - return Address; - } - - /// Determines if this address is equal two another. - /// - /// Determines if this address is equal two another. Only the IP Addresses - /// are compared. Similar to the - /// GetHashCode() - /// method, the comparison - /// is based on the integer IP address and not the string representation. - /// - public override bool Equals(object obj) - { - return (obj != null) && (obj is NbtAddress) && (((NbtAddress)obj).Address == Address - ); - } - - /// - /// Returns the - /// string - /// representaion of this address. - /// - public override string ToString() - { - return HostName + "/" + GetHostAddress(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs deleted file mode 100644 index e785c99433..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs +++ /dev/null @@ -1,164 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; - -namespace SharpCifs.Netbios -{ - - public class NbtException : IOException - { - public const int Success = 0; - - public const int ErrNamSrvc = unchecked(0x01); - - public const int ErrSsnSrvc = unchecked(0x02); - - public const int FmtErr = unchecked(0x1); - - public const int SrvErr = unchecked(0x2); - - public const int ImpErr = unchecked(0x4); - - public const int RfsErr = unchecked(0x5); - - public const int ActErr = unchecked(0x6); - - public const int CftErr = unchecked(0x7); - - public const int ConnectionRefused = -1; - - public const int NotListeningCalled = unchecked(0x80); - - public const int NotListeningCalling = unchecked(0x81); - - public const int CalledNotPresent = unchecked(0x82); - - public const int NoResources = unchecked(0x83); - - public const int Unspecified = unchecked(0x8F); - - public int ErrorClass; - - public int ErrorCode; - - // error classes - // name service error codes - // session service error codes - public static string GetErrorString(int errorClass, int errorCode) - { - string result = string.Empty; - switch (errorClass) - { - case Success: - { - result += "SUCCESS"; - break; - } - - case ErrNamSrvc: - { - result += "ERR_NAM_SRVC/"; - switch (errorCode) - { - case FmtErr: - { - result += "FMT_ERR: Format Error"; - goto default; - } - - default: - { - result += "Unknown error code: " + errorCode; - break; - } - } - break; - } - - case ErrSsnSrvc: - { - result += "ERR_SSN_SRVC/"; - switch (errorCode) - { - case ConnectionRefused: - { - result += "Connection refused"; - break; - } - - case NotListeningCalled: - { - result += "Not listening on called name"; - break; - } - - case NotListeningCalling: - { - result += "Not listening for calling name"; - break; - } - - case CalledNotPresent: - { - result += "Called name not present"; - break; - } - - case NoResources: - { - result += "Called name present, but insufficient resources"; - break; - } - - case Unspecified: - { - result += "Unspecified error"; - break; - } - - default: - { - result += "Unknown error code: " + errorCode; - break; - } - } - break; - } - - default: - { - result += "unknown error class: " + errorClass; - break; - } - } - return result; - } - - public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass - , errorCode)) - { - this.ErrorClass = errorClass; - this.ErrorCode = errorCode; - } - - public override string ToString() - { - return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString=" - + GetErrorString(ErrorClass, ErrorCode); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs deleted file mode 100644 index 66d3bb3e52..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusRequest.cs +++ /dev/null @@ -1,59 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Netbios -{ - internal class NodeStatusRequest : NameServicePacket - { - internal NodeStatusRequest(Name name) - { - QuestionName = name; - QuestionType = Nbstat; - IsRecurDesired = false; - IsBroadcast = false; - } - - internal override int WriteBodyWireFormat(byte[] dst, int dstIndex) - { - int tmp = QuestionName.HexCode; - QuestionName.HexCode = unchecked(0x00); - // type has to be 0x00 for node status - int result = WriteQuestionSectionWireFormat(dst, dstIndex); - QuestionName.HexCode = tmp; - return result; - } - - internal override int ReadBodyWireFormat(byte[] src, int srcIndex) - { - return 0; - } - - internal override int WriteRDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadRDataWireFormat(byte[] src, int srcIndex) - { - return 0; - } - - public override string ToString() - { - return "NodeStatusRequest[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs deleted file mode 100644 index aa32144192..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/NodeStatusResponse.cs +++ /dev/null @@ -1,140 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - internal class NodeStatusResponse : NameServicePacket - { - private NbtAddress _queryAddress; - - private int _numberOfNames; - - private byte[] _macAddress; - - private byte[] _stats; - - internal NbtAddress[] AddressArray; - - internal NodeStatusResponse(NbtAddress queryAddress) - { - this._queryAddress = queryAddress; - RecordName = new Name(); - _macAddress = new byte[6]; - } - - internal override int WriteBodyWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadBodyWireFormat(byte[] src, int srcIndex) - { - return ReadResourceRecordWireFormat(src, srcIndex); - } - - internal override int WriteRDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadRDataWireFormat(byte[] src, int srcIndex) - { - int start = srcIndex; - _numberOfNames = src[srcIndex] & unchecked(0xFF); - int namesLength = _numberOfNames * 18; - int statsLength = RDataLength - namesLength - 1; - _numberOfNames = src[srcIndex++] & unchecked(0xFF); - // gotta read the mac first so we can populate addressArray with it - Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6); - srcIndex += ReadNodeNameArray(src, srcIndex); - _stats = new byte[statsLength]; - Array.Copy(src, srcIndex, _stats, 0, statsLength); - srcIndex += statsLength; - return srcIndex - start; - } - - private int ReadNodeNameArray(byte[] src, int srcIndex) - { - int start = srcIndex; - AddressArray = new NbtAddress[_numberOfNames]; - string n; - int hexCode; - string scope = _queryAddress.HostName.Scope; - bool groupName; - int ownerNodeType; - bool isBeingDeleted; - bool isInConflict; - bool isActive; - bool isPermanent; - int j; - bool addrFound = false; - try - { - for (int i = 0; i < _numberOfNames; srcIndex += 18, i++) - { - for (j = srcIndex + 14; src[j] == unchecked(0x20); j--) - { - } - n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding - ); - hexCode = src[srcIndex + 15] & unchecked(0xFF); - groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false; - ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5; - isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false; - isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false; - isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false; - isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false; - if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName - == NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n))) - { - if (_queryAddress.HostName == NbtAddress.UnknownName) - { - _queryAddress.HostName = new Name(n, hexCode, scope); - } - _queryAddress.GroupName = groupName; - _queryAddress.NodeType = ownerNodeType; - _queryAddress.isBeingDeleted = isBeingDeleted; - _queryAddress.isInConflict = isInConflict; - _queryAddress.isActive = isActive; - _queryAddress.isPermanent = isPermanent; - _queryAddress.MacAddress = _macAddress; - _queryAddress.IsDataFromNodeStatus = true; - addrFound = true; - AddressArray[i] = _queryAddress; - } - else - { - AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address - , groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent, - _macAddress); - } - } - } - catch (UnsupportedEncodingException) - { - } - return srcIndex - start; - } - - public override string ToString() - { - return "NodeStatusResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs deleted file mode 100644 index a5243f7aa4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRequestPacket.cs +++ /dev/null @@ -1,63 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - public class SessionRequestPacket : SessionServicePacket - { - private Name _calledName; - - private Name _callingName; - - public SessionRequestPacket() - { - _calledName = new Name(); - _callingName = new Name(); - } - - public SessionRequestPacket(Name calledName, Name callingName) - { - Type = SessionRequest; - this._calledName = calledName; - this._callingName = callingName; - } - - internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dstIndex += _calledName.WriteWireFormat(dst, dstIndex); - dstIndex += _callingName.WriteWireFormat(dst, dstIndex); - return dstIndex - start; - } - - /// - internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - if (@in.Read(buffer, bufferIndex, Length) != Length) - { - throw new IOException("invalid session request wire format"); - } - bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex); - bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex); - return bufferIndex - start; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs deleted file mode 100644 index c901c6e263..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionRetargetResponsePacket.cs +++ /dev/null @@ -1,54 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - internal class SessionRetargetResponsePacket : SessionServicePacket - { - private NbtAddress _retargetAddress; - - private int _retargetPort; - - public SessionRetargetResponsePacket() - { - Type = SessionRetargetResponse; - Length = 6; - } - - internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - /// - internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex - ) - { - if (@in.Read(buffer, bufferIndex, Length) != Length) - { - throw new IOException("unexpected EOF reading netbios retarget session response"); - } - int addr = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - _retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode); - _retargetPort = ReadInt2(buffer, bufferIndex); - return Length; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs b/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs deleted file mode 100644 index c8d194222f..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Netbios/SessionServicePacket.cs +++ /dev/null @@ -1,156 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Netbios -{ - public abstract class SessionServicePacket - { - internal const int SessionMessage = unchecked(0x00); - - internal const int SessionRequest = unchecked(0x81); - - public const int PositiveSessionResponse = unchecked(0x82); - - public const int NegativeSessionResponse = unchecked(0x83); - - internal const int SessionRetargetResponse = unchecked(0x84); - - internal const int SessionKeepAlive = unchecked(0x85); - - internal const int MaxMessageSize = unchecked(0x0001FFFF); - - internal const int HeaderLength = 4; - - // session service packet types - internal static void WriteInt2(int val, byte[] dst, int dstIndex) - { - dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); - dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); - } - - internal static void WriteInt4(int val, byte[] dst, int dstIndex) - { - dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); - dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); - } - - internal static int ReadInt2(byte[] src, int srcIndex) - { - return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked( - 0xFF)); - } - - internal static int ReadInt4(byte[] src, int srcIndex) - { - return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked( - 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src - [srcIndex + 3] & unchecked(0xFF)); - } - - internal static int ReadLength(byte[] src, int srcIndex) - { - srcIndex++; - return ((src[srcIndex++] & unchecked(0x01)) << 16) + ((src[srcIndex++] & unchecked( - 0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF)); - } - - /// - internal static int Readn(InputStream @in, byte[] b, int off, int len) - { - int i = 0; - int n; - while (i < len) - { - n = @in.Read(b, off + i, len - i); - if (n <= 0) - { - break; - } - i += n; - } - return i; - } - - /// - internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex - ) - { - int n; - if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength) - { - if (n == -1) - { - return -1; - } - throw new IOException("unexpected EOF reading netbios session header"); - } - int t = buffer[bufferIndex] & unchecked(0xFF); - return t; - } - - internal int Type; - - internal int Length; - - public virtual int WriteWireFormat(byte[] dst, int dstIndex) - { - Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength); - WriteHeaderWireFormat(dst, dstIndex); - return HeaderLength + Length; - } - - /// - internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex - ) - { - ReadHeaderWireFormat(@in, buffer, bufferIndex); - return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex); - } - - internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = unchecked((byte)Type); - if (Length > unchecked(0x0000FFFF)) - { - dst[dstIndex] = unchecked(unchecked(0x01)); - } - dstIndex++; - WriteInt2(Length, dst, dstIndex); - return HeaderLength; - } - - /// - internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex - ) - { - Type = buffer[bufferIndex++] & unchecked(0xFF); - Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) + ReadInt2(buffer - , bufferIndex + 1); - return HeaderLength; - } - - internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex); - - /// - internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex - ); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs deleted file mode 100644 index 116f71b754..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs +++ /dev/null @@ -1,197 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Ntlmssp -{ - /// Flags used during negotiation of NTLMSSP authentication. - /// Flags used during negotiation of NTLMSSP authentication. - public abstract class NtlmFlags - { - /// Indicates whether Unicode strings are supported or used. - /// Indicates whether Unicode strings are supported or used. - public const int NtlmsspNegotiateUnicode = unchecked(0x00000001); - - /// Indicates whether OEM strings are supported or used. - /// Indicates whether OEM strings are supported or used. - public const int NtlmsspNegotiateOem = unchecked(0x00000002); - - /// - /// Indicates whether the authentication target is requested from - /// the server. - /// - /// - /// Indicates whether the authentication target is requested from - /// the server. - /// - public const int NtlmsspRequestTarget = unchecked(0x00000004); - - /// - /// Specifies that communication across the authenticated channel - /// should carry a digital signature (message integrity). - /// - /// - /// Specifies that communication across the authenticated channel - /// should carry a digital signature (message integrity). - /// - public const int NtlmsspNegotiateSign = unchecked(0x00000010); - - /// - /// Specifies that communication across the authenticated channel - /// should be encrypted (message confidentiality). - /// - /// - /// Specifies that communication across the authenticated channel - /// should be encrypted (message confidentiality). - /// - public const int NtlmsspNegotiateSeal = unchecked(0x00000020); - - /// Indicates datagram authentication. - /// Indicates datagram authentication. - public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040); - - /// - /// Indicates that the LAN Manager session key should be used for - /// signing and sealing authenticated communication. - /// - /// - /// Indicates that the LAN Manager session key should be used for - /// signing and sealing authenticated communication. - /// - public const int NtlmsspNegotiateLmKey = unchecked(0x00000080); - - public const int NtlmsspNegotiateNetware = unchecked(0x00000100); - - /// Indicates support for NTLM authentication. - /// Indicates support for NTLM authentication. - public const int NtlmsspNegotiateNtlm = unchecked(0x00000200); - - /// - /// Indicates whether the OEM-formatted domain name in which the - /// client workstation has membership is supplied in the Type-1 message. - /// - /// - /// Indicates whether the OEM-formatted domain name in which the - /// client workstation has membership is supplied in the Type-1 message. - /// This is used in the negotation of local authentication. - /// - public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000); - - /// - /// Indicates whether the OEM-formatted workstation name is supplied - /// in the Type-1 message. - /// - /// - /// Indicates whether the OEM-formatted workstation name is supplied - /// in the Type-1 message. This is used in the negotiation of local - /// authentication. - /// - public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000); - - /// - /// Sent by the server to indicate that the server and client are - /// on the same machine. - /// - /// - /// Sent by the server to indicate that the server and client are - /// on the same machine. This implies that the server will include - /// a local security context handle in the Type 2 message, for - /// use in local authentication. - /// - public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000); - - /// - /// Indicates that authenticated communication between the client - /// and server should carry a "dummy" digital signature. - /// - /// - /// Indicates that authenticated communication between the client - /// and server should carry a "dummy" digital signature. - /// - public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000); - - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a domain. - /// - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a domain. - /// - public const int NtlmsspTargetTypeDomain = unchecked(0x00010000); - - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a server. - /// - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a server. - /// - public const int NtlmsspTargetTypeServer = unchecked(0x00020000); - - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a share (presumably for share-level - /// authentication). - /// - /// - /// Sent by the server in the Type 2 message to indicate that the - /// target authentication realm is a share (presumably for share-level - /// authentication). - /// - public const int NtlmsspTargetTypeShare = unchecked(0x00040000); - - /// - /// Indicates that the NTLM2 signing and sealing scheme should be used - /// for protecting authenticated communications. - /// - /// - /// Indicates that the NTLM2 signing and sealing scheme should be used - /// for protecting authenticated communications. This refers to a - /// particular session security scheme, and is not related to the use - /// of NTLMv2 authentication. - /// - public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000); - - public const int NtlmsspRequestInitResponse = unchecked(0x00100000); - - public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000); - - public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000 - ); - - /// - /// Sent by the server in the Type 2 message to indicate that it is - /// including a Target Information block in the message. - /// - /// - /// Sent by the server in the Type 2 message to indicate that it is - /// including a Target Information block in the message. The Target - /// Information block is used in the calculation of the NTLMv2 response. - /// - public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000); - - /// Indicates that 128-bit encryption is supported. - /// Indicates that 128-bit encryption is supported. - public const int NtlmsspNegotiate128 = unchecked(0x20000000); - - public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000); - - /// Indicates that 56-bit encryption is supported. - /// Indicates that 56-bit encryption is supported. - public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000)); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs deleted file mode 100644 index 02827d2d07..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs +++ /dev/null @@ -1,140 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Ntlmssp -{ - /// Abstract superclass for all NTLMSSP messages. - /// Abstract superclass for all NTLMSSP messages. - public abstract class NtlmMessage : NtlmFlags - { - /// The NTLMSSP "preamble". - /// The NTLMSSP "preamble". - protected internal static readonly byte[] NtlmsspSignature = { unchecked( - (byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')), - unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte - )('S')), unchecked((byte)('P')), unchecked(0) }; - - private static readonly string OemEncoding = Config.DefaultOemEncoding; - - protected internal static readonly string UniEncoding = "UTF-16LE"; - - private int _flags; - - /// Returns the flags currently in use for this message. - /// Returns the flags currently in use for this message. - /// - /// An int containing the flags in use for this - /// message. - /// - public virtual int GetFlags() - { - return _flags; - } - - /// Sets the flags for this message. - /// Sets the flags for this message. - /// The flags for this message. - public virtual void SetFlags(int flags) - { - this._flags = flags; - } - - /// Returns the status of the specified flag. - /// Returns the status of the specified flag. - /// The flag to test (i.e., NTLMSSP_NEGOTIATE_OEM). - /// A boolean indicating whether the flag is set. - public virtual bool GetFlag(int flag) - { - return (GetFlags() & flag) != 0; - } - - /// Sets or clears the specified flag. - /// Sets or clears the specified flag. - /// - /// The flag to set/clear (i.e., - /// NTLMSSP_NEGOTIATE_OEM). - /// - /// - /// Indicates whether to set (true) or - /// clear (false) the specified flag. - /// - public virtual void SetFlag(int flag, bool value) - { - SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff) - ) ^ flag))); - } - - internal static int ReadULong(byte[] src, int index) - { - return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index - + 3] & unchecked(0xff)) << 24); - } - - internal static int ReadUShort(byte[] src, int index) - { - return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8); - } - - internal static byte[] ReadSecurityBuffer(byte[] src, int index) - { - int length = ReadUShort(src, index); - int offset = ReadULong(src, index + 4); - byte[] buffer = new byte[length]; - Array.Copy(src, offset, buffer, 0, length); - return buffer; - } - - internal static void WriteULong(byte[] dest, int offset, int value) - { - dest[offset] = unchecked((byte)(value & unchecked(0xff))); - dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff))); - dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff))); - dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff))); - } - - internal static void WriteUShort(byte[] dest, int offset, int value) - { - dest[offset] = unchecked((byte)(value & unchecked(0xff))); - dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff))); - } - - internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset, - byte[] src) - { - int length = (src != null) ? src.Length : 0; - if (length == 0) - { - return; - } - WriteUShort(dest, offset, length); - WriteUShort(dest, offset + 2, length); - WriteULong(dest, offset + 4, bodyOffset); - Array.Copy(src, 0, dest, bodyOffset, length); - } - - internal static string GetOemEncoding() - { - return OemEncoding; - } - - /// Returns the raw byte representation of this message. - /// Returns the raw byte representation of this message. - /// A byte[] containing the raw message material. - public abstract byte[] ToByteArray(); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs deleted file mode 100644 index afcf5ec7e7..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs +++ /dev/null @@ -1,249 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Netbios; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Ntlmssp -{ - /// Represents an NTLMSSP Type-1 message. - /// Represents an NTLMSSP Type-1 message. - public class Type1Message : NtlmMessage - { - private static readonly int DefaultFlags; - - private static readonly string DefaultDomain; - - private static readonly string DefaultWorkstation; - - private string _suppliedDomain; - - private string _suppliedWorkstation; - - static Type1Message() - { - DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" - , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); - DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); - string defaultWorkstation = null; - try - { - defaultWorkstation = NbtAddress.GetLocalHost().GetHostName(); - } - catch (UnknownHostException) - { - } - DefaultWorkstation = defaultWorkstation; - } - - /// - /// Creates a Type-1 message using default values from the current - /// environment. - /// - /// - /// Creates a Type-1 message using default values from the current - /// environment. - /// - public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation - ()) - { - } - - /// Creates a Type-1 message with the specified parameters. - /// Creates a Type-1 message with the specified parameters. - /// The flags to apply to this message. - /// The supplied authentication domain. - /// The supplied workstation name. - public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation) - { - SetFlags(GetDefaultFlags() | flags); - SetSuppliedDomain(suppliedDomain); - if (suppliedWorkstation == null) - { - suppliedWorkstation = GetDefaultWorkstation(); - } - SetSuppliedWorkstation(suppliedWorkstation); - } - - /// Creates a Type-1 message using the given raw Type-1 material. - /// Creates a Type-1 message using the given raw Type-1 material. - /// The raw Type-1 material used to construct this message. - /// If an error occurs while parsing the material. - /// - public Type1Message(byte[] material) - { - Parse(material); - } - - /// Returns the supplied authentication domain. - /// Returns the supplied authentication domain. - /// A String containing the supplied domain. - public virtual string GetSuppliedDomain() - { - return _suppliedDomain; - } - - /// Sets the supplied authentication domain for this message. - /// Sets the supplied authentication domain for this message. - /// The supplied domain for this message. - public virtual void SetSuppliedDomain(string suppliedDomain) - { - this._suppliedDomain = suppliedDomain; - } - - /// Returns the supplied workstation name. - /// Returns the supplied workstation name. - /// A String containing the supplied workstation name. - public virtual string GetSuppliedWorkstation() - { - return _suppliedWorkstation; - } - - /// Sets the supplied workstation name for this message. - /// Sets the supplied workstation name for this message. - /// The supplied workstation for this message. - public virtual void SetSuppliedWorkstation(string suppliedWorkstation) - { - this._suppliedWorkstation = suppliedWorkstation; - } - - public override byte[] ToByteArray() - { - try - { - string suppliedDomain = GetSuppliedDomain(); - string suppliedWorkstation = GetSuppliedWorkstation(); - int flags = GetFlags(); - bool hostInfo = false; - byte[] domain = new byte[0]; - if (!string.IsNullOrEmpty(suppliedDomain)) - { - hostInfo = true; - flags |= NtlmsspNegotiateOemDomainSupplied; - domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding - ()); - } - else - { - flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff))); - } - byte[] workstation = new byte[0]; - if (!string.IsNullOrEmpty(suppliedWorkstation)) - { - hostInfo = true; - flags |= NtlmsspNegotiateOemWorkstationSupplied; - workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding - ()); - } - else - { - flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff - ))); - } - byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16 - ]; - Array.Copy(NtlmsspSignature, 0, type1, 0, 8); - WriteULong(type1, 8, 1); - WriteULong(type1, 12, flags); - if (hostInfo) - { - WriteSecurityBuffer(type1, 16, 32, domain); - WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation); - } - return type1; - } - catch (IOException ex) - { - throw new InvalidOperationException(ex.Message); - } - } - - public override string ToString() - { - string suppliedDomain = GetSuppliedDomain(); - string suppliedWorkstation = GetSuppliedWorkstation(); - return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null" - ) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null" - ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]"; - } - - /// - /// Returns the default flags for a generic Type-1 message in the - /// current environment. - /// - /// - /// Returns the default flags for a generic Type-1 message in the - /// current environment. - /// - /// An int containing the default flags. - public static int GetDefaultFlags() - { - return DefaultFlags; - } - - /// Returns the default domain from the current environment. - /// Returns the default domain from the current environment. - /// A String containing the default domain. - public static string GetDefaultDomain() - { - return DefaultDomain; - } - - /// Returns the default workstation from the current environment. - /// Returns the default workstation from the current environment. - /// A String containing the default workstation. - public static string GetDefaultWorkstation() - { - return DefaultWorkstation; - } - - /// - private void Parse(byte[] material) - { - for (int i = 0; i < 8; i++) - { - if (material[i] != NtlmsspSignature[i]) - { - throw new IOException("Not an NTLMSSP message."); - } - } - if (ReadULong(material, 8) != 1) - { - throw new IOException("Not a Type 1 message."); - } - int flags = ReadULong(material, 12); - string suppliedDomain = null; - if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0) - { - byte[] domain = ReadSecurityBuffer(material, 16); - suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding()); - } - string suppliedWorkstation = null; - if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0) - { - byte[] workstation = ReadSecurityBuffer(material, 24); - suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding - ()); - } - SetFlags(flags); - SetSuppliedDomain(suppliedDomain); - SetSuppliedWorkstation(suppliedWorkstation); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs deleted file mode 100644 index 104e5b0fdf..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs +++ /dev/null @@ -1,438 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Netbios; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Ntlmssp -{ - /// Represents an NTLMSSP Type-2 message. - /// Represents an NTLMSSP Type-2 message. - public class Type2Message : NtlmMessage - { - private static readonly int DefaultFlags; - - private static readonly string DefaultDomain; - - private static readonly byte[] DefaultTargetInformation; - - private byte[] _challenge; - - private string _target; - - private byte[] _context; - - private byte[] _targetInformation; - - static Type2Message() - { - DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" - , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); - DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); - byte[] domain = new byte[0]; - if (DefaultDomain != null) - { - try - { - domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding); - } - catch (IOException) - { - } - } - int domainLength = domain.Length; - byte[] server = new byte[0]; - try - { - string host = NbtAddress.GetLocalHost().GetHostName(); - if (host != null) - { - try - { - server = Runtime.GetBytesForString(host, UniEncoding); - } - catch (IOException) - { - } - } - } - catch (UnknownHostException) - { - } - int serverLength = server.Length; - byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength - > 0 ? serverLength + 4 : 0) + 4]; - int offset = 0; - if (domainLength > 0) - { - WriteUShort(targetInfo, offset, 2); - offset += 2; - WriteUShort(targetInfo, offset, domainLength); - offset += 2; - Array.Copy(domain, 0, targetInfo, offset, domainLength); - offset += domainLength; - } - if (serverLength > 0) - { - WriteUShort(targetInfo, offset, 1); - offset += 2; - WriteUShort(targetInfo, offset, serverLength); - offset += 2; - Array.Copy(server, 0, targetInfo, offset, serverLength); - } - DefaultTargetInformation = targetInfo; - } - - /// - /// Creates a Type-2 message using default values from the current - /// environment. - /// - /// - /// Creates a Type-2 message using default values from the current - /// environment. - /// - public Type2Message() : this(GetDefaultFlags(), null, null) - { - } - - /// - /// Creates a Type-2 message in response to the given Type-1 message - /// using default values from the current environment. - /// - /// - /// Creates a Type-2 message in response to the given Type-1 message - /// using default values from the current environment. - /// - /// The Type-1 message which this represents a response to. - public Type2Message(Type1Message type1) : this(type1, null, null) - { - } - - /// Creates a Type-2 message in response to the given Type-1 message. - /// Creates a Type-2 message in response to the given Type-1 message. - /// The Type-1 message which this represents a response to. - /// The challenge from the domain controller/server. - /// The authentication target. - public Type2Message(Type1Message type1, byte[] challenge, string target) : this(GetDefaultFlags - (type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget - )) ? GetDefaultDomain() : target) - { - } - - /// Creates a Type-2 message with the specified parameters. - /// Creates a Type-2 message with the specified parameters. - /// The flags to apply to this message. - /// The challenge from the domain controller/server. - /// The authentication target. - public Type2Message(int flags, byte[] challenge, string target) - { - SetFlags(flags); - SetChallenge(challenge); - SetTarget(target); - if (target != null) - { - SetTargetInformation(GetDefaultTargetInformation()); - } - } - - /// Creates a Type-2 message using the given raw Type-2 material. - /// Creates a Type-2 message using the given raw Type-2 material. - /// The raw Type-2 material used to construct this message. - /// If an error occurs while parsing the material. - /// - public Type2Message(byte[] material) - { - Parse(material); - } - - /// Returns the challenge for this message. - /// Returns the challenge for this message. - /// A byte[] containing the challenge. - public virtual byte[] GetChallenge() - { - return _challenge; - } - - /// Sets the challenge for this message. - /// Sets the challenge for this message. - /// The challenge from the domain controller/server. - public virtual void SetChallenge(byte[] challenge) - { - this._challenge = challenge; - } - - /// Returns the authentication target. - /// Returns the authentication target. - /// A String containing the authentication target. - public virtual string GetTarget() - { - return _target; - } - - /// Sets the authentication target. - /// Sets the authentication target. - /// The authentication target. - public virtual void SetTarget(string target) - { - this._target = target; - } - - /// Returns the target information block. - /// Returns the target information block. - /// - /// A byte[] containing the target information block. - /// The target information block is used by the client to create an - /// NTLMv2 response. - /// - public virtual byte[] GetTargetInformation() - { - return _targetInformation; - } - - /// Sets the target information block. - /// - /// Sets the target information block. - /// The target information block is used by the client to create - /// an NTLMv2 response. - /// - /// The target information block. - public virtual void SetTargetInformation(byte[] targetInformation) - { - this._targetInformation = targetInformation; - } - - /// Returns the local security context. - /// Returns the local security context. - /// - /// A byte[] containing the local security - /// context. This is used by the client to negotiate local - /// authentication. - /// - public virtual byte[] GetContext() - { - return _context; - } - - /// Sets the local security context. - /// - /// Sets the local security context. This is used by the client - /// to negotiate local authentication. - /// - /// The local security context. - public virtual void SetContext(byte[] context) - { - this._context = context; - } - - public override byte[] ToByteArray() - { - try - { - string targetName = GetTarget(); - byte[] challenge = GetChallenge(); - byte[] context = GetContext(); - byte[] targetInformation = GetTargetInformation(); - int flags = GetFlags(); - byte[] target = new byte[0]; - if ((flags & NtlmsspRequestTarget) != 0) - { - if (!string.IsNullOrEmpty(targetName)) - { - target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString - (targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper - (), GetOemEncoding()); - } - else - { - flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget); - } - } - if (targetInformation != null) - { - flags |= NtlmsspNegotiateTargetInfo; - // empty context is needed for padding when t.i. is supplied. - if (context == null) - { - context = new byte[8]; - } - } - int data = 32; - if (context != null) - { - data += 8; - } - if (targetInformation != null) - { - data += 8; - } - byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation - .Length : 0)]; - Array.Copy(NtlmsspSignature, 0, type2, 0, 8); - WriteULong(type2, 8, 2); - WriteSecurityBuffer(type2, 12, data, target); - WriteULong(type2, 20, flags); - Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8); - if (context != null) - { - Array.Copy(context, 0, type2, 32, 8); - } - if (targetInformation != null) - { - WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation); - } - return type2; - } - catch (IOException ex) - { - throw new InvalidOperationException(ex.Message); - } - } - - public override string ToString() - { - string target = GetTarget(); - byte[] challenge = GetChallenge(); - byte[] context = GetContext(); - byte[] targetInformation = GetTargetInformation(); - return "Type2Message[target=" + target + ",challenge=" + (challenge == null ? "null" - : "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null" - : "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation - == null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" + - Hexdump.ToHexString(GetFlags(), 8) + "]"; - } - - /// - /// Returns the default flags for a generic Type-2 message in the - /// current environment. - /// - /// - /// Returns the default flags for a generic Type-2 message in the - /// current environment. - /// - /// An int containing the default flags. - public static int GetDefaultFlags() - { - return DefaultFlags; - } - - /// - /// Returns the default flags for a Type-2 message created in response - /// to the given Type-1 message in the current environment. - /// - /// - /// Returns the default flags for a Type-2 message created in response - /// to the given Type-1 message in the current environment. - /// - /// An int containing the default flags. - public static int GetDefaultFlags(Type1Message type1) - { - if (type1 == null) - { - return DefaultFlags; - } - int flags = NtlmsspNegotiateNtlm; - int type1Flags = type1.GetFlags(); - flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode - : NtlmsspNegotiateOem; - if ((type1Flags & NtlmsspRequestTarget) != 0) - { - string domain = GetDefaultDomain(); - if (domain != null) - { - flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain; - } - } - return flags; - } - - /// Returns the default domain from the current environment. - /// Returns the default domain from the current environment. - /// A String containing the domain. - public static string GetDefaultDomain() - { - return DefaultDomain; - } - - public static byte[] GetDefaultTargetInformation() - { - return DefaultTargetInformation; - } - - /// - private void Parse(byte[] material) - { - for (int i = 0; i < 8; i++) - { - if (material[i] != NtlmsspSignature[i]) - { - throw new IOException("Not an NTLMSSP message."); - } - } - if (ReadULong(material, 8) != 2) - { - throw new IOException("Not a Type 2 message."); - } - int flags = ReadULong(material, 20); - SetFlags(flags); - string target = null; - byte[] bytes = ReadSecurityBuffer(material, 12); - if (bytes.Length != 0) - { - target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode - ) != 0) ? UniEncoding : GetOemEncoding()); - } - SetTarget(target); - for (int i1 = 24; i1 < 32; i1++) - { - if (material[i1] != 0) - { - byte[] challenge = new byte[8]; - Array.Copy(material, 24, challenge, 0, 8); - SetChallenge(challenge); - break; - } - } - int offset = ReadULong(material, 16); - // offset of targetname start - if (offset == 32 || material.Length == 32) - { - return; - } - for (int i2 = 32; i2 < 40; i2++) - { - if (material[i2] != 0) - { - byte[] context = new byte[8]; - Array.Copy(material, 32, context, 0, 8); - SetContext(context); - break; - } - } - if (offset == 40 || material.Length == 40) - { - return; - } - bytes = ReadSecurityBuffer(material, 40); - if (bytes.Length != 0) - { - SetTargetInformation(bytes); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs b/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs deleted file mode 100644 index 9a2a37f3cf..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs +++ /dev/null @@ -1,677 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Netbios; -using SharpCifs.Smb; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Ntlmssp -{ - /// Represents an NTLMSSP Type-3 message. - /// Represents an NTLMSSP Type-3 message. - public class Type3Message : NtlmMessage - { - internal const long MillisecondsBetween1970And1601 = 11644473600000L; - - private static readonly int DefaultFlags; - - private static readonly string DefaultDomain; - - private static readonly string DefaultUser; - - private static readonly string DefaultPassword; - - private static readonly string DefaultWorkstation; - - private static readonly int LmCompatibility; - - //private static readonly SecureRandom RANDOM = new SecureRandom(); - - private byte[] _lmResponse; - - private byte[] _ntResponse; - - private string _domain; - - private string _user; - - private string _workstation; - - private byte[] _masterKey; - - private byte[] _sessionKey; - - static Type3Message() - { - DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" - , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); - DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); - DefaultUser = Config.GetProperty("jcifs.smb.client.username", null); - DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null); - string defaultWorkstation = null; - try - { - defaultWorkstation = NbtAddress.GetLocalHost().GetHostName(); - } - catch (UnknownHostException) - { - } - DefaultWorkstation = defaultWorkstation; - LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3); - } - - /// - /// Creates a Type-3 message using default values from the current - /// environment. - /// - /// - /// Creates a Type-3 message using default values from the current - /// environment. - /// - public Type3Message() - { - SetFlags(GetDefaultFlags()); - SetDomain(GetDefaultDomain()); - SetUser(GetDefaultUser()); - SetWorkstation(GetDefaultWorkstation()); - } - - /// - /// Creates a Type-3 message in response to the given Type-2 message - /// using default values from the current environment. - /// - /// - /// Creates a Type-3 message in response to the given Type-2 message - /// using default values from the current environment. - /// - /// The Type-2 message which this represents a response to. - public Type3Message(Type2Message type2) - { - SetFlags(GetDefaultFlags(type2)); - SetWorkstation(GetDefaultWorkstation()); - string domain = GetDefaultDomain(); - SetDomain(domain); - string user = GetDefaultUser(); - SetUser(user); - string password = GetDefaultPassword(); - switch (LmCompatibility) - { - case 0: - case 1: - { - SetLmResponse(GetLMResponse(type2, password)); - SetNtResponse(GetNTResponse(type2, password)); - break; - } - - case 2: - { - byte[] nt = GetNTResponse(type2, password); - SetLmResponse(nt); - SetNtResponse(nt); - break; - } - - case 3: - case 4: - case 5: - { - byte[] clientChallenge = new byte[8]; - //RANDOM.NextBytes(clientChallenge); - SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge)); - break; - } - - default: - { - SetLmResponse(GetLMResponse(type2, password)); - SetNtResponse(GetNTResponse(type2, password)); - break; - } - } - } - - /// Creates a Type-3 message in response to the given Type-2 message. - /// Creates a Type-3 message in response to the given Type-2 message. - /// The Type-2 message which this represents a response to. - /// The password to use when constructing the response. - /// The domain in which the user has an account. - /// The username for the authenticating user. - /// - /// The workstation from which authentication is - /// taking place. - /// - public Type3Message(Type2Message type2, string password, string domain, string user - , string workstation, int flags) - { - SetFlags(flags | GetDefaultFlags(type2)); - if (workstation == null) - { - workstation = GetDefaultWorkstation(); - } - SetWorkstation(workstation); - SetDomain(domain); - SetUser(user); - switch (LmCompatibility) - { - case 0: - case 1: - { - if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0) - { - SetLmResponse(GetLMResponse(type2, password)); - SetNtResponse(GetNTResponse(type2, password)); - } - else - { - // NTLM2 Session Response - byte[] clientChallenge = new byte[24]; - //RANDOM.NextBytes(clientChallenge); - Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00))); - // NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient - byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password); - byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt, - type2.GetChallenge(), clientChallenge); - SetLmResponse(clientChallenge); - SetNtResponse(ntlm2Response); - if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) - { - byte[] sessionNonce = new byte[16]; - Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8); - Array.Copy(clientChallenge, 0, sessionNonce, 8, 8); - Md4 md4 = new Md4(); - md4.Update(responseKeyNt); - byte[] userSessionKey = md4.Digest(); - Hmact64 hmac = new Hmact64(userSessionKey); - hmac.Update(sessionNonce); - byte[] ntlm2SessionKey = hmac.Digest(); - if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0) - { - _masterKey = new byte[16]; - //RANDOM.NextBytes(masterKey); - byte[] exchangedKey = new byte[16]; - Rc4 rc4 = new Rc4(ntlm2SessionKey); - rc4.Update(_masterKey, 0, 16, exchangedKey, 0); - SetSessionKey(exchangedKey); - } - else - { - _masterKey = ntlm2SessionKey; - SetSessionKey(_masterKey); - } - } - } - break; - } - - case 2: - { - byte[] nt = GetNTResponse(type2, password); - SetLmResponse(nt); - SetNtResponse(nt); - break; - } - - case 3: - case 4: - case 5: - { - byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password - ); - byte[] clientChallenge1 = new byte[8]; - //RANDOM.NextBytes(clientChallenge_1); - SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1)); - byte[] clientChallenge2 = new byte[8]; - //RANDOM.NextBytes(clientChallenge2); - SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2)); - if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) - { - Hmact64 hmac = new Hmact64(responseKeyNt1); - hmac.Update(_ntResponse, 0, 16); - // only first 16 bytes of ntResponse - byte[] userSessionKey = hmac.Digest(); - if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0) - { - _masterKey = new byte[16]; - //RANDOM.NextBytes(masterKey); - byte[] exchangedKey = new byte[16]; - Rc4 rc4 = new Rc4(userSessionKey); - rc4.Update(_masterKey, 0, 16, exchangedKey, 0); - SetSessionKey(exchangedKey); - } - else - { - _masterKey = userSessionKey; - SetSessionKey(_masterKey); - } - } - break; - } - - default: - { - SetLmResponse(GetLMResponse(type2, password)); - SetNtResponse(GetNTResponse(type2, password)); - break; - } - } - } - - /// Creates a Type-3 message with the specified parameters. - /// Creates a Type-3 message with the specified parameters. - /// The flags to apply to this message. - /// The LanManager/LMv2 response. - /// The NT/NTLMv2 response. - /// The domain in which the user has an account. - /// The username for the authenticating user. - /// - /// The workstation from which authentication is - /// taking place. - /// - public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse, string domain - , string user, string workstation) - { - SetFlags(flags); - SetLmResponse(lmResponse); - SetNtResponse(ntResponse); - SetDomain(domain); - SetUser(user); - SetWorkstation(workstation); - } - - /// Creates a Type-3 message using the given raw Type-3 material. - /// Creates a Type-3 message using the given raw Type-3 material. - /// The raw Type-3 material used to construct this message. - /// If an error occurs while parsing the material. - /// - public Type3Message(byte[] material) - { - Parse(material); - } - - /// Returns the LanManager/LMv2 response. - /// Returns the LanManager/LMv2 response. - /// A byte[] containing the LanManager response. - public virtual byte[] GetLMResponse() - { - return _lmResponse; - } - - /// Sets the LanManager/LMv2 response for this message. - /// Sets the LanManager/LMv2 response for this message. - /// The LanManager response. - public virtual void SetLmResponse(byte[] lmResponse) - { - this._lmResponse = lmResponse; - } - - /// Returns the NT/NTLMv2 response. - /// Returns the NT/NTLMv2 response. - /// A byte[] containing the NT/NTLMv2 response. - public virtual byte[] GetNTResponse() - { - return _ntResponse; - } - - /// Sets the NT/NTLMv2 response for this message. - /// Sets the NT/NTLMv2 response for this message. - /// The NT/NTLMv2 response. - public virtual void SetNtResponse(byte[] ntResponse) - { - this._ntResponse = ntResponse; - } - - /// Returns the domain in which the user has an account. - /// Returns the domain in which the user has an account. - /// A String containing the domain for the user. - public virtual string GetDomain() - { - return _domain; - } - - /// Sets the domain for this message. - /// Sets the domain for this message. - /// The domain. - public virtual void SetDomain(string domain) - { - this._domain = domain; - } - - /// Returns the username for the authenticating user. - /// Returns the username for the authenticating user. - /// A String containing the user for this message. - public virtual string GetUser() - { - return _user; - } - - /// Sets the user for this message. - /// Sets the user for this message. - /// The user. - public virtual void SetUser(string user) - { - this._user = user; - } - - /// Returns the workstation from which authentication is being performed. - /// Returns the workstation from which authentication is being performed. - /// A String containing the workstation. - public virtual string GetWorkstation() - { - return _workstation; - } - - /// Sets the workstation for this message. - /// Sets the workstation for this message. - /// The workstation. - public virtual void SetWorkstation(string workstation) - { - this._workstation = workstation; - } - - /// - /// The real session key if the regular session key is actually - /// the encrypted version used for key exchange. - /// - /// - /// The real session key if the regular session key is actually - /// the encrypted version used for key exchange. - /// - /// A byte[] containing the session key. - public virtual byte[] GetMasterKey() - { - return _masterKey; - } - - /// Returns the session key. - /// Returns the session key. - /// A byte[] containing the session key. - public virtual byte[] GetSessionKey() - { - return _sessionKey; - } - - /// Sets the session key. - /// Sets the session key. - /// The session key. - public virtual void SetSessionKey(byte[] sessionKey) - { - this._sessionKey = sessionKey; - } - - public override byte[] ToByteArray() - { - try - { - int flags = GetFlags(); - bool unicode = (flags & NtlmsspNegotiateUnicode) != 0; - string oem = unicode ? null : GetOemEncoding(); - string domainName = GetDomain(); - byte[] domain = null; - if (!string.IsNullOrEmpty(domainName)) - { - domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) : - Runtime.GetBytesForString(domainName, oem); - } - int domainLength = (domain != null) ? domain.Length : 0; - string userName = GetUser(); - byte[] user = null; - if (!string.IsNullOrEmpty(userName)) - { - user = unicode ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString - (userName.ToUpper(), oem); - } - int userLength = (user != null) ? user.Length : 0; - string workstationName = GetWorkstation(); - byte[] workstation = null; - if (!string.IsNullOrEmpty(workstationName)) - { - workstation = unicode ? Runtime.GetBytesForString(workstationName, UniEncoding - ) : Runtime.GetBytesForString(workstationName.ToUpper(), oem); - } - int workstationLength = (workstation != null) ? workstation.Length : 0; - byte[] lmResponse = GetLMResponse(); - int lmLength = (lmResponse != null) ? lmResponse.Length : 0; - byte[] ntResponse = GetNTResponse(); - int ntLength = (ntResponse != null) ? ntResponse.Length : 0; - byte[] sessionKey = GetSessionKey(); - int keyLength = (sessionKey != null) ? sessionKey.Length : 0; - byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength - + ntLength + keyLength]; - Array.Copy(NtlmsspSignature, 0, type3, 0, 8); - WriteULong(type3, 8, 3); - int offset = 64; - WriteSecurityBuffer(type3, 12, offset, lmResponse); - offset += lmLength; - WriteSecurityBuffer(type3, 20, offset, ntResponse); - offset += ntLength; - WriteSecurityBuffer(type3, 28, offset, domain); - offset += domainLength; - WriteSecurityBuffer(type3, 36, offset, user); - offset += userLength; - WriteSecurityBuffer(type3, 44, offset, workstation); - offset += workstationLength; - WriteSecurityBuffer(type3, 52, offset, sessionKey); - WriteULong(type3, 60, flags); - return type3; - } - catch (IOException ex) - { - throw new InvalidOperationException(ex.Message); - } - } - - public override string ToString() - { - string user = GetUser(); - string domain = GetDomain(); - string workstation = GetWorkstation(); - byte[] lmResponse = GetLMResponse(); - byte[] ntResponse = GetNTResponse(); - byte[] sessionKey = GetSessionKey(); - return "Type3Message[domain=" + domain + ",user=" + user + ",workstation=" + workstation - + ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>" - ) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>" - ) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>" - ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]"; - } - - /// - /// Returns the default flags for a generic Type-3 message in the - /// current environment. - /// - /// - /// Returns the default flags for a generic Type-3 message in the - /// current environment. - /// - /// An int containing the default flags. - public static int GetDefaultFlags() - { - return DefaultFlags; - } - - /// - /// Returns the default flags for a Type-3 message created in response - /// to the given Type-2 message in the current environment. - /// - /// - /// Returns the default flags for a Type-3 message created in response - /// to the given Type-2 message in the current environment. - /// - /// An int containing the default flags. - public static int GetDefaultFlags(Type2Message type2) - { - if (type2 == null) - { - return DefaultFlags; - } - int flags = NtlmsspNegotiateNtlm; - flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode - : NtlmsspNegotiateOem; - return flags; - } - - /// - /// Constructs the LanManager response to the given Type-2 message using - /// the supplied password. - /// - /// - /// Constructs the LanManager response to the given Type-2 message using - /// the supplied password. - /// - /// The Type-2 message. - /// The password. - /// A byte[] containing the LanManager response. - public static byte[] GetLMResponse(Type2Message type2, string password) - { - if (type2 == null || password == null) - { - return null; - } - return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge - ()); - } - - public static byte[] GetLMv2Response(Type2Message type2, string domain, string user - , string password, byte[] clientChallenge) - { - if (type2 == null || domain == null || user == null || password == null || clientChallenge - == null) - { - return null; - } - return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge - (), clientChallenge); - } - - public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt, - byte[] clientChallenge) - { - if (type2 == null || responseKeyNt == null || clientChallenge == null) - { - return null; - } - long nanos1601 = (Runtime.CurrentTimeMillis() + MillisecondsBetween1970And1601 - ) * 10000L; - return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge - (), clientChallenge, nanos1601, type2.GetTargetInformation()); - } - - /// - /// Constructs the NT response to the given Type-2 message using - /// the supplied password. - /// - /// - /// Constructs the NT response to the given Type-2 message using - /// the supplied password. - /// - /// The Type-2 message. - /// The password. - /// A byte[] containing the NT response. - public static byte[] GetNTResponse(Type2Message type2, string password) - { - if (type2 == null || password == null) - { - return null; - } - return NtlmPasswordAuthentication.GetNtlmResponse(password, type2.GetChallenge()); - } - - /// Returns the default domain from the current environment. - /// Returns the default domain from the current environment. - /// The default domain. - public static string GetDefaultDomain() - { - return DefaultDomain; - } - - /// Returns the default user from the current environment. - /// Returns the default user from the current environment. - /// The default user. - public static string GetDefaultUser() - { - return DefaultUser; - } - - /// Returns the default password from the current environment. - /// Returns the default password from the current environment. - /// The default password. - public static string GetDefaultPassword() - { - return DefaultPassword; - } - - /// Returns the default workstation from the current environment. - /// Returns the default workstation from the current environment. - /// The default workstation. - public static string GetDefaultWorkstation() - { - return DefaultWorkstation; - } - - /// - private void Parse(byte[] material) - { - for (int i = 0; i < 8; i++) - { - if (material[i] != NtlmsspSignature[i]) - { - throw new IOException("Not an NTLMSSP message."); - } - } - if (ReadULong(material, 8) != 3) - { - throw new IOException("Not a Type 3 message."); - } - byte[] lmResponse = ReadSecurityBuffer(material, 12); - int lmResponseOffset = ReadULong(material, 16); - byte[] ntResponse = ReadSecurityBuffer(material, 20); - int ntResponseOffset = ReadULong(material, 24); - byte[] domain = ReadSecurityBuffer(material, 28); - int domainOffset = ReadULong(material, 32); - byte[] user = ReadSecurityBuffer(material, 36); - int userOffset = ReadULong(material, 40); - byte[] workstation = ReadSecurityBuffer(material, 44); - int workstationOffset = ReadULong(material, 48); - int flags; - string charset; - byte[] _sessionKey = null; - if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset - == 52 || workstationOffset == 52) - { - flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem; - charset = GetOemEncoding(); - } - else - { - _sessionKey = ReadSecurityBuffer(material, 52); - flags = ReadULong(material, 60); - charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding - (); - } - SetSessionKey(_sessionKey); - SetFlags(flags); - SetLmResponse(lmResponse); - SetNtResponse(ntResponse); - SetDomain(Runtime.GetStringForBytes(domain, charset)); - SetUser(Runtime.GetStringForBytes(user, charset)); - SetWorkstation(Runtime.GetStringForBytes(workstation, charset)); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs deleted file mode 100644 index 73b742cfb6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs +++ /dev/null @@ -1,287 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.Text; -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - /// - /// An Access Control Entry (ACE) is an element in a security descriptor - /// such as those associated with files and directories. - /// - /// - /// An Access Control Entry (ACE) is an element in a security descriptor - /// such as those associated with files and directories. The Windows OS - /// determines which users have the necessary permissions to access objects - /// based on these entries. - ///

- /// To fully understand the information exposed by this class a description - /// of the access check algorithm used by Windows is required. The following - /// is a basic description of the algorithm. For a more complete description - /// we recommend reading the section on Access Control in Keith Brown's - /// "The .NET Developer's Guide to Windows Security" (which is also - /// available online). - ///

- /// Direct ACEs are evaluated first in order. The SID of the user performing - /// the operation and the desired access bits are compared to the SID - /// and access mask of each ACE. If the SID matches, the allow/deny flags - /// and access mask are considered. If the ACE is a "deny" - /// ACE and any of the desired access bits match bits in the access - /// mask of the ACE, the whole access check fails. If the ACE is an "allow" - /// ACE and all of the bits in the desired access bits match bits in - /// the access mask of the ACE, the access check is successful. Otherwise, - /// more ACEs are evaluated until all desired access bits (combined) - /// are "allowed". If all of the desired access bits are not "allowed" - /// the then same process is repeated for inherited ACEs. - ///

- /// For example, if user WNET\alice tries to open a file - /// with desired access bits 0x00000003 (FILE_READ_DATA | - /// FILE_WRITE_DATA) and the target file has the following security - /// descriptor ACEs: - ///

-	/// Allow WNET\alice     0x001200A9  Direct
-	/// Allow Administrators 0x001F01FF  Inherited
-	/// Allow SYSTEM         0x001F01FF  Inherited
-	/// 
- /// the access check would fail because the direct ACE has an access mask - /// of 0x001200A9 which doesn't have the - /// FILE_WRITE_DATA bit on (bit 0x00000002). Actually, this isn't quite correct. If - /// WNET\alice is in the local Administrators group the access check - /// will succeed because the inherited ACE allows local Administrators - /// both FILE_READ_DATA and FILE_WRITE_DATA access. - ///
- public class Ace - { - public const int FileReadData = unchecked(0x00000001); - - public const int FileWriteData = unchecked(0x00000002); - - public const int FileAppendData = unchecked(0x00000004); - - public const int FileReadEa = unchecked(0x00000008); - - public const int FileWriteEa = unchecked(0x00000010); - - public const int FileExecute = unchecked(0x00000020); - - public const int FileDelete = unchecked(0x00000040); - - public const int FileReadAttributes = unchecked(0x00000080); - - public const int FileWriteAttributes = unchecked(0x00000100); - - public const int Delete = unchecked(0x00010000); - - public const int ReadControl = unchecked(0x00020000); - - public const int WriteDac = unchecked(0x00040000); - - public const int WriteOwner = unchecked(0x00080000); - - public const int Synchronize = unchecked(0x00100000); - - public const int GenericAll = unchecked(0x10000000); - - public const int GenericExecute = unchecked(0x20000000); - - public const int GenericWrite = unchecked(0x40000000); - - public const int GenericRead = unchecked((int)(0x80000000)); - - public const int FlagsObjectInherit = unchecked(0x01); - - public const int FlagsContainerInherit = unchecked(0x02); - - public const int FlagsNoPropagate = unchecked(0x04); - - public const int FlagsInheritOnly = unchecked(0x08); - - public const int FlagsInherited = unchecked(0x10); - - internal bool Allow; - - internal int Flags; - - internal int Access; - - internal Sid Sid; - - // 1 - // 2 - // 3 - // 4 - // 5 - // 6 - // 7 - // 8 - // 9 - // 16 - // 17 - // 18 - // 19 - // 20 - // 28 - // 29 - // 30 - // 31 - /// Returns true if this ACE is an allow ACE and false if it is a deny ACE. - /// Returns true if this ACE is an allow ACE and false if it is a deny ACE. - public virtual bool IsAllow() - { - return Allow; - } - - /// Returns true if this ACE is an inherited ACE and false if it is a direct ACE. - /// - /// - /// Returns true if this ACE is an inherited ACE and false if it is a direct ACE. - ///

- /// Note: For reasons not fully understood, FLAGS_INHERITED may - /// not be set within all security descriptors even though the ACE was in - /// face inherited. If an inherited ACE is added to a parent the Windows - /// ACL editor will rebuild all children ACEs and set this flag accordingly. - /// - public virtual bool IsInherited() - { - return (Flags & FlagsInherited) != 0; - } - - ///

Returns the flags for this ACE. - /// - /// Returns the flags for this ACE. The isInherited() - /// method checks the FLAGS_INHERITED bit in these flags. - /// - public virtual int GetFlags() - { - return Flags; - } - - /// - /// Returns the 'Apply To' text for inheritance of ACEs on - /// directories such as 'This folder, subfolder and files'. - /// - /// - /// Returns the 'Apply To' text for inheritance of ACEs on - /// directories such as 'This folder, subfolder and files'. For - /// files the text is always 'This object only'. - /// - public virtual string GetApplyToText() - { - switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly - )) - { - case unchecked(0x00): - { - return "This folder only"; - } - - case unchecked(0x03): - { - return "This folder, subfolders and files"; - } - - case unchecked(0x0B): - { - return "Subfolders and files only"; - } - - case unchecked(0x02): - { - return "This folder and subfolders"; - } - - case unchecked(0x0A): - { - return "Subfolders only"; - } - - case unchecked(0x01): - { - return "This folder and files"; - } - - case unchecked(0x09): - { - return "Files only"; - } - } - return "Invalid"; - } - - /// Returns the access mask accociated with this ACE. - /// - /// Returns the access mask accociated with this ACE. Use the - /// constants for FILE_READ_DATA, FILE_WRITE_DATA, - /// READ_CONTROL, GENERIC_ALL, etc with bitwise - /// operators to determine which bits of the mask are on or off. - /// - public virtual int GetAccessMask() - { - return Access; - } - - /// Return the SID associated with this ACE. - /// Return the SID associated with this ACE. - public virtual Sid GetSid() - { - return Sid; - } - - internal virtual int Decode(byte[] buf, int bi) - { - Allow = buf[bi++] == unchecked(unchecked(0x00)); - Flags = buf[bi++] & unchecked(0xFF); - int size = ServerMessageBlock.ReadInt2(buf, bi); - bi += 2; - Access = ServerMessageBlock.ReadInt4(buf, bi); - bi += 4; - Sid = new Sid(buf, bi); - return size; - } - - internal virtual void AppendCol(StringBuilder sb, string str, int width) - { - sb.Append(str); - int count = width - str.Length; - for (int i = 0; i < count; i++) - { - sb.Append(' '); - } - } - - /// Return a string represeting this ACE. - /// - /// Return a string represeting this ACE. - ///

- /// Note: This function should probably be changed to return SDDL - /// fragments but currently it does not. - /// - public override string ToString() - { - int count; - int i; - string str; - StringBuilder sb = new StringBuilder(); - sb.Append(IsAllow() ? "Allow " : "Deny "); - AppendCol(sb, Sid.ToDisplayString(), 25); - sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' '); - sb.Append(IsInherited() ? "Inherited " : "Direct "); - AppendCol(sb, GetApplyToText(), 34); - return sb.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs deleted file mode 100644 index 6ebe882930..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs +++ /dev/null @@ -1,25 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal interface IAllocInfo - { - long GetCapacity(); - - long GetFree(); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs deleted file mode 100644 index e78bff9d0a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/AndXServerMessageBlock.cs +++ /dev/null @@ -1,221 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal abstract class AndXServerMessageBlock : ServerMessageBlock - { - private const int AndxCommandOffset = 1; - - private const int AndxReservedOffset = 2; - - private const int AndxOffsetOffset = 3; - - private byte _andxCommand = unchecked(unchecked(0xFF)); - - private int _andxOffset; - - internal ServerMessageBlock Andx; - - public AndXServerMessageBlock() - { - } - - internal AndXServerMessageBlock(ServerMessageBlock andx) - { - if (andx != null) - { - this.Andx = andx; - _andxCommand = andx.Command; - } - } - - internal virtual int GetBatchLimit(byte command) - { - return 0; - } - - internal override int Encode(byte[] dst, int dstIndex) - { - int start = HeaderStart = dstIndex; - dstIndex += WriteHeaderWireFormat(dst, dstIndex); - dstIndex += WriteAndXWireFormat(dst, dstIndex); - Length = dstIndex - start; - if (Digest != null) - { - Digest.Sign(dst, HeaderStart, Length, this, Response); - } - return Length; - } - - internal override int Decode(byte[] buffer, int bufferIndex) - { - int start = HeaderStart = bufferIndex; - bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex); - bufferIndex += ReadAndXWireFormat(buffer, bufferIndex); - Length = bufferIndex - start; - return Length; - } - - internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2); - WordCount += 4; - // for command, reserved, and offset - dstIndex += WordCount + 1; - WordCount /= 2; - dst[start] = unchecked((byte)(WordCount & unchecked(0xFF))); - ByteCount = WriteBytesWireFormat(dst, dstIndex + 2); - dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF))); - dstIndex += ByteCount; - if (Andx == null || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command - )) - { - _andxCommand = unchecked(unchecked(0xFF)); - Andx = null; - dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF)); - dst[start + AndxReservedOffset] = unchecked(unchecked(0x00)); - // dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00; - // dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00; - dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde)); - dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde)); - // andx not used; return - return dstIndex - start; - } - Andx.BatchLevel = BatchLevel + 1; - dst[start + AndxCommandOffset] = _andxCommand; - dst[start + AndxReservedOffset] = unchecked(unchecked(0x00)); - _andxOffset = dstIndex - HeaderStart; - WriteInt2(_andxOffset, dst, start + AndxOffsetOffset); - Andx.UseUnicode = UseUnicode; - if (Andx is AndXServerMessageBlock) - { - Andx.Uid = Uid; - dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex - ); - } - else - { - // the andx smb is not of type andx so lets just write it here and - // were done. - int andxStart = dstIndex; - Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex); - dstIndex += Andx.WordCount + 1; - Andx.WordCount /= 2; - dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))); - Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2); - dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF))); - dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF) - )); - dstIndex += Andx.ByteCount; - } - return dstIndex - start; - } - - internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex) - { - int start = bufferIndex; - WordCount = buffer[bufferIndex++]; - if (WordCount != 0) - { - _andxCommand = buffer[bufferIndex]; - _andxOffset = ReadInt2(buffer, bufferIndex + 2); - if (_andxOffset == 0) - { - _andxCommand = unchecked(unchecked(0xFF)); - } - if (WordCount > 2) - { - ReadParameterWordsWireFormat(buffer, bufferIndex + 4); - if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended) - { - WordCount += 8; - } - } - bufferIndex = start + 1 + (WordCount * 2); - } - ByteCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if (ByteCount != 0) - { - int n; - n = ReadBytesWireFormat(buffer, bufferIndex); - bufferIndex += ByteCount; - } - if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF))) - { - _andxCommand = unchecked(unchecked(0xFF)); - Andx = null; - } - else - { - if (Andx == null) - { - _andxCommand = unchecked(unchecked(0xFF)); - throw new RuntimeException("no andx command supplied with response"); - } - bufferIndex = HeaderStart + _andxOffset; - Andx.HeaderStart = HeaderStart; - Andx.Command = _andxCommand; - Andx.ErrorCode = ErrorCode; - Andx.Flags = Flags; - Andx.Flags2 = Flags2; - Andx.Tid = Tid; - Andx.Pid = Pid; - Andx.Uid = Uid; - Andx.Mid = Mid; - Andx.UseUnicode = UseUnicode; - if (Andx is AndXServerMessageBlock) - { - bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer - , bufferIndex); - } - else - { - buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)) - ); - if (Andx.WordCount != 0) - { - if (Andx.WordCount > 2) - { - bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex); - } - } - Andx.ByteCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if (Andx.ByteCount != 0) - { - Andx.ReadBytesWireFormat(buffer, bufferIndex); - bufferIndex += Andx.ByteCount; - } - } - Andx.Received = true; - } - return bufferIndex - start; - } - - public override string ToString() - { - return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand - , 2) + ",andxOffset=" + _andxOffset; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs deleted file mode 100644 index b36816e269..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs +++ /dev/null @@ -1,80 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public class BufferCache - { - private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16 - ); - - internal static object[] Cache = new object[MaxBuffers]; - - private static int _freeBuffers; - - public static byte[] GetBuffer() - { - lock (Cache) - { - byte[] buf; - if (_freeBuffers > 0) - { - for (int i = 0; i < MaxBuffers; i++) - { - if (Cache[i] != null) - { - buf = (byte[])Cache[i]; - Cache[i] = null; - _freeBuffers--; - return buf; - } - } - } - buf = new byte[SmbComTransaction.TransactionBufSize]; - return buf; - } - } - - internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse - rsp) - { - lock (Cache) - { - req.TxnBuf = GetBuffer(); - rsp.TxnBuf = GetBuffer(); - } - } - - public static void ReleaseBuffer(byte[] buf) - { - lock (Cache) - { - if (_freeBuffers < MaxBuffers) - { - for (int i = 0; i < MaxBuffers; i++) - { - if (Cache[i] == null) - { - Cache[i] = buf; - _freeBuffers++; - return; - } - } - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs deleted file mode 100644 index 2f62e5b8d0..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs +++ /dev/null @@ -1,389 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - public class Dfs - { - internal class CacheEntry - { - internal long Expiration; - - internal Hashtable Map; - - internal CacheEntry(long ttl) - { - if (ttl == 0) - { - ttl = Ttl; - } - Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L; - Map = new Hashtable(); - } - } - - internal static LogStream Log = LogStream.GetInstance(); - - internal static readonly bool StrictView = Config.GetBoolean("jcifs.smb.client.dfs.strictView" - , false); - - internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300 - ); - - internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled" - , false); - - internal static CacheEntry FalseEntry = new CacheEntry(0L); - - internal CacheEntry Domains; - - internal CacheEntry Referrals; - - /// - public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth) - { - if (Disabled || auth.Domain == "?") - { - return null; - } - if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration) - { - Domains = null; - } - if (Domains != null) - { - return Domains.Map; - } - try - { - UniAddress addr = UniAddress.GetByName(auth.Domain, true); - SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0); - CacheEntry entry = new CacheEntry(Ttl * 10L); - DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0); - if (dr != null) - { - DfsReferral start = dr; - do - { - string domain = dr.Server.ToLower(); - entry.Map.Put(domain, new Hashtable()); - dr = dr.Next; - } - while (dr != start); - Domains = entry; - return Domains.Map; - } - } - catch (IOException ioe) - { - if (Log.Level >= 3) - { - Runtime.PrintStackTrace(ioe, Log); - } - if (StrictView && ioe is SmbAuthException) - { - throw (SmbAuthException)ioe; - } - } - return null; - } - - /// - public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth - ) - { - Hashtable domains = GetTrustedDomains(auth); - if (domains == null) - { - return false; - } - domain = domain.ToLower(); - return domains.Get(domain) != null; - } - - /// - public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth) - { - if (Disabled) - { - return null; - } - try - { - UniAddress addr = UniAddress.GetByName(domain, true); - SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0); - DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1); - if (dr != null) - { - DfsReferral start = dr; - IOException e = null; - do - { - try - { - addr = UniAddress.GetByName(dr.Server); - return SmbTransport.GetSmbTransport(addr, 0); - } - catch (IOException ioe) - { - e = ioe; - } - dr = dr.Next; - } - while (dr != start); - throw e; - } - } - catch (IOException ioe) - { - if (Log.Level >= 3) - { - Runtime.PrintStackTrace(ioe, Log); - } - if (StrictView && ioe is SmbAuthException) - { - throw (SmbAuthException)ioe; - } - } - return null; - } - - /// - public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string - root, string path, NtlmPasswordAuthentication auth) - { - if (Disabled) - { - return null; - } - try - { - string p = "\\" + domain + "\\" + root; - if (path != null) - { - p += path; - } - DfsReferral dr = trans.GetDfsReferrals(auth, p, 0); - if (dr != null) - { - return dr; - } - } - catch (IOException ioe) - { - if (Log.Level >= 4) - { - Runtime.PrintStackTrace(ioe, Log); - } - if (StrictView && ioe is SmbAuthException) - { - throw (SmbAuthException)ioe; - } - } - return null; - } - - /// - public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication - auth) - { - lock (this) - { - DfsReferral dr = null; - long now = Runtime.CurrentTimeMillis(); - if (Disabled || root.Equals("IPC$")) - { - return null; - } - Hashtable domains = GetTrustedDomains(auth); - if (domains != null) - { - domain = domain.ToLower(); - Hashtable roots = (Hashtable)domains.Get(domain); - if (roots != null) - { - SmbTransport trans = null; - root = root.ToLower(); - CacheEntry links = (CacheEntry)roots.Get(root); - if (links != null && now > links.Expiration) - { - //Sharpen.Collections.Remove(roots, root); - roots.Remove(root); - links = null; - } - if (links == null) - { - if ((trans = GetDc(domain, auth)) == null) - { - return null; - } - dr = GetReferral(trans, domain, root, path, auth); - if (dr != null) - { - int len = 1 + domain.Length + 1 + root.Length; - links = new CacheEntry(0L); - DfsReferral tmp = dr; - do - { - if (path == null) - { - // TODO: fix this - //tmp.map = links.map; - tmp.Key = "\\"; - } - tmp.PathConsumed -= len; - tmp = tmp.Next; - } - while (tmp != dr); - if (dr.Key != null) - { - links.Map.Put(dr.Key, dr); - } - roots.Put(root, links); - } - else - { - if (path == null) - { - roots.Put(root, FalseEntry); - } - } - } - else - { - if (links == FalseEntry) - { - links = null; - } - } - if (links != null) - { - string link = "\\"; - dr = (DfsReferral)links.Map.Get(link); - if (dr != null && now > dr.Expiration) - { - //Sharpen.Collections.Remove(links.map, link); - links.Map.Remove(link); - dr = null; - } - if (dr == null) - { - if (trans == null) - { - if ((trans = GetDc(domain, auth)) == null) - { - return null; - } - } - dr = GetReferral(trans, domain, root, path, auth); - if (dr != null) - { - dr.PathConsumed -= 1 + domain.Length + 1 + root.Length; - dr.Link = link; - links.Map.Put(link, dr); - } - } - } - } - } - if (dr == null && path != null) - { - if (Referrals != null && now > Referrals.Expiration) - { - Referrals = null; - } - if (Referrals == null) - { - Referrals = new CacheEntry(0); - } - string key = "\\" + domain + "\\" + root; - if (path.Equals("\\") == false) - { - key += path; - } - key = key.ToLower(); - //ListIterator iter = new ListIterator(referrals.map.Keys.GetEnumerator(), 0); - foreach (var current in Referrals.Map.Keys) - { - string _key = (string)current; - int klen = _key.Length; - bool match = false; - if (klen == key.Length) - { - match = _key.Equals(key); - } - else - { - if (klen < key.Length) - { - match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\'; - } - } - if (match) - { - dr = (DfsReferral)Referrals.Map.Get(_key); - } - } - } - return dr; - } - } - - internal virtual void Insert(string path, DfsReferral dr) - { - lock (this) - { - int s1; - int s2; - string server; - string share; - string key; - if (Disabled) - { - return; - } - s1 = path.IndexOf('\\', 1); - s2 = path.IndexOf('\\', s1 + 1); - server = Runtime.Substring(path, 1, s1); - share = Runtime.Substring(path, s1 + 1, s2); - key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower(); - int ki = key.Length; - while (ki > 1 && key[ki - 1] == '\\') - { - ki--; - } - if (ki < key.Length) - { - key = Runtime.Substring(key, 0, ki); - } - dr.PathConsumed -= 1 + server.Length + 1 + share.Length; - if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration) - { - Referrals = null; - } - if (Referrals == null) - { - Referrals = new CacheEntry(0); - } - Referrals.Map.Put(key, dr); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs deleted file mode 100644 index 3b6091f73c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs +++ /dev/null @@ -1,67 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.Collections.Generic; - -namespace SharpCifs.Smb -{ - - public class DfsReferral : SmbException - { - public int PathConsumed; - - public long Ttl; - - public string Server; - - public string Share; - - public string Link; - - public string Path; - - public bool ResolveHashes; - - public long Expiration; - - internal DfsReferral Next; - - internal IDictionary Map; - - internal string Key = null; - - public DfsReferral() - { - // Server - // Share - // Path relative to tree from which this referral was thrown - Next = this; - } - - internal virtual void Append(DfsReferral dr) - { - dr.Next = Next; - Next = dr; - } - - public override string ToString() - { - return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share=" - + Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" + - Expiration + ",resolveHashes=" + ResolveHashes + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs deleted file mode 100644 index d89e5bafac..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs +++ /dev/null @@ -1,64 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public static class DosError - { - public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked( - (int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)( - 0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a - )) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) }, - new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked( - 0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked( - (int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)( - 0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2 - )) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) }, - new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked( - 0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked( - (int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)( - 0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc - )) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) }, - new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked( - 0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked( - (int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)( - 0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035 - )) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) }, - new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked( - 0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked( - (int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)( - 0xC0000071)) } }; - - public static string[] DosErrorMessages = { "The operation completed successfully." - , "Incorrect function.", "Incorrect function.", "The system cannot find the file specified." - , "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function." - , "Access is denied.", "The TID specified was invalid.", "The handle is invalid." - , "The network name cannot be found.", "Not enough storage is available to process this command." - , "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning." - , "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process." - , "The process cannot access the file because it is being used by another process." - , "The process cannot access the file because another process has locked a portion of the file." - , "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found." - , "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session." - , "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended." - , "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty." - , "Cannot create a file when that file already exists.", "All pipe instances are busy." - , "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available." - , "This user account has expired.", "The user is not allowed to log on from this workstation." - , "The user is not allowed to log on at this time.", "The password of this user has expired." - }; - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs deleted file mode 100644 index bbf7882c8e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/DosFileFilter.cs +++ /dev/null @@ -1,37 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public class DosFileFilter : ISmbFileFilter - { - protected internal string Wildcard; - - protected internal int Attributes; - - public DosFileFilter(string wildcard, int attributes) - { - this.Wildcard = wildcard; - this.Attributes = attributes; - } - - /// - public virtual bool Accept(SmbFile file) - { - return (file.GetAttributes() & Attributes) != 0; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs deleted file mode 100644 index bbf3e7cc41..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs +++ /dev/null @@ -1,33 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public interface IFileEntry - { - string GetName(); - - int GetType(); - - int GetAttributes(); - - long CreateTime(); - - long LastModified(); - - long Length(); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs deleted file mode 100644 index b0e40c5cdc..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal interface IInfo - { - int GetAttributes(); - - long GetCreateTime(); - - long GetLastWriteTime(); - - long GetSize(); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs deleted file mode 100644 index b4a02d8c36..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs +++ /dev/null @@ -1,122 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class NetServerEnum2 : SmbComTransaction - { - internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF)); - - internal const int SvTypeDomainEnum = unchecked((int)(0x80000000)); - - internal static readonly string[] Descr = { "WrLehDO\u0000B16BBDz\u0000" - , "WrLehDz\u0000B16BBDz\u0000" }; - - internal string Domain; - - internal string LastName; - - internal int ServerTypes; - - internal NetServerEnum2(string domain, int serverTypes) - { - this.Domain = domain; - this.ServerTypes = serverTypes; - Command = SmbComTransaction; - SubCommand = NetServerEnum2; - // not really true be used by upper logic - Name = "\\PIPE\\LANMAN"; - MaxParameterCount = 8; - MaxDataCount = 16384; - MaxSetupCount = unchecked(unchecked(0x00)); - SetupCount = 0; - Timeout = 5000; - } - - internal override void Reset(int key, string lastName) - { - base.Reset(); - this.LastName = lastName; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - byte[] descr; - int which = SubCommand == NetServerEnum2 ? 0 : 1; - try - { - descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII"); - } - catch (UnsupportedEncodingException) - { - return 0; - } - WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex); - dstIndex += 2; - Array.Copy(descr, 0, dst, dstIndex, descr.Length); - dstIndex += descr.Length; - WriteInt2(unchecked(0x0001), dst, dstIndex); - dstIndex += 2; - WriteInt2(MaxDataCount, dst, dstIndex); - dstIndex += 2; - WriteInt4(ServerTypes, dst, dstIndex); - dstIndex += 4; - dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false); - if (which == 1) - { - dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false); - } - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes=" - + (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs deleted file mode 100644 index 9a0e5e3d57..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2Response.cs +++ /dev/null @@ -1,157 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class NetServerEnum2Response : SmbComTransactionResponse - { - internal class ServerInfo1 : IFileEntry - { - internal string Name; - - internal int VersionMajor; - - internal int VersionMinor; - - internal int Type; - - internal string CommentOrMasterBrowser; - - public virtual string GetName() - { - return Name; - } - - public new virtual int GetType() - { - return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup : - SmbFile.TypeServer; - } - - public virtual int GetAttributes() - { - return SmbFile.AttrReadonly | SmbFile.AttrDirectory; - } - - public virtual long CreateTime() - { - return 0L; - } - - public virtual long LastModified() - { - return 0L; - } - - public virtual long Length() - { - return 0L; - } - - public override string ToString() - { - return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString - (Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]"; - } - - internal ServerInfo1(NetServerEnum2Response enclosing) - { - this._enclosing = enclosing; - } - - private readonly NetServerEnum2Response _enclosing; - } - - private int _converter; - - private int _totalAvailableEntries; - - internal string LastName; - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - int start = bufferIndex; - Status = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _converter = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - NumEntries = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _totalAvailableEntries = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - return bufferIndex - start; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - ServerInfo1 e = null; - Results = new ServerInfo1[NumEntries]; - for (int i = 0; i < NumEntries; i++) - { - Results[i] = e = new ServerInfo1(this); - e.Name = ReadString(buffer, bufferIndex, 16, false); - bufferIndex += 16; - e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF); - e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF); - e.Type = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - int off = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - off = (off & unchecked(0xFFFF)) - _converter; - off = start + off; - e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false); - if (Log.Level >= 4) - { - Log.WriteLine(e); - } - } - LastName = NumEntries == 0 ? null : e.Name; - return bufferIndex - start; - } - - public override string ToString() - { - return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status - + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries=" - + _totalAvailableEntries + ",lastName=" + LastName + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs deleted file mode 100644 index 1b0c6f9315..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs +++ /dev/null @@ -1,95 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class NetShareEnum : SmbComTransaction - { - private static readonly string Descr = "WrLeh\u0000B13BWz\u0000"; - - public NetShareEnum() - { - Command = SmbComTransaction; - SubCommand = NetShareEnum; - // not really true be used by upper logic - Name ="\\PIPE\\LANMAN"; - MaxParameterCount = 8; - // maxDataCount = 4096; why was this set? - MaxSetupCount = 0x00; - SetupCount = 0; - Timeout = 5000; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - byte[] descr; - try - { - //descr = Runtime.GetBytesForString(Descr, "ASCII"); - descr = Runtime.GetBytesForString(Descr, "UTF-8"); - } - catch (UnsupportedEncodingException) - { - return 0; - } - WriteInt2(NetShareEnum, dst, dstIndex); - dstIndex += 2; - Array.Copy(descr, 0, dst, dstIndex, descr.Length); - dstIndex += descr.Length; - WriteInt2(unchecked(0x0001), dst, dstIndex); - dstIndex += 2; - WriteInt2(MaxDataCount, dst, dstIndex); - dstIndex += 2; - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "NetShareEnum[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs deleted file mode 100644 index 408f8e4d16..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnumResponse.cs +++ /dev/null @@ -1,94 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class NetShareEnumResponse : SmbComTransactionResponse - { - private int _converter; - - private int _totalAvailableEntries; - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - int start = bufferIndex; - Status = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _converter = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - NumEntries = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _totalAvailableEntries = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - return bufferIndex - start; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - SmbShareInfo e; - UseUnicode = false; - Results = new SmbShareInfo[NumEntries]; - for (int i = 0; i < NumEntries; i++) - { - Results[i] = e = new SmbShareInfo(); - e.NetName = ReadString(buffer, bufferIndex, 13, false); - bufferIndex += 14; - e.Type = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - int off = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - off = (off & unchecked(0xFFFF)) - _converter; - off = start + off; - e.Remark = ReadString(buffer, off, 128, false); - if (Log.Level >= 4) - { - Log.WriteLine(e); - } - } - return bufferIndex - start; - } - - public override string ToString() - { - return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status - + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries=" - + _totalAvailableEntries + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs deleted file mode 100644 index 511e7ae84f..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs +++ /dev/null @@ -1,202 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public static class NtStatus - { - public const int NtStatusOk = unchecked(0x00000000); - - public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001)); - - public const int NtStatusNotImplemented = unchecked((int)(0xC0000002)); - - public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003)); - - public const int NtStatusAccessViolation = unchecked((int)(0xC0000005)); - - public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008)); - - public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d)); - - public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e)); - - public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f)); - - public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016) - ); - - public const int NtStatusAccessDenied = unchecked((int)(0xC0000022)); - - public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023)); - - public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033)); - - public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034)); - - public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035)); - - public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037)); - - public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039)); - - public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a)); - - public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b)); - - public const int NtStatusSharingViolation = unchecked((int)(0xC0000043)); - - public const int NtStatusDeletePending = unchecked((int)(0xC0000056)); - - public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e)); - - public const int NtStatusUserExists = unchecked((int)(0xC0000063)); - - public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064)); - - public const int NtStatusWrongPassword = unchecked((int)(0xC000006a)); - - public const int NtStatusLogonFailure = unchecked((int)(0xC000006d)); - - public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e)); - - public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f)); - - public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070)); - - public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071)); - - public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072)); - - public const int NtStatusNoneMapped = unchecked((int)(0xC0000073)); - - public const int NtStatusInvalidSid = unchecked((int)(0xC0000078)); - - public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab)); - - public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac)); - - public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad)); - - public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae)); - - public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0)); - - public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1)); - - public const int NtStatusPipeListening = unchecked((int)(0xC00000b3)); - - public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba)); - - public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd)); - - public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9)); - - public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca)); - - public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc)); - - public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0)); - - public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da)); - - public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df)); - - public const int NtStatusNotADirectory = unchecked((int)(0xC0000103)); - - public const int NtStatusCannotDelete = unchecked((int)(0xC0000121)); - - public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122)); - - public const int NtStatusPipeBroken = unchecked((int)(0xC000014b)); - - public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151)); - - public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b)); - - public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b)); - - public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c)); - - public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199 - )); - - public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224)); - - public const int NtStatusNotFound = unchecked((int)(0xC0000225)); - - public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234)); - - public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257)); - - public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279 - )); - - public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful - , NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation - , NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice - , NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied - , NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound - , NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid - , NtStatusObjectPathNotFound, NtStatusObjectPathSyntaxBad, NtStatusSharingViolation - , NtStatusDeletePending, NtStatusNoLogonServers, NtStatusUserExists, NtStatusNoSuchUser - , NtStatusWrongPassword, NtStatusLogonFailure, NtStatusAccountRestriction - , NtStatusInvalidLogonHours, NtStatusInvalidWorkstation, NtStatusPasswordExpired - , NtStatusAccountDisabled, NtStatusNoneMapped, NtStatusInvalidSid, NtStatusInstanceNotAvailable - , NtStatusPipeNotAvailable, NtStatusInvalidPipeState, NtStatusPipeBusy - , NtStatusPipeDisconnected, NtStatusPipeClosing, NtStatusPipeListening, - NtStatusFileIsADirectory, NtStatusDuplicateName, NtStatusNetworkNameDeleted - , NtStatusNetworkAccessDenied, NtStatusBadNetworkName, NtStatusRequestNotAccepted - , NtStatusCantAccessDomainInfo, NtStatusNoSuchDomain, NtStatusNotADirectory - , NtStatusCannotDelete, NtStatusInvalidComputerName, NtStatusPipeBroken - , NtStatusNoSuchAlias, NtStatusLogonTypeNotGranted, NtStatusNoTrustSamAccount - , NtStatusTrustedDomainFailure, NtStatusNologonWorkstationTrustAccount, - NtStatusPasswordMustChange, NtStatusNotFound, NtStatusAccountLockedOut - , NtStatusPathNotCovered, NtStatusIoReparseTagNotHandled }; - - public static string[] NtStatusMessages = { "The operation completed successfully." - , "A device attached to the system is not functioning.", "Incorrect function.", - "The parameter is incorrect.", "Invalid access to memory location.", "The handle is invalid." - , "The parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified." - , "More data is available.", "Access is denied.", "The data area passed to a system call is too small." - , "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified." - , "Cannot create a file when that file already exists.", "The handle is invalid." - , "The specified path is invalid.", "The system cannot find the path specified." - , "The specified path is invalid.", "The process cannot access the file because it is being used by another process." - , "Access is denied.", "There are currently no logon servers available to service the logon request." - , "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct." - , "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction." - , "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer." - , "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled." - , "No mapping between account names and security IDs was done.", "The security ID structure is invalid." - , "All pipe instances are busy.", "All pipe instances are busy.", "The pipe state is invalid." - , "All pipe instances are busy.", "No process is on the other end of the pipe.", - "The pipe is being closed.", "Waiting for a process to open the other end of the pipe." - , "Access is denied.", "A duplicate name exists on the network.", "The specified network name is no longer available." - , "Network access is denied.", "The network name cannot be found.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept." - , "Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved." - , "The specified domain did not exist.", "The directory name is invalid.", "Access is denied." - , "The format of the specified computer name is invalid.", "The pipe has been ended." - , "The specified local group does not exist.", "Logon failure: the user has not been granted the requested logon type at this computer." - , "The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship." - , "The trust relationship between the primary domain and the trusted domain failed." - , "The account used is a Computer Account. Use your global user account or local user account to access this server." - , "The user must change his password before he logs on the first time.", "NT_STATUS_NOT_FOUND" - , "The referenced account is currently locked out and may not be logged on to.", - "The remote system is not reachable by the transport.", "NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED" - }; - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs deleted file mode 100644 index 6a83543b16..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDesc.cs +++ /dev/null @@ -1,88 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class NtTransQuerySecurityDesc : SmbComNtTransaction - { - internal int Fid; - - internal int SecurityInformation; - - internal NtTransQuerySecurityDesc(int fid, int securityInformation) - { - this.Fid = fid; - this.SecurityInformation = securityInformation; - Command = SmbComNtTransact; - Function = NtTransactQuerySecurityDesc; - SetupCount = 0; - TotalDataCount = 0; - MaxParameterCount = 4; - MaxDataCount = 32768; - MaxSetupCount = unchecked(unchecked(0x00)); - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(Fid, dst, dstIndex); - dstIndex += 2; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved - WriteInt4(SecurityInformation, dst, dstIndex); - dstIndex += 4; - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump - .ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation - , 8) + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs deleted file mode 100644 index 9365d51542..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtTransQuerySecurityDescResponse.cs +++ /dev/null @@ -1,78 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse - { - internal SecurityDescriptor SecurityDescriptor; - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - Length = ReadInt4(buffer, bufferIndex); - return 4; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - if (ErrorCode != 0) - { - return 4; - } - try - { - SecurityDescriptor = new SecurityDescriptor(); - bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len); - } - catch (IOException ioe) - { - throw new RuntimeException(ioe.Message); - } - return bufferIndex - start; - } - - public override string ToString() - { - return "NtTransQuerySecurityResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs deleted file mode 100644 index 853364f8ef..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmAuthenticator.cs +++ /dev/null @@ -1,93 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - /// This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. - /// - /// This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read jCIFS Exceptions and NtlmAuthenticator for complete details. - /// - public abstract class NtlmAuthenticator - { - private static NtlmAuthenticator _auth; - - private string _url; - - private SmbAuthException _sae; - - private void Reset() - { - _url = null; - _sae = null; - } - - /// Set the default NtlmAuthenticator. - /// Set the default NtlmAuthenticator. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect. - /// - public static void SetDefault(NtlmAuthenticator a) - { - lock (typeof(NtlmAuthenticator)) - { - if (_auth != null) - { - return; - } - _auth = a; - } - } - - protected internal string GetRequestingUrl() - { - return _url; - } - - protected internal SmbAuthException GetRequestingException() - { - return _sae; - } - - /// Used internally by jCIFS when an SmbAuthException is trapped to retrieve new user credentials. - /// - /// Used internally by jCIFS when an SmbAuthException is trapped to retrieve new user credentials. - /// - public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string - url, SmbAuthException sae) - { - if (_auth == null) - { - return null; - } - lock (_auth) - { - _auth._url = url; - _auth._sae = sae; - return _auth.GetNtlmPasswordAuthentication(); - } - } - - /// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the getRequestingURL and getRequestingException methods. - /// - /// - /// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the getRequestingURL and getRequestingException methods. - /// If this method returns null the SmbAuthException that triggered the authenticator check will simply be rethrown. The default implementation returns null. - /// - protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication - () - { - return null; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs deleted file mode 100644 index 745b1f6639..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmChallenge.cs +++ /dev/null @@ -1,40 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - - public sealed class NtlmChallenge - { - public byte[] Challenge; - - public UniAddress Dc; - - internal NtlmChallenge(byte[] challenge, UniAddress dc) - { - this.Challenge = challenge; - this.Dc = dc; - } - - public override string ToString() - { - return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge - .Length * 2) + ",dc=" + Dc + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs deleted file mode 100644 index aa52ee1db8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs +++ /dev/null @@ -1,206 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Ntlmssp; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - /// For initiating NTLM authentication (including NTLMv2). - /// For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication. - /// - public class NtlmContext - { - internal NtlmPasswordAuthentication Auth; - - internal int NtlmsspFlags; - - internal string Workstation; - - internal bool isEstablished; - - internal byte[] ServerChallenge; - - internal byte[] SigningKey; - - internal string NetbiosName = null; - - internal int State = 1; - - internal LogStream Log; - - public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning) - { - this.Auth = auth; - NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2 - | NtlmFlags.NtlmsspNegotiate128; - if (doSigning) - { - NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign - | NtlmFlags.NtlmsspNegotiateKeyExch; - } - Workstation = Type1Message.GetDefaultWorkstation(); - Log = LogStream.GetInstance(); - } - - public override string ToString() - { - string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString - (NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished - + ",state=" + State + ",serverChallenge="; - if (ServerChallenge == null) - { - ret += "null"; - } - else - { - ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2); - } - ret += ",signingKey="; - if (SigningKey == null) - { - ret += "null"; - } - else - { - ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2); - } - ret += "]"; - return ret; - } - - public virtual bool IsEstablished() - { - return isEstablished; - } - - public virtual byte[] GetServerChallenge() - { - return ServerChallenge; - } - - public virtual byte[] GetSigningKey() - { - return SigningKey; - } - - public virtual string GetNetbiosName() - { - return NetbiosName; - } - - private string GetNtlmsspListItem(byte[] type2Token, int id0) - { - int ri = 58; - for (; ; ) - { - int id = Encdec.Dec_uint16le(type2Token, ri); - int len = Encdec.Dec_uint16le(type2Token, ri + 2); - ri += 4; - if (id == 0 || (ri + len) > type2Token.Length) - { - break; - } - if (id == id0) - { - try - { - return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding - ); - } - catch (UnsupportedEncodingException) - { - break; - } - } - ri += len; - } - return null; - } - - /// - public virtual byte[] InitSecContext(byte[] token, int offset, int len) - { - switch (State) - { - case 1: - { - Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation); - token = msg1.ToByteArray(); - if (Log.Level >= 4) - { - Log.WriteLine(msg1); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, token, 0, token.Length); - } - } - State++; - break; - } - - case 2: - { - try - { - Type2Message msg2 = new Type2Message(token); - if (Log.Level >= 4) - { - Log.WriteLine(msg2); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, token, 0, token.Length); - } - } - ServerChallenge = msg2.GetChallenge(); - NtlmsspFlags &= msg2.GetFlags(); - // netbiosName = getNtlmsspListItem(token, 0x0001); - Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(), - Auth.GetUsername(), Workstation, NtlmsspFlags); - token = msg3.ToByteArray(); - if (Log.Level >= 4) - { - Log.WriteLine(msg3); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, token, 0, token.Length); - } - } - if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0) - { - SigningKey = msg3.GetMasterKey(); - } - isEstablished = true; - State++; - break; - } - catch (Exception e) - { - throw new SmbException(e.Message, e); - } - } - - default: - { - throw new SmbException("Invalid state"); - } - } - return token; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs deleted file mode 100644 index ec3899fe9b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmPasswordAuthentication.cs +++ /dev/null @@ -1,807 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - /// This class stores and encrypts NTLM user credentials. - /// - /// This class stores and encrypts NTLM user credentials. The default - /// credentials are retrieved from the jcifs.smb.client.domain, - /// jcifs.smb.client.username, and jcifs.smb.client.password - /// properties. - ///

- /// Read jCIFS Exceptions and - /// NtlmAuthenticator for related information. - /// - - public sealed class NtlmPasswordAuthentication : Principal - { - private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility" - , 3); - - private static readonly Random Random = new Random(); - - private static LogStream _log = LogStream.GetInstance(); - - private static readonly byte[] S8 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) }; - - // KGS!@#$% - private static void E(byte[] key, byte[] data, byte[] e) - { - byte[] key7 = new byte[7]; - byte[] e8 = new byte[8]; - for (int i = 0; i < key.Length / 7; i++) - { - Array.Copy(key, i * 7, key7, 0, 7); - DES des = new DES(key7); - des.Encrypt(data, e8); - Array.Copy(e8, 0, e, i * 8, 8); - } - } - - internal static string DefaultDomain; - - internal static string DefaultUsername; - - internal static string DefaultPassword; - - internal static readonly string Blank = string.Empty; - - public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication - (string.Empty, string.Empty, string.Empty); - - internal static void InitDefaults() - { - if (DefaultDomain != null) - { - return; - } - DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", "?"); - DefaultUsername = Config.GetProperty("jcifs.smb.client.username", "GUEST"); - DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank); - } - - ///

Generate the ANSI DES hash for the password associated with these credentials. - /// - /// Generate the ANSI DES hash for the password associated with these credentials. - /// - public static byte[] GetPreNtlmResponse(string password, byte[] challenge) - { - byte[] p14 = new byte[14]; - byte[] p21 = new byte[21]; - byte[] p24 = new byte[24]; - byte[] passwordBytes; - try - { - passwordBytes = Runtime.GetBytesForString(password.ToUpper(), SmbConstants.OemEncoding); - } - catch (UnsupportedEncodingException uee) - { - throw new RuntimeException("Try setting jcifs.encoding=US-ASCII", uee); - } - int passwordLength = passwordBytes.Length; - // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM - if (passwordLength > 14) - { - passwordLength = 14; - } - Array.Copy(passwordBytes, 0, p14, 0, passwordLength); - E(p14, S8, p21); - E(p21, challenge, p24); - return p24; - } - - /// Generate the Unicode MD4 hash for the password associated with these credentials. - /// - /// Generate the Unicode MD4 hash for the password associated with these credentials. - /// - public static byte[] GetNtlmResponse(string password, byte[] challenge) - { - byte[] uni = null; - byte[] p21 = new byte[21]; - byte[] p24 = new byte[24]; - try - { - uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding); - } - catch (UnsupportedEncodingException uee) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(uee, _log); - } - } - Md4 md4 = new Md4(); - md4.Update(uni); - try - { - md4.Digest(p21, 0, 16); - } - catch (Exception ex) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(ex, _log); - } - } - E(p21, challenge, p24); - return p24; - } - - /// Creates the LMv2 response for the supplied information. - /// Creates the LMv2 response for the supplied information. - /// The domain in which the username exists. - /// The username. - /// The user's password. - /// The server challenge. - /// The client challenge (nonce). - public static byte[] GetLMv2Response(string domain, string user, string password, - byte[] challenge, byte[] clientChallenge) - { - try - { - byte[] hash = new byte[16]; - byte[] response = new byte[24]; - // The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password - Md4 md4 = new Md4(); - md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding) - ); - Hmact64 hmac = new Hmact64(md4.Digest()); - hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding - )); - hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding - )); - hmac = new Hmact64(hmac.Digest()); - hmac.Update(challenge); - hmac.Update(clientChallenge); - hmac.Digest(response, 0, 16); - Array.Copy(clientChallenge, 0, response, 16, 8); - return response; - } - catch (Exception ex) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(ex, _log); - } - return null; - } - } - - public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte - [] clientChallenge) - { - byte[] sessionHash = new byte[8]; - try - { - MessageDigest md5; - md5 = MessageDigest.GetInstance("MD5"); - md5.Update(serverChallenge); - md5.Update(clientChallenge, 0, 8); - Array.Copy(md5.Digest(), 0, sessionHash, 0, 8); - } - catch (Exception gse) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(gse, _log); - } - throw new RuntimeException("MD5", gse); - } - byte[] key = new byte[21]; - Array.Copy(nTowFv1, 0, key, 0, 16); - byte[] ntResponse = new byte[24]; - E(key, sessionHash, ntResponse); - return ntResponse; - } - - public static byte[] NtowFv1(string password) - { - if (password == null) - { - throw new RuntimeException("Password parameter is required"); - } - try - { - Md4 md4 = new Md4(); - md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding) - ); - return md4.Digest(); - } - catch (UnsupportedEncodingException uee) - { - throw new RuntimeException(uee.Message); - } - } - - public static byte[] NtowFv2(string domain, string username, string password) - { - try - { - Md4 md4 = new Md4(); - md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding) - ); - Hmact64 hmac = new Hmact64(md4.Digest()); - hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding - )); - hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding)); - return hmac.Digest(); - } - catch (UnsupportedEncodingException uee) - { - throw new RuntimeException(uee.Message); - } - } - - internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge - , byte[] clientData, int offset, int length) - { - Hmact64 hmac = new Hmact64(responseKey); - hmac.Update(serverChallenge); - hmac.Update(clientData, offset, length); - byte[] mac = hmac.Digest(); - byte[] ret = new byte[mac.Length + clientData.Length]; - Array.Copy(mac, 0, ret, 0, mac.Length); - Array.Copy(clientData, 0, ret, mac.Length, clientData.Length); - return ret; - } - - public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge - , byte[] clientChallenge) - { - return ComputeResponse(responseKeyLm, serverChallenge - , clientChallenge, 0, clientChallenge.Length); - } - - public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge - , byte[] clientChallenge, long nanos1601, byte[] targetInfo) - { - int targetInfoLength = targetInfo != null ? targetInfo.Length : 0; - byte[] temp = new byte[28 + targetInfoLength + 4]; - Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0); - // Header - Encdec.Enc_uint32le(unchecked(0x00000000), temp, 4); - // Reserved - Encdec.Enc_uint64le(nanos1601, temp, 8); - Array.Copy(clientChallenge, 0, temp, 16, 8); - Encdec.Enc_uint32le(unchecked(0x00000000), temp, 24); - // Unknown - if (targetInfo != null) - { - Array.Copy(targetInfo, 0, temp, 28, targetInfoLength); - } - Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength); - // mystery bytes! - return ComputeResponse(responseKeyNt, serverChallenge - , temp, 0, temp.Length); - } - - internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication - (string.Empty, string.Empty, string.Empty); - - internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication - ("?", "GUEST", string.Empty); - - internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication - (null); - - internal string Domain; - - internal string Username; - - internal string Password; - - internal byte[] AnsiHash; - - internal byte[] UnicodeHash; - - internal bool HashesExternal; - - internal byte[] ClientChallenge; - - internal byte[] Challenge; - - /// - /// Create an NtlmPasswordAuthentication object from the userinfo - /// component of an SMB URL like "domain;user:pass". - /// - /// - /// Create an NtlmPasswordAuthentication object from the userinfo - /// component of an SMB URL like "domain;user:pass". This constructor - /// is used internally be jCIFS when parsing SMB URLs. - /// - public NtlmPasswordAuthentication(string userInfo) - { - Domain = Username = Password = null; - if (userInfo != null) - { - try - { - userInfo = Unescape(userInfo); - } - catch (UnsupportedEncodingException) - { - } - int i; - int u; - int end; - char c; - end = userInfo.Length; - for (i = 0, u = 0; i < end; i++) - { - c = userInfo[i]; - if (c == ';') - { - Domain = Runtime.Substring(userInfo, 0, i); - u = i + 1; - } - else - { - if (c == ':') - { - Password = Runtime.Substring(userInfo, i + 1); - break; - } - } - } - Username = Runtime.Substring(userInfo, u, i); - } - InitDefaults(); - if (Domain == null) - { - Domain = DefaultDomain; - } - if (Username == null) - { - Username = DefaultUsername; - } - if (Password == null) - { - Password = DefaultPassword; - } - } - - /// - /// Create an NtlmPasswordAuthentication object from a - /// domain, username, and password. - /// - /// - /// Create an NtlmPasswordAuthentication object from a - /// domain, username, and password. Parameters that are null - /// will be substituted with jcifs.smb.client.domain, - /// jcifs.smb.client.username, jcifs.smb.client.password - /// property values. - /// - public NtlmPasswordAuthentication(string domain, string username, string password - ) - { - int ci; - if (username != null) - { - ci = username.IndexOf('@'); - if (ci > 0) - { - domain = Runtime.Substring(username, ci + 1); - username = Runtime.Substring(username, 0, ci); - } - else - { - ci = username.IndexOf('\\'); - if (ci > 0) - { - domain = Runtime.Substring(username, 0, ci); - username = Runtime.Substring(username, ci + 1); - } - } - } - this.Domain = domain; - this.Username = username; - this.Password = password; - InitDefaults(); - if (domain == null) - { - this.Domain = DefaultDomain; - } - if (username == null) - { - this.Username = DefaultUsername; - } - if (password == null) - { - this.Password = DefaultPassword; - } - } - - /// - /// Create an NtlmPasswordAuthentication object with raw password - /// hashes. - /// - /// - /// Create an NtlmPasswordAuthentication object with raw password - /// hashes. This is used exclusively by the jcifs.http.NtlmSsp - /// class which is in turn used by NTLM HTTP authentication functionality. - /// - public NtlmPasswordAuthentication(string domain, string username, byte[] challenge - , byte[] ansiHash, byte[] unicodeHash) - { - if (domain == null || username == null || ansiHash == null || unicodeHash == null) - { - throw new ArgumentException("External credentials cannot be null"); - } - this.Domain = domain; - this.Username = username; - Password = null; - this.Challenge = challenge; - this.AnsiHash = ansiHash; - this.UnicodeHash = unicodeHash; - HashesExternal = true; - } - - /// Returns the domain. - /// Returns the domain. - public string GetDomain() - { - return Domain; - } - - /// Returns the username. - /// Returns the username. - public string GetUsername() - { - return Username; - } - - /// - /// Returns the password in plain text or null if the raw password - /// hashes were used to construct this NtlmPasswordAuthentication - /// object which will be the case when NTLM HTTP Authentication is - /// used. - /// - /// - /// Returns the password in plain text or null if the raw password - /// hashes were used to construct this NtlmPasswordAuthentication - /// object which will be the case when NTLM HTTP Authentication is - /// used. There is no way to retrieve a users password in plain text unless - /// it is supplied by the user at runtime. - /// - public string GetPassword() - { - return Password; - } - - /// - /// Return the domain and username in the format: - /// domain\\username. - /// - /// - /// Return the domain and username in the format: - /// domain\\username. This is equivalent to toString(). - /// - public new string GetName() - { - bool d = Domain.Length > 0 && Domain.Equals("?") == false; - return d ? Domain + "\\" + Username : Username; - } - - /// Computes the 24 byte ANSI password hash given the 8 byte server challenge. - /// - /// Computes the 24 byte ANSI password hash given the 8 byte server challenge. - /// - public byte[] GetAnsiHash(byte[] challenge) - { - if (HashesExternal) - { - return AnsiHash; - } - switch (LmCompatibility) - { - case 0: - case 1: - { - return GetPreNtlmResponse(Password, challenge); - } - - case 2: - { - return GetNtlmResponse(Password, challenge); - } - - case 3: - case 4: - case 5: - { - if (ClientChallenge == null) - { - ClientChallenge = new byte[8]; - Random.NextBytes(ClientChallenge); - } - return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge); - } - - default: - { - return GetPreNtlmResponse(Password, challenge); - } - } - } - - /// Computes the 24 byte Unicode password hash given the 8 byte server challenge. - /// - /// Computes the 24 byte Unicode password hash given the 8 byte server challenge. - /// - public byte[] GetUnicodeHash(byte[] challenge) - { - if (HashesExternal) - { - return UnicodeHash; - } - switch (LmCompatibility) - { - case 0: - case 1: - case 2: - { - return GetNtlmResponse(Password, challenge); - } - - case 3: - case 4: - case 5: - { - return new byte[0]; - } - - default: - { - return GetNtlmResponse(Password, challenge); - } - } - } - - /// - public byte[] GetSigningKey(byte[] challenge) - { - switch (LmCompatibility) - { - case 0: - case 1: - case 2: - { - byte[] signingKey = new byte[40]; - GetUserSessionKey(challenge, signingKey, 0); - Array.Copy(GetUnicodeHash(challenge), 0, signingKey, 16, 24); - return signingKey; - } - - case 3: - case 4: - case 5: - { - throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)" - ); - } - } - return null; - } - - /// Returns the effective user session key. - /// Returns the effective user session key. - /// The server challenge. - /// - /// A byte[] containing the effective user session key, - /// used in SMB MAC signing and NTLMSSP signing and sealing. - /// - public byte[] GetUserSessionKey(byte[] challenge) - { - if (HashesExternal) - { - return null; - } - byte[] key = new byte[16]; - try - { - GetUserSessionKey(challenge, key, 0); - } - catch (Exception ex) - { - if (_log.Level > 0) - { - Runtime.PrintStackTrace(ex, _log); - } - } - return key; - } - - /// Calculates the effective user session key. - /// Calculates the effective user session key. - /// The server challenge. - /// - /// The destination array in which the user session key will be - /// placed. - /// - /// - /// The offset in the destination array at which the - /// session key will start. - /// - /// - internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset) - { - if (HashesExternal) - { - return; - } - try - { - Md4 md4 = new Md4(); - md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding) - ); - switch (LmCompatibility) - { - case 0: - case 1: - case 2: - { - md4.Update(md4.Digest()); - md4.Digest(dest, offset, 16); - break; - } - - case 3: - case 4: - case 5: - { - if (ClientChallenge == null) - { - ClientChallenge = new byte[8]; - Random.NextBytes(ClientChallenge); - } - Hmact64 hmac = new Hmact64(md4.Digest()); - hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding - )); - hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding - )); - byte[] ntlmv2Hash = hmac.Digest(); - hmac = new Hmact64(ntlmv2Hash); - hmac.Update(challenge); - hmac.Update(ClientChallenge); - Hmact64 userKey = new Hmact64(ntlmv2Hash); - userKey.Update(hmac.Digest()); - userKey.Digest(dest, offset, 16); - break; - } - - default: - { - md4.Update(md4.Digest()); - md4.Digest(dest, offset, 16); - break; - } - } - } - catch (Exception e) - { - throw new SmbException(string.Empty, e); - } - } - - /// - /// Compares two NtlmPasswordAuthentication objects for - /// equality. - /// - /// - /// Compares two NtlmPasswordAuthentication objects for - /// equality. Two NtlmPasswordAuthentication objects are equal if - /// their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one NtlmPasswordAuthentication object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method. - /// - public override bool Equals(object obj) - { - if (obj is NtlmPasswordAuthentication) - { - NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication - )obj; - if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals - (Username.ToUpper())) - { - if (HashesExternal && ntlm.HashesExternal) - { - - return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm. - UnicodeHash); - } - if (!HashesExternal && Password.Equals(ntlm.Password)) - { - return true; - } - } - } - return false; - } - - /// Return the upcased username hash code. - /// Return the upcased username hash code. - public override int GetHashCode() - { - return GetName().ToUpper().GetHashCode(); - } - - /// - /// Return the domain and username in the format: - /// domain\\username. - /// - /// - /// Return the domain and username in the format: - /// domain\\username. This is equivalent to getName(). - /// - public override string ToString() - { - return GetName(); - } - - /// - /// - internal static string Unescape(string str) - { - char ch; - int i; - int j; - int state; - int len; - char[] @out; - byte[] b = new byte[1]; - if (str == null) - { - return null; - } - len = str.Length; - @out = new char[len]; - state = 0; - for (i = j = 0; i < len; i++) - { - switch (state) - { - case 0: - { - ch = str[i]; - if (ch == '%') - { - state = 1; - } - else - { - @out[j++] = ch; - } - break; - } - - case 1: - { - b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i, - i + 2), 16) & unchecked(0xFF))); - @out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0]; - i++; - state = 0; - break; - } - } - } - return new string(@out, 0, j); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs deleted file mode 100644 index 14a5479e31..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs +++ /dev/null @@ -1,28 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public class Principal - { - private string _name = ""; - - public string GetName() - { - return _name; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs deleted file mode 100644 index a6ad59fb1a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs +++ /dev/null @@ -1,900 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using SharpCifs.Dcerpc; -using SharpCifs.Dcerpc.Msrpc; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; -using Hashtable = SharpCifs.Util.Sharpen.Hashtable; //not System.Collections.Hashtable - -namespace SharpCifs.Smb -{ - /// - /// A Windows SID is a numeric identifier used to represent Windows - /// accounts. - /// - /// - /// A Windows SID is a numeric identifier used to represent Windows - /// accounts. SIDs are commonly represented using a textual format such as - /// S-1-5-21-1496946806-2192648263-3843101252-1029 but they may - /// also be resolved to yield the name of the associated Windows account - /// such as Administrators or MYDOM\alice. - ///

- /// Consider the following output of examples/SidLookup.java: - ///

-	/// toString: S-1-5-21-4133388617-793952518-2001621813-512
-	/// toDisplayString: WNET\Domain Admins
-	/// getType: 2
-	/// getTypeText: Domain group
-	/// getDomainName: WNET
-	/// getAccountName: Domain Admins
-	/// 
- ///
- public class Sid : Rpc.SidT - { - public const int SidTypeUseNone = Lsarpc.SidNameUseNone; - - public const int SidTypeUser = Lsarpc.SidNameUser; - - public const int SidTypeDomGrp = Lsarpc.SidNameDomGrp; - - public const int SidTypeDomain = Lsarpc.SidNameDomain; - - public const int SidTypeAlias = Lsarpc.SidNameAlias; - - public const int SidTypeWknGrp = Lsarpc.SidNameWknGrp; - - public const int SidTypeDeleted = Lsarpc.SidNameDeleted; - - public const int SidTypeInvalid = Lsarpc.SidNameInvalid; - - public const int SidTypeUnknown = Lsarpc.SidNameUnknown; - - internal static readonly string[] SidTypeNames = { "0", "User", "Domain group" - , "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" }; - - public const int SidFlagResolveSids = unchecked(0x0001); - - public static Sid Everyone; - - public static Sid CreatorOwner; - - public static Sid SYSTEM; - - static Sid() - { - try - { - Everyone = new Sid("S-1-1-0"); - CreatorOwner = new Sid("S-1-3-0"); - SYSTEM = new Sid("S-1-5-18"); - } - catch (SmbException) - { - } - } - - internal static Hashtable SidCache = new Hashtable(); - - /// - internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle - , Sid[] sids) - { - MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids); - handle.Sendrecv(rpc); - switch (rpc.Retval) - { - case 0: - case NtStatus.NtStatusNoneMapped: - case unchecked(0x00000107): - { - // NT_STATUS_SOME_NOT_MAPPED - break; - } - - default: - { - throw new SmbException(rpc.Retval, false); - } - } - for (int si = 0; si < sids.Length; si++) - { - sids[si].Type = rpc.Names.Names[si].SidType; - sids[si].DomainName = null; - switch (sids[si].Type) - { - case SidTypeUser: - case SidTypeDomGrp: - case SidTypeDomain: - case SidTypeAlias: - case SidTypeWknGrp: - { - int sidIndex = rpc.Names.Names[si].SidIndex; - Rpc.Unicode_string ustr = rpc.Domains.Domains[sidIndex].Name; - sids[si].DomainName = (new UnicodeString(ustr, false)).ToString(); - break; - } - } - sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString - (); - sids[si].OriginServer = null; - sids[si].OriginAuth = null; - } - } - - /// - internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication - auth, Sid[] sids) - { - DcerpcHandle handle = null; - LsaPolicyHandle policyHandle = null; - lock (SidCache) - { - try - { - handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]" - , auth); - string server = authorityServerName; - int dot = server.IndexOf('.'); - if (dot > 0 && char.IsDigit(server[0]) == false) - { - server = Runtime.Substring(server, 0, dot); - } - policyHandle = new LsaPolicyHandle(handle, "\\\\" + server, unchecked(0x00000800)); - ResolveSids(handle, policyHandle, sids); - } - finally - { - if (handle != null) - { - if (policyHandle != null) - { - policyHandle.Close(); - } - handle.Close(); - } - } - } - } - - /// - public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication - auth, Sid[] sids, int offset, int length) - { - List list = new List();//new List(sids.Length); - int si; - lock (SidCache) - { - for (si = 0; si < length; si++) - { - Sid sid = (Sid)SidCache.Get(sids[offset + si]); - if (sid != null) - { - sids[offset + si].Type = sid.Type; - sids[offset + si].DomainName = sid.DomainName; - sids[offset + si].AcctName = sid.AcctName; - } - else - { - list.Add(sids[offset + si]); - } - } - if (list.Count > 0) - { - //sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]); - sids = (Sid[])list.ToArray(); - ResolveSids0(authorityServerName, auth, sids); - for (si = 0; si < sids.Length; si++) - { - SidCache.Put(sids[si], sids[si]); - } - } - } - } - - /// Resolve an array of SIDs using a cache and at most one MSRPC request. - /// - /// Resolve an array of SIDs using a cache and at most one MSRPC request. - ///

- /// This method will attempt - /// to resolve SIDs using a cache and cache the results of any SIDs that - /// required resolving with the authority. SID cache entries are currently not - /// expired because under normal circumstances SID information never changes. - /// - /// The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority. - /// - /// The credentials that should be used to communicate with the named server. As usual, null indicates that default credentials should be used. - /// - /// The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the toDisplayString, getDomainName, and getAccountName methods. - /// - /// - public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication - auth, Sid[] sids) - { - List list = new List();//new List(sids.Length); - int si; - lock (SidCache) - { - for (si = 0; si < sids.Length; si++) - { - Sid sid = (Sid)SidCache.Get(sids[si]); - if (sid != null) - { - sids[si].Type = sid.Type; - sids[si].DomainName = sid.DomainName; - sids[si].AcctName = sid.AcctName; - } - else - { - list.Add(sids[si]); - } - } - if (list.Count > 0) - { - //sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]); - sids = (Sid[]) list.ToArray(); - ResolveSids0(authorityServerName, auth, sids); - for (si = 0; si < sids.Length; si++) - { - SidCache.Put(sids[si], sids[si]); - } - } - } - } - - /// - public static Sid GetServerSid(string server, NtlmPasswordAuthentication - auth) - { - DcerpcHandle handle = null; - LsaPolicyHandle policyHandle = null; - Lsarpc.LsarDomainInfo info = new Lsarpc.LsarDomainInfo(); - MsrpcQueryInformationPolicy rpc; - lock (SidCache) - { - try - { - handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth); - // NetApp doesn't like the 'generic' access mask values - policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001)); - rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain - , info); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - return new Sid(info.Sid, SidTypeDomain, (new UnicodeString - (info.Name, false)).ToString(), null, false); - } - finally - { - if (handle != null) - { - if (policyHandle != null) - { - policyHandle.Close(); - } - handle.Close(); - } - } - } - } - - public static byte[] ToByteArray(Rpc.SidT sid) - { - byte[] dst = new byte[1 + 1 + 6 + sid.SubAuthorityCount * 4]; - int di = 0; - dst[di++] = sid.Revision; - dst[di++] = sid.SubAuthorityCount; - Array.Copy(sid.IdentifierAuthority, 0, dst, di, 6); - di += 6; - for (int ii = 0; ii < sid.SubAuthorityCount; ii++) - { - Encdec.Enc_uint32le(sid.SubAuthority[ii], dst, di); - di += 4; - } - return dst; - } - - internal int Type; - - internal string DomainName; - - internal string AcctName; - - internal string OriginServer; - - internal NtlmPasswordAuthentication OriginAuth; - - public Sid(byte[] src, int si) - { - Revision = src[si++]; - SubAuthorityCount = src[si++]; - IdentifierAuthority = new byte[6]; - Array.Copy(src, si, IdentifierAuthority, 0, 6); - si += 6; - if (SubAuthorityCount > 100) - { - throw new RuntimeException("Invalid SID sub_authority_count"); - } - SubAuthority = new int[SubAuthorityCount]; - for (int i = 0; i < SubAuthorityCount; i++) - { - SubAuthority[i] = ServerMessageBlock.ReadInt4(src, si); - si += 4; - } - } - - /// - /// Construct a SID from it's textual representation such as - /// S-1-5-21-1496946806-2192648263-3843101252-1029. - /// - /// - /// Construct a SID from it's textual representation such as - /// S-1-5-21-1496946806-2192648263-3843101252-1029. - /// - /// - public Sid(string textual) - { - StringTokenizer st = new StringTokenizer(textual, "-"); - if (st.CountTokens() < 3 || !st.NextToken().Equals("S")) - { - // need S-N-M - throw new SmbException("Bad textual SID format: " + textual); - } - Revision = byte.Parse(st.NextToken()); - string tmp = st.NextToken(); - long id = 0; - if (tmp.StartsWith("0x")) - { - //id = long.Parse(Sharpen.Runtime.Substring(tmp, 2), 16); - id = long.Parse(Runtime.Substring(tmp, 2)); - } - else - { - id = long.Parse(tmp); - } - IdentifierAuthority = new byte[6]; - for (int i = 5; id > 0; i--) - { - IdentifierAuthority[i] = unchecked((byte)(id % 256)); - id >>= 8; - } - SubAuthorityCount = unchecked((byte)st.CountTokens()); - if (SubAuthorityCount > 0) - { - SubAuthority = new int[SubAuthorityCount]; - for (int i1 = 0; i1 < SubAuthorityCount; i1++) - { - SubAuthority[i1] = (int)(long.Parse(st.NextToken()) & unchecked(0xFFFFFFFFL)); - } - } - } - - /// - /// Construct a SID from a domain SID and an RID - /// (relative identifier). - /// - /// - /// Construct a SID from a domain SID and an RID - /// (relative identifier). For example, a domain SID - /// S-1-5-21-1496946806-2192648263-3843101252 and RID 1029 would - /// yield the SID S-1-5-21-1496946806-2192648263-3843101252-1029. - /// - public Sid(Sid domsid, int rid) - { - Revision = domsid.Revision; - IdentifierAuthority = domsid.IdentifierAuthority; - SubAuthorityCount = unchecked((byte)(domsid.SubAuthorityCount + 1)); - SubAuthority = new int[SubAuthorityCount]; - int i; - for (i = 0; i < domsid.SubAuthorityCount; i++) - { - SubAuthority[i] = domsid.SubAuthority[i]; - } - SubAuthority[i] = rid; - } - - public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority - ) - { - Revision = sid.Revision; - SubAuthorityCount = sid.SubAuthorityCount; - IdentifierAuthority = sid.IdentifierAuthority; - SubAuthority = sid.SubAuthority; - this.Type = type; - this.DomainName = domainName; - this.AcctName = acctName; - if (decrementAuthority) - { - SubAuthorityCount--; - SubAuthority = new int[SubAuthorityCount]; - for (int i = 0; i < SubAuthorityCount; i++) - { - SubAuthority[i] = sid.SubAuthority[i]; - } - } - } - - public virtual Sid GetDomainSid() - { - return new Sid(this, SidTypeDomain, DomainName, null, GetType() - != SidTypeDomain); - } - - public virtual int GetRid() - { - if (GetType() == SidTypeDomain) - { - throw new ArgumentException("This SID is a domain sid"); - } - return SubAuthority[SubAuthorityCount - 1]; - } - - /// Returns the type of this SID indicating the state or type of account. - /// - /// Returns the type of this SID indicating the state or type of account. - ///

- /// SID types are described in the following table. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ///
TypeName
SID_TYPE_USE_NONE0
SID_TYPE_USERUser
SID_TYPE_DOM_GRPDomain group
SID_TYPE_DOMAINDomain
SID_TYPE_ALIASLocal group
SID_TYPE_WKN_GRPBuiltin group
SID_TYPE_DELETEDDeleted
SID_TYPE_INVALIDInvalid
SID_TYPE_UNKNOWNUnknown
- ///
- /// - public virtual int GetType() - { - if (OriginServer != null) - { - ResolveWeak(); - } - return Type; - } - - ///

- /// Return text represeting the SID type suitable for display to - /// users. - /// - /// - /// Return text represeting the SID type suitable for display to - /// users. Text includes 'User', 'Domain group', 'Local group', etc. - /// - public virtual string GetTypeText() - { - if (OriginServer != null) - { - ResolveWeak(); - } - return SidTypeNames[Type]; - } - - /// - /// Return the domain name of this SID unless it could not be - /// resolved in which case the numeric representation is returned. - /// - /// - /// Return the domain name of this SID unless it could not be - /// resolved in which case the numeric representation is returned. - /// - public virtual string GetDomainName() - { - if (OriginServer != null) - { - ResolveWeak(); - } - if (Type == SidTypeUnknown) - { - string full = ToString(); - return Runtime.Substring(full, 0, full.Length - GetAccountName().Length - - 1); - } - return DomainName; - } - - /// - /// Return the sAMAccountName of this SID unless it could not - /// be resolved in which case the numeric RID is returned. - /// - /// - /// Return the sAMAccountName of this SID unless it could not - /// be resolved in which case the numeric RID is returned. If this - /// SID is a domain SID, this method will return an empty String. - /// - public virtual string GetAccountName() - { - if (OriginServer != null) - { - ResolveWeak(); - } - if (Type == SidTypeUnknown) - { - return string.Empty + SubAuthority[SubAuthorityCount - 1]; - } - if (Type == SidTypeDomain) - { - return string.Empty; - } - return AcctName; - } - - public override int GetHashCode() - { - int hcode = IdentifierAuthority[5]; - for (int i = 0; i < SubAuthorityCount; i++) - { - hcode += 65599 * SubAuthority[i]; - } - return hcode; - } - - public override bool Equals(object obj) - { - if (obj is Sid) - { - Sid sid = (Sid)obj; - if (sid == this) - { - return true; - } - if (sid.SubAuthorityCount == SubAuthorityCount) - { - int i = SubAuthorityCount; - while (i-- > 0) - { - if (sid.SubAuthority[i] != SubAuthority[i]) - { - return false; - } - } - for (i = 0; i < 6; i++) - { - if (sid.IdentifierAuthority[i] != IdentifierAuthority[i]) - { - return false; - } - } - return sid.Revision == Revision; - } - } - return false; - } - - /// - /// Return the numeric representation of this sid such as - /// S-1-5-21-1496946806-2192648263-3843101252-1029. - /// - /// - /// Return the numeric representation of this sid such as - /// S-1-5-21-1496946806-2192648263-3843101252-1029. - /// - public override string ToString() - { - string ret = "S-" + (Revision & unchecked(0xFF)) + "-"; - if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked( - 0)) - { - ret += "0x"; - ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6); - } - else - { - int shift = 0; - long id = 0; - for (int i = 5; i > 1; i--) - { - id += (IdentifierAuthority[i] & unchecked(0xFFL)) << shift; - shift += 8; - } - ret += id; - } - for (int i1 = 0; i1 < SubAuthorityCount; i1++) - { - ret += "-" + (SubAuthority[i1] & unchecked(0xFFFFFFFFL)); - } - return ret; - } - - /// - /// Return a String representing this SID ideal for display to - /// users. - /// - /// - /// Return a String representing this SID ideal for display to - /// users. This method should return the same text that the ACL - /// editor in Windows would display. - ///

- /// Specifically, if the SID has - /// been resolved and it is not a domain SID or builtin account, - /// the full DOMAIN\name form of the account will be - /// returned (e.g. MYDOM\alice or MYDOM\Domain Users). - /// If the SID has been resolved but it is is a domain SID, - /// only the domain name will be returned (e.g. MYDOM). - /// If the SID has been resolved but it is a builtin account, - /// only the name component will be returned (e.g. SYSTEM). - /// If the sid cannot be resolved the numeric representation from - /// toString() is returned. - /// - public virtual string ToDisplayString() - { - if (OriginServer != null) - { - ResolveWeak(); - } - if (DomainName != null) - { - string str; - if (Type == SidTypeDomain) - { - str = DomainName; - } - else - { - if (Type == SidTypeWknGrp || DomainName.Equals("BUILTIN")) - { - if (Type == SidTypeUnknown) - { - str = ToString(); - } - else - { - str = AcctName; - } - } - else - { - str = DomainName + "\\" + AcctName; - } - } - return str; - } - return ToString(); - } - - ///

Manually resolve this SID. - /// - /// Manually resolve this SID. Normally SIDs are automatically - /// resolved. However, if a SID is constructed explicitly using a SID - /// constructor, JCIFS will have no knowledge of the server that created the - /// SID and therefore cannot possibly resolve it automatically. In this case, - /// this method will be necessary. - /// - /// The FQDN of the server that is an authority for the SID. - /// - /// Credentials suitable for accessing the SID's information. - /// - public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication - auth) - { - Sid[] sids = new Sid[1]; - sids[0] = this; - ResolveSids(authorityServerName, auth, sids); - } - - internal virtual void ResolveWeak() - { - if (OriginServer != null) - { - try - { - Resolve(OriginServer, OriginAuth); - } - catch (IOException) - { - } - finally - { - OriginServer = null; - OriginAuth = null; - } - } - } - - /// - internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle - domainHandle, Sid domsid, int rid, int flags) - { - SamrAliasHandle aliasHandle = null; - Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray(); - MsrpcGetMembersInAlias rpc = null; - try - { - aliasHandle = new SamrAliasHandle(handle, domainHandle, unchecked(0x0002000c), rid); - rpc = new MsrpcGetMembersInAlias(aliasHandle, sidarray); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - Sid[] sids = new Sid[rpc.Sids.NumSids]; - string originServer = handle.GetServer(); - NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal - (); - for (int i = 0; i < sids.Length; i++) - { - sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false); - sids[i].OriginServer = originServer; - sids[i].OriginAuth = originAuth; - } - if (sids.Length > 0 && (flags & SidFlagResolveSids) != 0) - { - ResolveSids(originServer, originAuth, sids); - } - return sids; - } - finally - { - if (aliasHandle != null) - { - aliasHandle.Close(); - } - } - } - - /// - public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication - auth, int flags) - { - if (Type != SidTypeDomGrp && Type != SidTypeAlias) - { - return new Sid[0]; - } - DcerpcHandle handle = null; - SamrPolicyHandle policyHandle = null; - SamrDomainHandle domainHandle = null; - Sid domsid = GetDomainSid(); - lock (SidCache) - { - try - { - handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]" - , auth); - policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030)); - domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid); - return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(), - flags); - } - finally - { - if (handle != null) - { - if (policyHandle != null) - { - if (domainHandle != null) - { - domainHandle.Close(); - } - policyHandle.Close(); - } - handle.Close(); - } - } - } - } - - /// - /// This specialized method returns a Map of users and local groups for the - /// target server where keys are SIDs representing an account and each value - /// is an List of SIDs represents the local groups that the account is - /// a member of. - /// - /// - /// This specialized method returns a Map of users and local groups for the - /// target server where keys are SIDs representing an account and each value - /// is an List of SIDs represents the local groups that the account is - /// a member of. - ///

- /// This method is designed to assist with computing access control for a - /// given user when the target object's ACL has local groups. Local groups - /// are not listed in a user's group membership (e.g. as represented by the - /// tokenGroups constructed attribute retrived via LDAP). - ///

- /// Domain groups nested inside a local group are currently not expanded. In - /// this case the key (SID) type will be SID_TYPE_DOM_GRP rather than - /// SID_TYPE_USER. - /// - /// The server from which the local groups will be queried. - /// - /// The credentials required to query groups and group members. - /// - /// Flags that control the behavior of the operation. When all - /// name associated with SIDs will be required, the SID_FLAG_RESOLVE_SIDS - /// flag should be used which causes all group member SIDs to be resolved - /// together in a single more efficient operation. - /// - /// - internal static Hashtable GetLocalGroupsMap(string authorityServerName, NtlmPasswordAuthentication - auth, int flags) - { - Sid domsid = GetServerSid(authorityServerName, auth); - DcerpcHandle handle = null; - SamrPolicyHandle policyHandle = null; - SamrDomainHandle domainHandle = null; - Samr.SamrSamArray sam = new Samr.SamrSamArray(); - MsrpcEnumerateAliasesInDomain rpc; - lock (SidCache) - { - try - { - handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]" - , auth); - policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000)); - domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid); - rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam - ); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, false); - } - Hashtable map = new Hashtable(); - for (int ei = 0; ei < rpc.Sam.Count; ei++) - { - Samr.SamrSamEntry entry = rpc.Sam.Entries[ei]; - Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid - , entry.Idx, flags); - Sid groupSid = new Sid(domsid, entry.Idx); - groupSid.Type = SidTypeAlias; - groupSid.DomainName = domsid.GetDomainName(); - groupSid.AcctName = (new UnicodeString(entry.Name, false)).ToString(); - for (int mi = 0; mi < mems.Length; mi++) - { - List groups = (List)map.Get(mems[mi]); - if (groups == null) - { - groups = new List(); - map.Put(mems[mi], groups); - } - if (!groups.Contains(groupSid)) - { - groups.Add(groupSid); - } - } - } - return map; - } - finally - { - if (handle != null) - { - if (policyHandle != null) - { - if (domainHandle != null) - { - domainHandle.Close(); - } - policyHandle.Close(); - } - handle.Close(); - } - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs deleted file mode 100644 index 8a424a0199..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SecurityDescriptor.cs +++ /dev/null @@ -1,101 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; - -namespace SharpCifs.Smb -{ - public class SecurityDescriptor - { - public int Type; - - public Ace[] Aces; - - public SecurityDescriptor() - { - } - - /// - public SecurityDescriptor(byte[] buffer, int bufferIndex, int len) - { - Decode(buffer, bufferIndex, len); - } - - /// - public virtual int Decode(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - bufferIndex++; - // revision - bufferIndex++; - Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - ServerMessageBlock.ReadInt4(buffer, bufferIndex); - // offset to owner sid - bufferIndex += 4; - ServerMessageBlock.ReadInt4(buffer, bufferIndex); - // offset to group sid - bufferIndex += 4; - ServerMessageBlock.ReadInt4(buffer, bufferIndex); - // offset to sacl - bufferIndex += 4; - int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex); - bufferIndex = start + daclOffset; - bufferIndex++; - // revision - bufferIndex++; - int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - if (numAces > 4096) - { - throw new IOException("Invalid SecurityDescriptor"); - } - if (daclOffset != 0) - { - Aces = new Ace[numAces]; - for (int i = 0; i < numAces; i++) - { - Aces[i] = new Ace(); - bufferIndex += Aces[i].Decode(buffer, bufferIndex); - } - } - else - { - Aces = null; - } - return bufferIndex - start; - } - - public override string ToString() - { - string ret = "SecurityDescriptor:\n"; - if (Aces != null) - { - for (int ai = 0; ai < Aces.Length; ai++) - { - ret += Aces[ai] + "\n"; - } - } - else - { - ret += "NULL"; - } - return ret; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs deleted file mode 100644 index cb38c89fa6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/ServerMessageBlock.cs +++ /dev/null @@ -1,692 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; -using SharpCifs.Util.Transport; - -namespace SharpCifs.Smb -{ - public abstract class ServerMessageBlock: Response - { - internal static LogStream Log = LogStream.GetInstance(); - - internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks; - - internal static readonly byte[] Header = { 0xFF, (byte)('S'), (byte)('M'), - (byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - internal static void WriteInt2(long val, byte[] dst, int dstIndex) - { - dst[dstIndex] = unchecked((byte)(val)); - dst[++dstIndex] = unchecked((byte)(val >> 8)); - } - - internal static void WriteInt4(long val, byte[] dst, int dstIndex) - { - dst[dstIndex] = unchecked((byte)(val)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >> 8)); - } - - internal static int ReadInt2(byte[] src, int srcIndex) - { - return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8); - } - - internal static int ReadInt4(byte[] src, int srcIndex) - { - return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2] - & 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24); - } - - internal static long ReadInt8(byte[] src, int srcIndex) - { - return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4 - (src, srcIndex + 4)) << 32); - } - - internal static void WriteInt8(long val, byte[] dst, int dstIndex) - { - dst[dstIndex] = unchecked((byte)(val)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >>= 8)); - dst[++dstIndex] = unchecked((byte)(val >> 8)); - } - - internal static long ReadTime(byte[] src, int srcIndex) - { - int low = ReadInt4(src, srcIndex); - int hi = ReadInt4(src, srcIndex + 4); - long t = ((long)hi << (int)32L) | (low & unchecked((long)(0xFFFFFFFFL))); - t = (t / 10000L - SmbConstants.MillisecondsBetween1970And1601); - return t; - } - - internal static void WriteTime(long t, byte[] dst, int dstIndex) - { - if (t != 0L) - { - t = (t + SmbConstants.MillisecondsBetween1970And1601) * 10000L; - } - WriteInt8(t, dst, dstIndex); - } - - internal static long ReadUTime(byte[] buffer, int bufferIndex) - { - return ReadInt4(buffer, bufferIndex) * 1000L; - } - - internal static void WriteUTime(long t, byte[] dst, int dstIndex) - { - if (t == 0L || t == unchecked((long)(0xFFFFFFFFFFFFFFFFL))) - { - WriteInt4(unchecked((int)(0xFFFFFFFF)), dst, dstIndex); - return; - } - // t isn't in DST either - WriteInt4((int)(t / 1000L), dst, dstIndex); - } - - internal const byte SmbComCreateDirectory = 0x00; - - internal const byte SmbComDeleteDirectory = 0x01; - - internal const byte SmbComClose = 0x04; - - internal const byte SmbComDelete = 0x06; - - internal const byte SmbComRename = 0x07; - - internal const byte SmbComQueryInformation = 0x08; - - internal const byte SmbComWrite = 0x0B; - - internal const byte SmbComCheckDirectory = 0x10; - - internal const byte SmbComTransaction = 0x25; - - internal const byte SmbComTransactionSecondary = 0x26; - - internal const byte SmbComMove = 0x2A; - - internal const byte SmbComEcho = 0x2B; - - internal const byte SmbComOpenAndx = 0x2D; - - internal const byte SmbComReadAndx = 0x2E; - - internal const byte SmbComWriteAndx = 0x2F; - - internal const byte SmbComTransaction2 = 0x32; - - internal const byte SmbComFindClose2 = 0x34; - - internal const byte SmbComTreeDisconnect = 0x71; - - internal const byte SmbComNegotiate = 0x72; - - internal const byte SmbComSessionSetupAndx = 0x73; - - internal const byte SmbComLogoffAndx = 0x74; - - internal const byte SmbComTreeConnectAndx = 0x75; - - internal const byte SmbComNtTransact = 0xA0; - - internal const byte SmbComNtTransactSecondary = 0xA1; - - internal const byte SmbComNtCreateAndx = 0xA2; - - internal byte Command; - - internal byte Flags; - - internal int HeaderStart; - - internal int Length; - - internal int BatchLevel; - - internal int ErrorCode; - - internal int Flags2; - - internal int Tid; - - internal int Pid; - - internal int Uid; - - internal int Mid; - - internal int WordCount; - - internal int ByteCount; - - internal bool UseUnicode; - - internal bool Received; - - internal bool ExtendedSecurity; - - internal long ResponseTimeout = 1; - - internal int SignSeq; - - internal bool VerifyFailed; - - internal NtlmPasswordAuthentication Auth = null; - - internal string Path; - - internal SigningDigest Digest; - - internal ServerMessageBlock Response; - - public ServerMessageBlock() - { - Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized - )); - Pid = SmbConstants.Pid; - BatchLevel = 0; - } - - internal virtual void Reset() - { - Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized - )); - Flags2 = 0; - ErrorCode = 0; - Received = false; - Digest = null; - } - - internal virtual int WriteString(string str, byte[] dst, int dstIndex) - { - return WriteString(str, dst, dstIndex, UseUnicode); - } - - internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode - ) - { - int start = dstIndex; - try - { - if (useUnicode) - { - // Unicode requires word alignment - if (((dstIndex - HeaderStart) % 2) != 0) - { - dst[dstIndex++] = (byte)('\0'); - } - Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex - , str.Length * 2); - dstIndex += str.Length * 2; - dst[dstIndex++] = (byte)('\0'); - dst[dstIndex++] = (byte)('\0'); - } - else - { - byte[] b = Runtime.GetBytesForString(str, SmbConstants.OemEncoding); - Array.Copy(b, 0, dst, dstIndex, b.Length); - dstIndex += b.Length; - dst[dstIndex++] = (byte)('\0'); - } - } - catch (UnsupportedEncodingException uee) - { - if (Log.Level > 1) - { - Runtime.PrintStackTrace(uee, Log); - } - } - return dstIndex - start; - } - - internal virtual string ReadString(byte[] src, int srcIndex) - { - return ReadString(src, srcIndex, 256, UseUnicode); - } - - internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode - ) - { - int len = 0; - string str = null; - try - { - if (useUnicode) - { - // Unicode requires word alignment - if (((srcIndex - HeaderStart) % 2) != 0) - { - srcIndex++; - } - while (src[srcIndex + len] != 0x00 || src[srcIndex - + len + 1] != 0x00) - { - len += 2; - if (len > maxLen) - { - if (Log.Level > 0) - { - Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : - 128); - } - throw new RuntimeException("zero termination not found"); - } - } - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding); - } - else - { - while (src[srcIndex + len] != 0x00) - { - len++; - if (len > maxLen) - { - if (Log.Level > 0) - { - Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : - 128); - } - throw new RuntimeException("zero termination not found"); - } - } - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding); - } - } - catch (UnsupportedEncodingException uee) - { - if (Log.Level > 1) - { - Runtime.PrintStackTrace(uee, Log); - } - } - return str; - } - - internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen - , bool useUnicode) - { - int len = 0; - string str = null; - try - { - if (useUnicode) - { - // Unicode requires word alignment - if (((srcIndex - HeaderStart) % 2) != 0) - { - srcIndex++; - } - for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2) - { - if (src[srcIndex + len] == 0x00 && src[srcIndex - + len + 1] == 0x00) - { - break; - } - if (len > maxLen) - { - if (Log.Level > 0) - { - Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : - 128); - } - throw new RuntimeException("zero termination not found"); - } - } - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding); - } - else - { - for (len = 0; srcIndex < srcEnd; len++) - { - if (src[srcIndex + len] == 0x00) - { - break; - } - if (len > maxLen) - { - if (Log.Level > 0) - { - Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : - 128); - } - throw new RuntimeException("zero termination not found"); - } - } - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding); - } - } - catch (UnsupportedEncodingException uee) - { - if (Log.Level > 1) - { - Runtime.PrintStackTrace(uee, Log); - } - } - return str; - } - - internal virtual int StringWireLength(string str, int offset) - { - int len = str.Length + 1; - if (UseUnicode) - { - len = str.Length * 2 + 2; - len = (offset % 2) != 0 ? len + 1 : len; - } - return len; - } - - internal virtual int ReadStringLength(byte[] src, int srcIndex, int max) - { - int len = 0; - while (src[srcIndex + len] != 0x00) - { - if (len++ > max) - { - throw new RuntimeException("zero termination not found: " + this); - } - } - return len; - } - - internal virtual int Encode(byte[] dst, int dstIndex) - { - int start = HeaderStart = dstIndex; - dstIndex += WriteHeaderWireFormat(dst, dstIndex); - WordCount = WriteParameterWordsWireFormat(dst, dstIndex + 1); - dst[dstIndex++] = unchecked((byte)((WordCount / 2) & 0xFF)); - dstIndex += WordCount; - WordCount /= 2; - ByteCount = WriteBytesWireFormat(dst, dstIndex + 2); - dst[dstIndex++] = unchecked((byte)(ByteCount & 0xFF)); - dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & 0xFF)); - dstIndex += ByteCount; - Length = dstIndex - start; - if (Digest != null) - { - Digest.Sign(dst, HeaderStart, Length, this, Response); - } - return Length; - } - - internal virtual int Decode(byte[] buffer, int bufferIndex) - { - int start = HeaderStart = bufferIndex; - bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex); - WordCount = buffer[bufferIndex++]; - if (WordCount != 0) - { - int n; - if ((n = ReadParameterWordsWireFormat(buffer, bufferIndex)) != WordCount * 2) - { - if (Log.Level >= 5) - { - Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned " - + n); - } - } - bufferIndex += WordCount * 2; - } - ByteCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if (ByteCount != 0) - { - int n; - if ((n = ReadBytesWireFormat(buffer, bufferIndex)) != ByteCount) - { - if (Log.Level >= 5) - { - Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n - ); - } - } - // Don't think we can rely on n being correct here. Must use byteCount. - // Last paragraph of section 3.13.3 eludes to this. - bufferIndex += ByteCount; - } - Length = bufferIndex - start; - return Length; - } - - internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex) - { - Array.Copy(Header, 0, dst, dstIndex, Header.Length); - dst[dstIndex + SmbConstants.CmdOffset] = Command; - dst[dstIndex + SmbConstants.FlagsOffset] = Flags; - WriteInt2(Flags2, dst, dstIndex + SmbConstants.FlagsOffset + 1); - dstIndex += SmbConstants.TidOffset; - WriteInt2(Tid, dst, dstIndex); - WriteInt2(Pid, dst, dstIndex + 2); - WriteInt2(Uid, dst, dstIndex + 4); - WriteInt2(Mid, dst, dstIndex + 6); - return SmbConstants.HeaderLength; - } - - internal virtual int ReadHeaderWireFormat(byte[] buffer, int bufferIndex) - { - Command = buffer[bufferIndex + SmbConstants.CmdOffset]; - ErrorCode = ReadInt4(buffer, bufferIndex + SmbConstants.ErrorCodeOffset); - Flags = buffer[bufferIndex + SmbConstants.FlagsOffset]; - Flags2 = ReadInt2(buffer, bufferIndex + SmbConstants.FlagsOffset + 1); - Tid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset); - Pid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 2); - Uid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 4); - Mid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 6); - return SmbConstants.HeaderLength; - } - - internal virtual bool IsResponse() - { - return (Flags & SmbConstants.FlagsResponse) == SmbConstants.FlagsResponse; - } - - internal abstract int WriteParameterWordsWireFormat(byte[] dst, int dstIndex); - - internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex); - - internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ); - - internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex); - - public override int GetHashCode() - { - return Mid; - } - - public override bool Equals(object obj) - { - return obj is ServerMessageBlock && ((ServerMessageBlock)obj) - .Mid == Mid; - } - - public override string ToString() - { - string c; - switch (Command) - { - case SmbComNegotiate: - { - c = "SMB_COM_NEGOTIATE"; - break; - } - - case SmbComSessionSetupAndx: - { - c = "SMB_COM_SESSION_SETUP_ANDX"; - break; - } - - case SmbComTreeConnectAndx: - { - c = "SMB_COM_TREE_CONNECT_ANDX"; - break; - } - - case SmbComQueryInformation: - { - c = "SMB_COM_QUERY_INFORMATION"; - break; - } - - case SmbComCheckDirectory: - { - c = "SMB_COM_CHECK_DIRECTORY"; - break; - } - - case SmbComTransaction: - { - c = "SMB_COM_TRANSACTION"; - break; - } - - case SmbComTransaction2: - { - c = "SMB_COM_TRANSACTION2"; - break; - } - - case SmbComTransactionSecondary: - { - c = "SMB_COM_TRANSACTION_SECONDARY"; - break; - } - - case SmbComFindClose2: - { - c = "SMB_COM_FIND_CLOSE2"; - break; - } - - case SmbComTreeDisconnect: - { - c = "SMB_COM_TREE_DISCONNECT"; - break; - } - - case SmbComLogoffAndx: - { - c = "SMB_COM_LOGOFF_ANDX"; - break; - } - - case SmbComEcho: - { - c = "SMB_COM_ECHO"; - break; - } - - case SmbComMove: - { - c = "SMB_COM_MOVE"; - break; - } - - case SmbComRename: - { - c = "SMB_COM_RENAME"; - break; - } - - case SmbComDelete: - { - c = "SMB_COM_DELETE"; - break; - } - - case SmbComDeleteDirectory: - { - c = "SMB_COM_DELETE_DIRECTORY"; - break; - } - - case SmbComNtCreateAndx: - { - c = "SMB_COM_NT_CREATE_ANDX"; - break; - } - - case SmbComOpenAndx: - { - c = "SMB_COM_OPEN_ANDX"; - break; - } - - case SmbComReadAndx: - { - c = "SMB_COM_READ_ANDX"; - break; - } - - case SmbComClose: - { - c = "SMB_COM_CLOSE"; - break; - } - - case SmbComWriteAndx: - { - c = "SMB_COM_WRITE_ANDX"; - break; - } - - case SmbComCreateDirectory: - { - c = "SMB_COM_CREATE_DIRECTORY"; - break; - } - - case SmbComNtTransact: - { - c = "SMB_COM_NT_TRANSACT"; - break; - } - - case SmbComNtTransactSecondary: - { - c = "SMB_COM_NT_TRANSACT_SECONDARY"; - break; - } - - default: - { - c = "UNKNOWN"; - break; - } - } - string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode); - return "command=" + c + ",received=" + Received + ",errorCode=" + str - + ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x" - + Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid=" - + Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount=" - + ByteCount; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs deleted file mode 100644 index 9f57e887b7..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs +++ /dev/null @@ -1,257 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - /// To filter 0 len updates and for debugging - public class SigningDigest - { - internal static LogStream Log = LogStream.GetInstance(); - - private MessageDigest _digest; - - private byte[] _macSigningKey; - - private bool _bypass; - - private int _updates; - - private int _signSequence; - - /// - public SigningDigest(byte[] macSigningKey, bool bypass) - { - try - { - _digest = MessageDigest.GetInstance("MD5"); - } - catch (NoSuchAlgorithmException ex) - { - if (Log.Level > 0) - { - Runtime.PrintStackTrace(ex, Log); - } - throw new SmbException("MD5", ex); - } - this._macSigningKey = macSigningKey; - this._bypass = bypass; - _updates = 0; - _signSequence = 0; - if (Log.Level >= 5) - { - Log.WriteLine("macSigningKey:"); - Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length); - } - } - - /// - public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth) - { - try - { - _digest = MessageDigest.GetInstance("MD5"); - } - catch (NoSuchAlgorithmException ex) - { - if (Log.Level > 0) - { - Runtime.PrintStackTrace(ex, Log); - } - throw new SmbException("MD5", ex); - } - try - { - switch (SmbConstants.LmCompatibility) - { - case 0: - case 1: - case 2: - { - _macSigningKey = new byte[40]; - auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0); - Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey - , 16, 24); - break; - } - - case 3: - case 4: - case 5: - { - _macSigningKey = new byte[16]; - auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0); - break; - } - - default: - { - _macSigningKey = new byte[40]; - auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0); - Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey - , 16, 24); - break; - } - } - } - catch (Exception ex) - { - throw new SmbException(string.Empty, ex); - } - if (Log.Level >= 5) - { - Log.WriteLine("LM_COMPATIBILITY=" + SmbConstants.LmCompatibility); - Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length); - } - } - - public virtual void Update(byte[] input, int offset, int len) - { - if (Log.Level >= 5) - { - Log.WriteLine("update: " + _updates + " " + offset + ":" + len); - Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256)); - Log.Flush(); - } - if (len == 0) - { - return; - } - _digest.Update(input, offset, len); - _updates++; - } - - public virtual byte[] Digest() - { - byte[] b; - b = _digest.Digest(); - if (Log.Level >= 5) - { - Log.WriteLine("digest: "); - Hexdump.ToHexdump(Log, b, 0, b.Length); - Log.Flush(); - } - _updates = 0; - return b; - } - - /// Performs MAC signing of the SMB. - /// - /// Performs MAC signing of the SMB. This is done as follows. - /// The signature field of the SMB is overwritted with the sequence number; - /// The MD5 digest of the MAC signing key + the entire SMB is taken; - /// The first 8 bytes of this are placed in the signature field. - /// - /// The data. - /// The starting offset at which the SMB header begins. - /// The length of the SMB data starting at offset. - internal virtual void Sign(byte[] data, int offset, int length, ServerMessageBlock - request, ServerMessageBlock response) - { - request.SignSeq = _signSequence; - if (response != null) - { - response.SignSeq = _signSequence + 1; - response.VerifyFailed = false; - } - try - { - Update(_macSigningKey, 0, _macSigningKey.Length); - int index = offset + SmbConstants.SignatureOffset; - for (int i = 0; i < 8; i++) - { - data[index + i] = 0; - } - ServerMessageBlock.WriteInt4(_signSequence, data, index); - Update(data, offset, length); - Array.Copy(Digest(), 0, data, index, 8); - if (_bypass) - { - _bypass = false; - Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index, - 8); - } - } - catch (Exception ex) - { - if (Log.Level > 0) - { - Runtime.PrintStackTrace(ex, Log); - } - } - finally - { - _signSequence += 2; - } - } - - /// Performs MAC signature verification. - /// - /// Performs MAC signature verification. This calculates the signature - /// of the SMB and compares it to the signature field on the SMB itself. - /// - /// The data. - /// The starting offset at which the SMB header begins. - /// The length of the SMB data starting at offset. - internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response - ) - { - Update(_macSigningKey, 0, _macSigningKey.Length); - int index = offset; - Update(data, index, SmbConstants.SignatureOffset); - index += SmbConstants.SignatureOffset; - byte[] sequence = new byte[8]; - ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0); - Update(sequence, 0, sequence.Length); - index += 8; - if (response.Command == ServerMessageBlock.SmbComReadAndx) - { - SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response; - int length = response.Length - raxr.DataLength; - Update(data, index, length - SmbConstants.SignatureOffset - 8); - Update(raxr.B, raxr.Off, raxr.DataLength); - } - else - { - Update(data, index, response.Length - SmbConstants.SignatureOffset - 8); - } - byte[] signature = Digest(); - for (int i = 0; i < 8; i++) - { - if (signature[i] != data[offset + SmbConstants.SignatureOffset + i]) - { - if (Log.Level >= 2) - { - Log.WriteLine("signature verification failure"); - Hexdump.ToHexdump(Log, signature, 0, 8); - Hexdump.ToHexdump(Log, data, offset + SmbConstants.SignatureOffset, 8); - } - return response.VerifyFailed = true; - } - } - return response.VerifyFailed = false; - } - - public override string ToString() - { - return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString - (_macSigningKey, 0, _macSigningKey.Length); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs deleted file mode 100644 index defaea71b4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbAuthException.cs +++ /dev/null @@ -1,36 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - /// - /// The SmbAuthException encapsulates the variety of - /// authentication related error codes returned by an SMB server. - /// - /// - /// The SmbAuthException encapsulates the variety of - /// authentication related error codes returned by an SMB server. - ///

- /// See jCIFS Exceptions and NtlmAuthenticator for more information about SmbAuthException. - /// - - public class SmbAuthException : SmbException - { - internal SmbAuthException(int errcode) : base(errcode, null) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs deleted file mode 100644 index 2295de5b9c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComBlankResponse.cs +++ /dev/null @@ -1,47 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComBlankResponse : ServerMessageBlock - { - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComBlankResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs deleted file mode 100644 index 4a160f5188..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComClose.cs +++ /dev/null @@ -1,62 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComClose : ServerMessageBlock - { - private int _fid; - - private long _lastWriteTime; - - internal SmbComClose(int fid, long lastWriteTime) - { - this._fid = fid; - this._lastWriteTime = lastWriteTime; - Command = SmbComClose; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - WriteInt2(_fid, dst, dstIndex); - dstIndex += 2; - WriteUTime(_lastWriteTime, dst, dstIndex); - return 6; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComClose[" + base.ToString() + ",fid=" + _fid + ",lastWriteTime=" - + _lastWriteTime + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs deleted file mode 100644 index 7549db01ab..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComCreateDirectory.cs +++ /dev/null @@ -1,57 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComCreateDirectory : ServerMessageBlock - { - internal SmbComCreateDirectory(string directoryName) - { - Path = directoryName; - Command = SmbComCreateDirectory; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = unchecked(unchecked(0x04)); - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComCreateDirectory[" + base.ToString() + ",directoryName=" - + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs deleted file mode 100644 index d055d2446d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDelete.cs +++ /dev/null @@ -1,63 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class SmbComDelete : ServerMessageBlock - { - private int _searchAttributes; - - internal SmbComDelete(string fileName) - { - Path = fileName; - Command = SmbComDelete; - _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrHidden | SmbConstants.AttrSystem; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - WriteInt2(_searchAttributes, dst, dstIndex); - return 2; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = unchecked(unchecked(0x04)); - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComDelete[" + base.ToString() + ",searchAttributes=0x" + Hexdump - .ToHexString(_searchAttributes, 4) + ",fileName=" + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs deleted file mode 100644 index 240139a173..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComDeleteDirectory.cs +++ /dev/null @@ -1,57 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComDeleteDirectory : ServerMessageBlock - { - internal SmbComDeleteDirectory(string directoryName) - { - Path = directoryName; - Command = SmbComDeleteDirectory; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = unchecked(unchecked(0x04)); - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName=" - + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs deleted file mode 100644 index 9b7c0c7657..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComFindClose2.cs +++ /dev/null @@ -1,56 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComFindClose2 : ServerMessageBlock - { - private int _sid; - - internal SmbComFindClose2(int sid) - { - this._sid = sid; - Command = SmbComFindClose2; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - WriteInt2(_sid, dst, dstIndex); - return 2; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs deleted file mode 100644 index 8f88ccd579..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComLogoffAndX.cs +++ /dev/null @@ -1,52 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComLogoffAndX : AndXServerMessageBlock - { - internal SmbComLogoffAndX(ServerMessageBlock andx) : base(andx) - { - Command = SmbComLogoffAndx; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComLogoffAndX[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs deleted file mode 100644 index 26b5ba63af..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndX.cs +++ /dev/null @@ -1,193 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class SmbComNtCreateAndX : AndXServerMessageBlock - { - internal const int FileSupersede = unchecked(0x0); - - internal const int FileOpen = unchecked(0x1); - - internal const int FileCreate = unchecked(0x2); - - internal const int FileOpenIf = unchecked(0x3); - - internal const int FileOverwrite = unchecked(0x4); - - internal const int FileOverwriteIf = unchecked(0x5); - - internal const int FileWriteThrough = unchecked(0x00000002); - - internal const int FileSequentialOnly = unchecked(0x00000004); - - internal const int FileSynchronousIoAlert = unchecked(0x00000010); - - internal const int FileSynchronousIoNonalert = unchecked(0x00000020); - - internal const int SecurityContextTracking = unchecked(0x01); - - internal const int SecurityEffectiveOnly = unchecked(0x02); - - private int _rootDirectoryFid; - - private int _extFileAttributes; - - private int _shareAccess; - - private int _createDisposition; - - private int _createOptions; - - private int _impersonationLevel; - - private long _allocationSize; - - private byte _securityFlags; - - private int _namelenIndex; - - internal int Flags0; - - internal int DesiredAccess; - - internal SmbComNtCreateAndX(string name, int flags, int access, int shareAccess, - int extFileAttributes, int createOptions, ServerMessageBlock andx) : base(andx) - { - // share access specified in SmbFile - // create disposition - // create options - // security flags - Path = name; - Command = SmbComNtCreateAndx; - DesiredAccess = access; - DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes; - // extFileAttributes - this._extFileAttributes = extFileAttributes; - // shareAccess - this._shareAccess = shareAccess; - // createDisposition - if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc) - { - // truncate the file - if ((flags & SmbFile.OCreat) == SmbFile.OCreat) - { - // create it if necessary - _createDisposition = FileOverwriteIf; - } - else - { - _createDisposition = FileOverwrite; - } - } - else - { - // don't truncate the file - if ((flags & SmbFile.OCreat) == SmbFile.OCreat) - { - // create it if necessary - if ((flags & SmbFile.OExcl) == SmbFile.OExcl) - { - // fail if already exists - _createDisposition = FileCreate; - } - else - { - _createDisposition = FileOpenIf; - } - } - else - { - _createDisposition = FileOpen; - } - } - if ((createOptions & unchecked(0x0001)) == 0) - { - this._createOptions = createOptions | unchecked(0x0040); - } - else - { - this._createOptions = createOptions; - } - _impersonationLevel = unchecked(0x02); - // As seen on NT :~) - _securityFlags = unchecked(unchecked(0x03)); - } - - // SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // name length without counting null termination - _namelenIndex = dstIndex; - dstIndex += 2; - WriteInt4(Flags0, dst, dstIndex); - dstIndex += 4; - WriteInt4(_rootDirectoryFid, dst, dstIndex); - dstIndex += 4; - WriteInt4(DesiredAccess, dst, dstIndex); - dstIndex += 4; - WriteInt8(_allocationSize, dst, dstIndex); - dstIndex += 8; - WriteInt4(_extFileAttributes, dst, dstIndex); - dstIndex += 4; - WriteInt4(_shareAccess, dst, dstIndex); - dstIndex += 4; - WriteInt4(_createDisposition, dst, dstIndex); - dstIndex += 4; - WriteInt4(_createOptions, dst, dstIndex); - dstIndex += 4; - WriteInt4(_impersonationLevel, dst, dstIndex); - dstIndex += 4; - dst[dstIndex++] = _securityFlags; - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int n; - n = WriteString(Path, dst, dstIndex); - WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex); - return n; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComNTCreateAndX[" + base.ToString() + ",flags=0x" + Hexdump - .ToHexString(Flags0, 2) + ",rootDirectoryFid=" + _rootDirectoryFid + ",desiredAccess=0x" - + Hexdump.ToHexString(DesiredAccess, 4) + ",allocationSize=" + _allocationSize + - ",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) + ",shareAccess=0x" - + Hexdump.ToHexString(_shareAccess, 4) + ",createDisposition=0x" + Hexdump.ToHexString - (_createDisposition, 4) + ",createOptions=0x" + Hexdump.ToHexString(_createOptions - , 8) + ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4) + ",securityFlags=0x" - + Hexdump.ToHexString(_securityFlags, 2) + ",name=" + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs deleted file mode 100644 index 4a007bdc5b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNTCreateAndXResponse.cs +++ /dev/null @@ -1,116 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock - { - internal const int ExclusiveOplockGranted = 1; - - internal const int BatchOplockGranted = 2; - - internal const int LevelIiOplockGranted = 3; - - internal byte OplockLevel; - - internal int Fid; - - internal int CreateAction; - - internal int ExtFileAttributes; - - internal int FileType; - - internal int DeviceState; - - internal long CreationTime; - - internal long LastAccessTime; - - internal long LastWriteTime; - - internal long ChangeTime; - - internal long AllocationSize; - - internal long EndOfFile; - - internal bool Directory; - - internal bool IsExtended; - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - OplockLevel = buffer[bufferIndex++]; - Fid = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - CreateAction = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - CreationTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - LastAccessTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - LastWriteTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - ChangeTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - ExtFileAttributes = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - AllocationSize = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - EndOfFile = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - FileType = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DeviceState = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0; - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel=" - + OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction - , 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime=" - + Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate - (LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x" - + Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize - + ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState - + ",directory=" + Directory + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs deleted file mode 100644 index 499bffbd9c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiate.cs +++ /dev/null @@ -1,70 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComNegotiate : ServerMessageBlock - { - private const string Dialects = "\u0002NT LM 0.12\u0000"; - - public SmbComNegotiate() - { - Command = SmbComNegotiate; - Flags2 = SmbConstants.DefaultFlags2; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - byte[] dialects; - try - { - //dialects = Runtime.GetBytesForString(Dialects, "ASCII"); - dialects = Runtime.GetBytesForString(Dialects, "UTF-8"); - } - catch (UnsupportedEncodingException) - { - return 0; - } - Array.Copy(dialects, 0, dst, dstIndex, dialects.Length); - return dialects.Length; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount - + ",dialects=NT LM 0.12]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs deleted file mode 100644 index c4cd1c1297..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNegotiateResponse.cs +++ /dev/null @@ -1,164 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComNegotiateResponse : ServerMessageBlock - { - internal int DialectIndex; - - internal SmbTransport.ServerData Server; - - internal SmbComNegotiateResponse(SmbTransport.ServerData server) - { - this.Server = server; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - DialectIndex = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if (DialectIndex > 10) - { - return bufferIndex - start; - } - Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF); - Server.Security = Server.SecurityMode & unchecked(0x01); - Server.EncryptedPasswords = (Server.SecurityMode & unchecked(0x02)) == unchecked( - 0x02); - Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked( - 0x04); - Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked( - 0x08); - Server.MaxMpxCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Server.MaxBufferSize = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - Server.MaxRawSize = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - Server.SessionKey = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - Server.Capabilities = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - Server.ServerTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - Server.ServerTimeZone = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF); - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - int start = bufferIndex; - if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0) - { - Server.EncryptionKey = new byte[Server.EncryptionKeyLength]; - Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength - ); - bufferIndex += Server.EncryptionKeyLength; - if (ByteCount > Server.EncryptionKeyLength) - { - int len = 0; - // TODO: we can use new string routine here - try - { - if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode) - { - while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer - [bufferIndex + len + 1] != unchecked(unchecked(0x00))) - { - len += 2; - if (len > 256) - { - throw new RuntimeException("zero termination not found"); - } - } - Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len - , SmbConstants.UniEncoding); - } - else - { - while (buffer[bufferIndex + len] != unchecked(unchecked(0x00))) - { - len++; - if (len > 256) - { - throw new RuntimeException("zero termination not found"); - } - } - Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len - , SmbConstants.OemEncoding); - } - } - catch (UnsupportedEncodingException uee) - { - if (Log.Level > 1) - { - Runtime.PrintStackTrace(uee, Log); - } - } - bufferIndex += len; - } - else - { - Server.OemDomainName = ""; - } - } - else - { - Server.Guid = new byte[16]; - Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16); - Server.OemDomainName = ""; - } - // ignore SPNEGO token for now ... - return bufferIndex - start; - } - - public override string ToString() - { - return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" + - WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString - (Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share" - : "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount=" - + Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize=" - + Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x" - + Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString - (Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server - .ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength=" - + Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" + - Server.OemDomainName + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs deleted file mode 100644 index b5d2cf947e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransaction.cs +++ /dev/null @@ -1,93 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal abstract class SmbComNtTransaction : SmbComTransaction - { - private const int NttPrimarySetupOffset = 69; - - private const int NttSecondaryParameterOffset = 51; - - internal const int NtTransactQuerySecurityDesc = 6; - - internal int Function; - - public SmbComNtTransaction() - { - // relative to headerStart - primarySetupOffset = NttPrimarySetupOffset; - secondaryParameterOffset = NttSecondaryParameterOffset; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - if (Command != SmbComNtTransactSecondary) - { - dst[dstIndex++] = MaxSetupCount; - } - else - { - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - // Reserved - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved - WriteInt4(TotalParameterCount, dst, dstIndex); - dstIndex += 4; - WriteInt4(TotalDataCount, dst, dstIndex); - dstIndex += 4; - if (Command != SmbComNtTransactSecondary) - { - WriteInt4(MaxParameterCount, dst, dstIndex); - dstIndex += 4; - WriteInt4(MaxDataCount, dst, dstIndex); - dstIndex += 4; - } - WriteInt4(ParameterCount, dst, dstIndex); - dstIndex += 4; - WriteInt4((ParameterCount == 0 ? 0 : ParameterOffset), dst, dstIndex); - dstIndex += 4; - if (Command == SmbComNtTransactSecondary) - { - WriteInt4(ParameterDisplacement, dst, dstIndex); - dstIndex += 4; - } - WriteInt4(DataCount, dst, dstIndex); - dstIndex += 4; - WriteInt4((DataCount == 0 ? 0 : DataOffset), dst, dstIndex); - dstIndex += 4; - if (Command == SmbComNtTransactSecondary) - { - WriteInt4(DataDisplacement, dst, dstIndex); - dstIndex += 4; - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - else - { - // Reserved1 - dst[dstIndex++] = unchecked((byte)SetupCount); - WriteInt2(Function, dst, dstIndex); - dstIndex += 2; - dstIndex += WriteSetupWireFormat(dst, dstIndex); - } - return dstIndex - start; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs deleted file mode 100644 index 88d73528a1..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComNtTransactionResponse.cs +++ /dev/null @@ -1,63 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse - { - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - buffer[bufferIndex++] = unchecked(unchecked(0x00)); - // Reserved - buffer[bufferIndex++] = unchecked(unchecked(0x00)); - // Reserved - buffer[bufferIndex++] = unchecked(unchecked(0x00)); - // Reserved - TotalParameterCount = ReadInt4(buffer, bufferIndex); - if (BufDataStart == 0) - { - BufDataStart = TotalParameterCount; - } - bufferIndex += 4; - TotalDataCount = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - ParameterCount = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - ParameterOffset = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - ParameterDisplacement = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - DataCount = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - DataOffset = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - DataDisplacement = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - SetupCount = buffer[bufferIndex] & unchecked(0xFF); - bufferIndex += 2; - if (SetupCount != 0) - { - if (Log.Level >= 3) - { - Log.WriteLine("setupCount is not zero: " + SetupCount); - } - } - return bufferIndex - start; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs deleted file mode 100644 index de11e2a6a8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndX.cs +++ /dev/null @@ -1,190 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComOpenAndX : AndXServerMessageBlock - { - private const int FlagsReturnAdditionalInfo = 0x01; - - private const int FlagsRequestOplock = 0x02; - - private const int FlagsRequestBatchOplock = 0x04; - - private const int SharingCompatibility = 0x00; - - private const int SharingDenyReadWriteExecute = 0x10; - - private const int SharingDenyWrite = 0x20; - - private const int SharingDenyReadExecute = 0x30; - - private const int SharingDenyNone = 0x40; - - private const int DoNotCache = 0x1000; - - private const int WriteThrough = 0x4000; - - private const int OpenFnCreate = 0x10; - - private const int OpenFnFailIfExists = 0x00; - - private const int OpenFnOpen = 0x01; - - private const int OpenFnTrunc = 0x02; - - private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX" - , 1); - - internal int flags; - - internal int DesiredAccess; - - internal int SearchAttributes; - - internal int FileAttributes; - - internal int CreationTime; - - internal int OpenFunction; - - internal int AllocationSize; - - internal SmbComOpenAndX(string fileName, int access, int flags, ServerMessageBlock - andx) : base(andx) - { - // flags (not the same as flags constructor argument) - // Access Mode Encoding for desiredAccess - // bit 12 - // bit 14 - // flags is NOT the same as flags member - Path = fileName; - Command = SmbComOpenAndx; - DesiredAccess = access & 0x3; - if (DesiredAccess == 0x3) - { - DesiredAccess = 0x2; - } - DesiredAccess |= SharingDenyNone; - DesiredAccess &= ~0x1; - // Win98 doesn't like GENERIC_READ ?! -- get Access Denied. - // searchAttributes - SearchAttributes = SmbConstants.AttrDirectory | SmbConstants.AttrHidden | SmbConstants.AttrSystem; - // fileAttributes - FileAttributes = 0; - // openFunction - if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc) - { - // truncate the file - if ((flags & SmbFile.OCreat) == SmbFile.OCreat) - { - // create it if necessary - OpenFunction = OpenFnTrunc | OpenFnCreate; - } - else - { - OpenFunction = OpenFnTrunc; - } - } - else - { - // don't truncate the file - if ((flags & SmbFile.OCreat) == SmbFile.OCreat) - { - // create it if necessary - if ((flags & SmbFile.OExcl) == SmbFile.OExcl) - { - // fail if already exists - OpenFunction = OpenFnCreate | OpenFnFailIfExists; - } - else - { - OpenFunction = OpenFnCreate | OpenFnOpen; - } - } - else - { - OpenFunction = OpenFnOpen; - } - } - } - - internal override int GetBatchLimit(byte command) - { - return command == SmbComReadAndx ? BatchLimit : 0; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(flags, dst, dstIndex); - dstIndex += 2; - WriteInt2(DesiredAccess, dst, dstIndex); - dstIndex += 2; - WriteInt2(SearchAttributes, dst, dstIndex); - dstIndex += 2; - WriteInt2(FileAttributes, dst, dstIndex); - dstIndex += 2; - CreationTime = 0; - WriteInt4(CreationTime, dst, dstIndex); - dstIndex += 4; - WriteInt2(OpenFunction, dst, dstIndex); - dstIndex += 2; - WriteInt4(AllocationSize, dst, dstIndex); - dstIndex += 4; - for (int i = 0; i < 8; i++) - { - dst[dstIndex++] = 0x00; - } - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - if (UseUnicode) - { - dst[dstIndex++] = (byte)('\0'); - } - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComOpenAndX[" + base.ToString() + ",flags=0x" + Hexdump.ToHexString - (flags, 2) + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + ",searchAttributes=0x" - + Hexdump.ToHexString(SearchAttributes, 4) + ",fileAttributes=0x" + Hexdump.ToHexString - (FileAttributes, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime - ) + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2) + ",allocationSize=" - + AllocationSize + ",fileName=" + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs deleted file mode 100644 index 9c49d19a83..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComOpenAndXResponse.cs +++ /dev/null @@ -1,87 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComOpenAndXResponse : AndXServerMessageBlock - { - internal int Fid; - - internal int FileAttributes; - - internal int DataSize; - - internal int GrantedAccess; - - internal int FileType; - - internal int DeviceState; - - internal int Action; - - internal int ServerFid; - - internal long LastWriteTime; - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - Fid = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - FileAttributes = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - LastWriteTime = ReadUTime(buffer, bufferIndex); - bufferIndex += 4; - DataSize = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - GrantedAccess = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - FileType = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DeviceState = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Action = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - ServerFid = ReadInt4(buffer, bufferIndex); - bufferIndex += 6; - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComOpenAndXResponse[" + base.ToString() + ",fid=" + Fid + ",fileAttributes=" - + FileAttributes + ",lastWriteTime=" + LastWriteTime + ",dataSize=" + DataSize - + ",grantedAccess=" + GrantedAccess + ",fileType=" + FileType + ",deviceState=" - + DeviceState + ",action=" + Action + ",serverFid=" + ServerFid + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs deleted file mode 100644 index a528dbb111..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformation.cs +++ /dev/null @@ -1,57 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComQueryInformation : ServerMessageBlock - { - internal SmbComQueryInformation(string filename) - { - Path = filename; - Command = SmbComQueryInformation; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = 0x04; - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComQueryInformation[" + base.ToString() + ",filename=" + Path - + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs deleted file mode 100644 index 040f081f04..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComQueryInformationResponse.cs +++ /dev/null @@ -1,95 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComQueryInformationResponse : ServerMessageBlock, IInfo - { - private int _fileAttributes = 0x0000; - - private long _lastWriteTime; - - private long _serverTimeZoneOffset; - - private int _fileSize; - - internal SmbComQueryInformationResponse(long serverTimeZoneOffset) - { - this._serverTimeZoneOffset = serverTimeZoneOffset; - Command = SmbComQueryInformation; - } - - public virtual int GetAttributes() - { - return _fileAttributes; - } - - public virtual long GetCreateTime() - { - return _lastWriteTime + _serverTimeZoneOffset; - } - - public virtual long GetLastWriteTime() - { - return _lastWriteTime + _serverTimeZoneOffset; - } - - public virtual long GetSize() - { - return _fileSize; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - if (WordCount == 0) - { - return 0; - } - _fileAttributes = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _lastWriteTime = ReadUTime(buffer, bufferIndex); - bufferIndex += 4; - _fileSize = ReadInt4(buffer, bufferIndex); - return 20; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComQueryInformationResponse[" + base.ToString() + ",fileAttributes=0x" - + Hexdump.ToHexString(_fileAttributes, 4) + ",lastWriteTime=" + Extensions.CreateDate - (_lastWriteTime) + ",fileSize=" + _fileSize + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs deleted file mode 100644 index e751797006..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndX.cs +++ /dev/null @@ -1,107 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComReadAndX : AndXServerMessageBlock - { - private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.ReadAndX.Close" - , 1); - - private long _offset; - - private int _fid; - - private int _openTimeout; - - internal int MaxCount; - - internal int MinCount; - - internal int Remaining; - - public SmbComReadAndX() : base(null) - { - Command = SmbComReadAndx; - _openTimeout = unchecked((int)(0xFFFFFFFF)); - } - - internal SmbComReadAndX(int fid, long offset, int maxCount, ServerMessageBlock andx - ) : base(andx) - { - this._fid = fid; - this._offset = offset; - this.MaxCount = MinCount = maxCount; - Command = SmbComReadAndx; - _openTimeout = unchecked((int)(0xFFFFFFFF)); - } - - internal virtual void SetParam(int fid, long offset, int maxCount) - { - this._fid = fid; - this._offset = offset; - this.MaxCount = MinCount = maxCount; - } - - internal override int GetBatchLimit(byte command) - { - return command == SmbComClose ? BatchLimit : 0; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_fid, dst, dstIndex); - dstIndex += 2; - WriteInt4(_offset, dst, dstIndex); - dstIndex += 4; - WriteInt2(MaxCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(MinCount, dst, dstIndex); - dstIndex += 2; - WriteInt4(_openTimeout, dst, dstIndex); - dstIndex += 4; - WriteInt2(Remaining, dst, dstIndex); - dstIndex += 2; - WriteInt4(_offset >> 32, dst, dstIndex); - dstIndex += 4; - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComReadAndX[" + base.ToString() + ",fid=" + _fid + ",offset=" - + _offset + ",maxCount=" + MaxCount + ",minCount=" + MinCount + ",openTimeout=" - + _openTimeout + ",remaining=" + Remaining + ",offset=" + _offset + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs deleted file mode 100644 index 4d857aa2c3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComReadAndXResponse.cs +++ /dev/null @@ -1,87 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComReadAndXResponse : AndXServerMessageBlock - { - internal byte[] B; - - internal int Off; - - internal int DataCompactionMode; - - internal int DataLength; - - internal int DataOffset; - - public SmbComReadAndXResponse() - { - } - - internal SmbComReadAndXResponse(byte[] b, int off) - { - this.B = b; - this.Off = off; - } - - internal virtual void SetParam(byte[] b, int off) - { - this.B = b; - this.Off = off; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - bufferIndex += 2; - // reserved - DataCompactionMode = ReadInt2(buffer, bufferIndex); - bufferIndex += 4; - // 2 reserved - DataLength = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DataOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 12; - // 10 reserved - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - // handled special in SmbTransport.doRecv() - return 0; - } - - public override string ToString() - { - return "SmbComReadAndXResponse[" + base.ToString() + ",dataCompactionMode=" - + DataCompactionMode + ",dataLength=" + DataLength + ",dataOffset=" + DataOffset - + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs deleted file mode 100644 index 0ac57dd3e4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComRename.cs +++ /dev/null @@ -1,75 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class SmbComRename : ServerMessageBlock - { - private int _searchAttributes; - - private string _oldFileName; - - private string _newFileName; - - internal SmbComRename(string oldFileName, string newFileName) - { - Command = SmbComRename; - this._oldFileName = oldFileName; - this._newFileName = newFileName; - _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrSystem | SmbConstants.AttrDirectory; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - WriteInt2(_searchAttributes, dst, dstIndex); - return 2; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = unchecked(unchecked(0x04)); - dstIndex += WriteString(_oldFileName, dst, dstIndex); - dst[dstIndex++] = unchecked(unchecked(0x04)); - if (UseUnicode) - { - dst[dstIndex++] = unchecked((byte)('\0')); - } - dstIndex += WriteString(_newFileName, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComRename[" + base.ToString() + ",searchAttributes=0x" + Hexdump - .ToHexString(_searchAttributes, 4) + ",oldFileName=" + _oldFileName + ",newFileName=" - + _newFileName + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs deleted file mode 100644 index a1642391ca..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndX.cs +++ /dev/null @@ -1,234 +0,0 @@ -// This code is derived from jcifs smb client library -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// Ported to C# by J. Arturo -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComSessionSetupAndX : AndXServerMessageBlock - { - private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX" - , 1); - - private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords" - , true); - - private byte[] _lmHash; - - private byte[] _ntHash; - - private byte[] _blob; - - private int _sessionKey; - - private int _capabilities; - - private string _accountName; - - private string _primaryDomain; - - internal SmbSession Session; - - internal object Cred; - - /// - internal SmbComSessionSetupAndX(SmbSession session, ServerMessageBlock andx, object - cred) : base(andx) - { - Command = SmbComSessionSetupAndx; - this.Session = session; - this.Cred = cred; - _sessionKey = session.transport.SessionKey; - _capabilities = session.transport.Capabilities; - if (session.transport.Server.Security == SmbConstants.SecurityUser) - { - if (cred is NtlmPasswordAuthentication) - { - NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred; - if (auth == NtlmPasswordAuthentication.Anonymous) - { - _lmHash = new byte[0]; - _ntHash = new byte[0]; - _capabilities &= ~SmbConstants.CapExtendedSecurity; - } - else - { - if (session.transport.Server.EncryptedPasswords) - { - _lmHash = auth.GetAnsiHash(session.transport.Server.EncryptionKey); - _ntHash = auth.GetUnicodeHash(session.transport.Server.EncryptionKey); - // prohibit HTTP auth attempts for the null session - if (_lmHash.Length == 0 && _ntHash.Length == 0) - { - throw new RuntimeException("Null setup prohibited."); - } - } - else - { - if (DisablePlainTextPasswords) - { - throw new RuntimeException("Plain text passwords are disabled"); - } - if (UseUnicode) - { - // plain text - string password = auth.GetPassword(); - _lmHash = new byte[0]; - _ntHash = new byte[(password.Length + 1) * 2]; - WriteString(password, _ntHash, 0); - } - else - { - // plain text - string password = auth.GetPassword(); - _lmHash = new byte[(password.Length + 1) * 2]; - _ntHash = new byte[0]; - WriteString(password, _lmHash, 0); - } - } - } - _accountName = auth.Username; - if (UseUnicode) - { - _accountName = _accountName.ToUpper(); - } - _primaryDomain = auth.Domain.ToUpper(); - } - else - { - if (cred is byte[]) - { - _blob = (byte[])cred; - } - else - { - throw new SmbException("Unsupported credential type"); - } - } - } - else - { - if (session.transport.Server.Security == SmbConstants.SecurityShare) - { - if (cred is NtlmPasswordAuthentication) - { - NtlmPasswordAuthentication auth = (NtlmPasswordAuthentication)cred; - _lmHash = new byte[0]; - _ntHash = new byte[0]; - _accountName = auth.Username; - if (UseUnicode) - { - _accountName = _accountName.ToUpper(); - } - _primaryDomain = auth.Domain.ToUpper(); - } - else - { - throw new SmbException("Unsupported credential type"); - } - } - else - { - throw new SmbException("Unsupported"); - } - } - } - - internal override int GetBatchLimit(byte command) - { - return command == SmbComTreeConnectAndx ? BatchLimit : 0; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(Session.transport.SndBufSize, dst, dstIndex); - dstIndex += 2; - WriteInt2(Session.transport.MaxMpxCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(SmbConstants.VcNumber, dst, dstIndex); - dstIndex += 2; - WriteInt4(_sessionKey, dst, dstIndex); - dstIndex += 4; - if (_blob != null) - { - WriteInt2(_blob.Length, dst, dstIndex); - dstIndex += 2; - } - else - { - WriteInt2(_lmHash.Length, dst, dstIndex); - dstIndex += 2; - WriteInt2(_ntHash.Length, dst, dstIndex); - dstIndex += 2; - } - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - WriteInt4(_capabilities, dst, dstIndex); - dstIndex += 4; - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - if (_blob != null) - { - Array.Copy(_blob, 0, dst, dstIndex, _blob.Length); - dstIndex += _blob.Length; - } - else - { - Array.Copy(_lmHash, 0, dst, dstIndex, _lmHash.Length); - dstIndex += _lmHash.Length; - Array.Copy(_ntHash, 0, dst, dstIndex, _ntHash.Length); - dstIndex += _ntHash.Length; - dstIndex += WriteString(_accountName, dst, dstIndex); - dstIndex += WriteString(_primaryDomain, dst, dstIndex); - } - dstIndex += WriteString(SmbConstants.NativeOs, dst, dstIndex); - dstIndex += WriteString(SmbConstants.NativeLanman, dst, dstIndex); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - string result = "SmbComSessionSetupAndX[" + base.ToString() + ",snd_buf_size=" - + Session.transport.SndBufSize + ",maxMpxCount=" + Session.transport.MaxMpxCount - + ",VC_NUMBER=" + SmbConstants.VcNumber + ",sessionKey=" + _sessionKey + ",lmHash.length=" - + (_lmHash == null ? 0 : _lmHash.Length) + ",ntHash.length=" + (_ntHash == null ? - 0 : _ntHash.Length) + ",capabilities=" + _capabilities + ",accountName=" + _accountName - + ",primaryDomain=" + _primaryDomain + ",NATIVE_OS=" + SmbConstants.NativeOs - + ",NATIVE_LANMAN=" + SmbConstants.NativeLanman + "]"; - return result; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs deleted file mode 100644 index a3b80a669a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComSessionSetupAndXResponse.cs +++ /dev/null @@ -1,92 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal class SmbComSessionSetupAndXResponse : AndXServerMessageBlock - { - private string _nativeOs = string.Empty; - - private string _nativeLanMan = string.Empty; - - private string _primaryDomain = string.Empty; - - internal bool IsLoggedInAsGuest; - - internal byte[] Blob; - - internal SmbComSessionSetupAndXResponse(ServerMessageBlock andx) : base(andx) - { - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - IsLoggedInAsGuest = (buffer[bufferIndex] & 0x01) == 0x01 ? true : false; - bufferIndex += 2; - if (ExtendedSecurity) - { - int blobLength = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Blob = new byte[blobLength]; - } - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - int start = bufferIndex; - if (ExtendedSecurity) - { - Array.Copy(buffer, bufferIndex, Blob, 0, Blob.Length); - bufferIndex += Blob.Length; - } - _nativeOs = ReadString(buffer, bufferIndex); - bufferIndex += StringWireLength(_nativeOs, bufferIndex); - _nativeLanMan = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode - ); - bufferIndex += StringWireLength(_nativeLanMan, bufferIndex); - if (!ExtendedSecurity) - { - _primaryDomain = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode - ); - bufferIndex += StringWireLength(_primaryDomain, bufferIndex); - } - return bufferIndex - start; - } - - public override string ToString() - { - string result = "SmbComSessionSetupAndXResponse[" + base.ToString() + - ",isLoggedInAsGuest=" + IsLoggedInAsGuest + ",nativeOs=" + _nativeOs + ",nativeLanMan=" - + _nativeLanMan + ",primaryDomain=" + _primaryDomain + "]"; - return result; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs deleted file mode 100644 index b3aeaaf7d0..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransaction.cs +++ /dev/null @@ -1,346 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal abstract class SmbComTransaction : ServerMessageBlock - { - private static readonly int DefaultMaxDataCount = Config.GetInt("jcifs.smb.client.transaction_buf_size" - , TransactionBufSize) - 512; - - private const int PrimarySetupOffset = 61; - - private const int SecondaryParameterOffset = 51; - - private const int DisconnectTid = unchecked(0x01); - - private const int OneWayTransaction = unchecked(0x02); - - private const int PaddingSize = 2; - - private int _flags = unchecked(0x00); - - private int _fid; - - private int _pad; - - private int _pad1; - - private bool _hasMore = true; - - private bool _isPrimary = true; - - private int _bufParameterOffset; - - private int _bufDataOffset; - - internal const int TransactionBufSize = unchecked(0xFFFF); - - internal const byte Trans2FindFirst2 = unchecked(unchecked(0x01)); - - internal const byte Trans2FindNext2 = unchecked(unchecked(0x02)); - - internal const byte Trans2QueryFsInformation = unchecked(unchecked(0x03)); - - internal const byte Trans2QueryPathInformation = unchecked(unchecked(0x05)); - - internal const byte Trans2GetDfsReferral = unchecked(unchecked(0x10)); - - internal const byte Trans2SetFileInformation = unchecked(unchecked(0x08)); - - internal const int NetShareEnum = unchecked(0x0000); - - internal const int NetServerEnum2 = unchecked(0x0068); - - internal const int NetServerEnum3 = unchecked(0x00D7); - - internal const byte TransPeekNamedPipe = unchecked(unchecked(0x23 - )); - - internal const byte TransWaitNamedPipe = unchecked(unchecked(0x53 - )); - - internal const byte TransCallNamedPipe = unchecked(unchecked(0x54 - )); - - internal const byte TransTransactNamedPipe = unchecked(unchecked(0x26)); - - protected internal int primarySetupOffset; - - protected internal int secondaryParameterOffset; - - protected internal int ParameterCount; - - protected internal int ParameterOffset; - - protected internal int ParameterDisplacement; - - protected internal int DataCount; - - protected internal int DataOffset; - - protected internal int DataDisplacement; - - internal int TotalParameterCount; - - internal int TotalDataCount; - - internal int MaxParameterCount; - - internal int MaxDataCount = DefaultMaxDataCount; - - internal byte MaxSetupCount; - - internal int Timeout = 0; - - internal int SetupCount = 1; - - internal byte SubCommand; - - internal string Name = string.Empty; - - internal int MaxBufferSize; - - internal byte[] TxnBuf; - - public SmbComTransaction() - { - // relative to headerStart - // set in SmbTransport.sendTransaction() before nextElement called - MaxParameterCount = 1024; - primarySetupOffset = PrimarySetupOffset; - secondaryParameterOffset = SecondaryParameterOffset; - } - - internal override void Reset() - { - base.Reset(); - _isPrimary = _hasMore = true; - } - - internal virtual void Reset(int key, string lastName) - { - Reset(); - } - - public virtual bool MoveNext() - { - return _hasMore; - } - - public virtual object Current() - { - if (_isPrimary) - { - _isPrimary = false; - ParameterOffset = primarySetupOffset + (SetupCount * 2) + 2; - if (Command != SmbComNtTransact) - { - if (Command == SmbComTransaction && IsResponse() == false) - { - ParameterOffset += StringWireLength(Name, ParameterOffset); - } - } - else - { - if (Command == SmbComNtTransact) - { - ParameterOffset += 2; - } - } - _pad = ParameterOffset % PaddingSize; - _pad = _pad == 0 ? 0 : PaddingSize - _pad; - ParameterOffset += _pad; - TotalParameterCount = WriteParametersWireFormat(TxnBuf, _bufParameterOffset); - _bufDataOffset = TotalParameterCount; - // data comes right after data - int available = MaxBufferSize - ParameterOffset; - ParameterCount = Math.Min(TotalParameterCount, available); - available -= ParameterCount; - DataOffset = ParameterOffset + ParameterCount; - _pad1 = DataOffset % PaddingSize; - _pad1 = _pad1 == 0 ? 0 : PaddingSize - _pad1; - DataOffset += _pad1; - TotalDataCount = WriteDataWireFormat(TxnBuf, _bufDataOffset); - DataCount = Math.Min(TotalDataCount, available); - } - else - { - if (Command != SmbComNtTransact) - { - Command = SmbComTransactionSecondary; - } - else - { - Command = SmbComNtTransactSecondary; - } - // totalParameterCount and totalDataCount are set ok from primary - ParameterOffset = SecondaryParameterOffset; - if ((TotalParameterCount - ParameterDisplacement) > 0) - { - _pad = ParameterOffset % PaddingSize; - _pad = _pad == 0 ? 0 : PaddingSize - _pad; - ParameterOffset += _pad; - } - // caclulate parameterDisplacement before calculating new parameterCount - ParameterDisplacement += ParameterCount; - int available = MaxBufferSize - ParameterOffset - _pad; - ParameterCount = Math.Min(TotalParameterCount - ParameterDisplacement, available); - available -= ParameterCount; - DataOffset = ParameterOffset + ParameterCount; - _pad1 = DataOffset % PaddingSize; - _pad1 = _pad1 == 0 ? 0 : PaddingSize - _pad1; - DataOffset += _pad1; - DataDisplacement += DataCount; - available -= _pad1; - DataCount = Math.Min(TotalDataCount - DataDisplacement, available); - } - if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount && (DataDisplacement - + DataCount) >= TotalDataCount) - { - _hasMore = false; - } - return this; - - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(TotalParameterCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(TotalDataCount, dst, dstIndex); - dstIndex += 2; - if (Command != SmbComTransactionSecondary) - { - WriteInt2(MaxParameterCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(MaxDataCount, dst, dstIndex); - dstIndex += 2; - dst[dstIndex++] = MaxSetupCount; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved1 - WriteInt2(_flags, dst, dstIndex); - dstIndex += 2; - WriteInt4(Timeout, dst, dstIndex); - dstIndex += 4; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved2 - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - WriteInt2(ParameterCount, dst, dstIndex); - dstIndex += 2; - // writeInt2(( parameterCount == 0 ? 0 : parameterOffset ), dst, dstIndex ); - WriteInt2(ParameterOffset, dst, dstIndex); - dstIndex += 2; - if (Command == SmbComTransactionSecondary) - { - WriteInt2(ParameterDisplacement, dst, dstIndex); - dstIndex += 2; - } - WriteInt2(DataCount, dst, dstIndex); - dstIndex += 2; - WriteInt2((DataCount == 0 ? 0 : DataOffset), dst, dstIndex); - dstIndex += 2; - if (Command == SmbComTransactionSecondary) - { - WriteInt2(DataDisplacement, dst, dstIndex); - dstIndex += 2; - } - else - { - dst[dstIndex++] = unchecked((byte)SetupCount); - dst[dstIndex++] = unchecked(unchecked(0x00)); - // Reserved3 - dstIndex += WriteSetupWireFormat(dst, dstIndex); - } - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - int p = _pad; - if (Command == SmbComTransaction && IsResponse() == false) - { - dstIndex += WriteString(Name, dst, dstIndex); - } - if (ParameterCount > 0) - { - while (p-- > 0) - { - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - // Pad - Array.Copy(TxnBuf, _bufParameterOffset, dst, dstIndex, ParameterCount); - dstIndex += ParameterCount; - } - if (DataCount > 0) - { - p = _pad1; - while (p-- > 0) - { - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - // Pad1 - Array.Copy(TxnBuf, _bufDataOffset, dst, dstIndex, DataCount); - _bufDataOffset += DataCount; - dstIndex += DataCount; - } - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - internal abstract int WriteSetupWireFormat(byte[] dst, int dstIndex); - - internal abstract int WriteParametersWireFormat(byte[] dst, int dstIndex); - - internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex); - - internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ); - - internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len); - - internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len); - - public override string ToString() - { - return base.ToString() + ",totalParameterCount=" + TotalParameterCount - + ",totalDataCount=" + TotalDataCount + ",maxParameterCount=" + MaxParameterCount - + ",maxDataCount=" + MaxDataCount + ",maxSetupCount=" + (int)MaxSetupCount + ",flags=0x" - + Hexdump.ToHexString(_flags, 2) + ",timeout=" + Timeout + ",parameterCount=" + - ParameterCount + ",parameterOffset=" + ParameterOffset + ",parameterDisplacement=" - + ParameterDisplacement + ",dataCount=" + DataCount + ",dataOffset=" + DataOffset - + ",dataDisplacement=" + DataDisplacement + ",setupCount=" + SetupCount + ",pad=" - + _pad + ",pad1=" + _pad1; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs deleted file mode 100644 index 35f87594d6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTransactionResponse.cs +++ /dev/null @@ -1,206 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal abstract class SmbComTransactionResponse : ServerMessageBlock - { - private const int SetupOffset = 61; - - private const int DisconnectTid = unchecked(0x01); - - private const int OneWayTransaction = unchecked(0x02); - - private int _pad; - - private int _pad1; - - private bool _parametersDone; - - private bool _dataDone; - - protected internal int TotalParameterCount; - - protected internal int TotalDataCount; - - protected internal int ParameterCount; - - protected internal int ParameterOffset; - - protected internal int ParameterDisplacement; - - protected internal int DataOffset; - - protected internal int DataDisplacement; - - protected internal int SetupCount; - - protected internal int BufParameterStart; - - protected internal int BufDataStart; - - internal int DataCount; - - internal byte SubCommand; - - internal bool HasMore = true; - - internal bool IsPrimary = true; - - internal byte[] TxnBuf; - - internal int Status; - - internal int NumEntries; - - internal IFileEntry[] Results; - - public SmbComTransactionResponse() - { - // relative to headerStart - TxnBuf = null; - } - - internal override void Reset() - { - base.Reset(); - BufDataStart = 0; - IsPrimary = HasMore = true; - _parametersDone = _dataDone = false; - } - - public virtual bool MoveNext() - { - return ErrorCode == 0 && HasMore; - } - - public virtual object Current() - { - if (IsPrimary) - { - IsPrimary = false; - } - return this; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - TotalParameterCount = ReadInt2(buffer, bufferIndex); - if (BufDataStart == 0) - { - BufDataStart = TotalParameterCount; - } - bufferIndex += 2; - TotalDataCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 4; - // Reserved - ParameterCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - ParameterOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - ParameterDisplacement = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DataCount = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DataOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - DataDisplacement = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - SetupCount = buffer[bufferIndex] & unchecked(0xFF); - bufferIndex += 2; - if (SetupCount != 0) - { - if (Log.Level > 2) - { - Log.WriteLine("setupCount is not zero: " + SetupCount); - } - } - return bufferIndex - start; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - _pad = _pad1 = 0; - int n; - if (ParameterCount > 0) - { - bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart); - Array.Copy(buffer, bufferIndex, TxnBuf, BufParameterStart + ParameterDisplacement - , ParameterCount); - bufferIndex += ParameterCount; - } - if (DataCount > 0) - { - bufferIndex += _pad1 = DataOffset - (bufferIndex - HeaderStart); - Array.Copy(buffer, bufferIndex, TxnBuf, BufDataStart + DataDisplacement, - DataCount); - bufferIndex += DataCount; - } - if (!_parametersDone && (ParameterDisplacement + ParameterCount) == TotalParameterCount) - { - _parametersDone = true; - } - if (!_dataDone && (DataDisplacement + DataCount) == TotalDataCount) - { - _dataDone = true; - } - if (_parametersDone && _dataDone) - { - HasMore = false; - ReadParametersWireFormat(TxnBuf, BufParameterStart, TotalParameterCount); - ReadDataWireFormat(TxnBuf, BufDataStart, TotalDataCount); - } - return _pad + ParameterCount + _pad1 + DataCount; - } - - internal abstract int WriteSetupWireFormat(byte[] dst, int dstIndex); - - internal abstract int WriteParametersWireFormat(byte[] dst, int dstIndex); - - internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex); - - internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ); - - internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len); - - internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len); - - public override string ToString() - { - return base.ToString() + ",totalParameterCount=" + TotalParameterCount - + ",totalDataCount=" + TotalDataCount + ",parameterCount=" + ParameterCount + ",parameterOffset=" - + ParameterOffset + ",parameterDisplacement=" + ParameterDisplacement + ",dataCount=" - + DataCount + ",dataOffset=" + DataOffset + ",dataDisplacement=" + DataDisplacement - + ",setupCount=" + SetupCount + ",pad=" + _pad + ",pad1=" + _pad1; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs deleted file mode 100644 index 67ad04f5f6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndX.cs +++ /dev/null @@ -1,226 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComTreeConnectAndX : AndXServerMessageBlock - { - private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords" - , true); - - private SmbSession _session; - - private bool _disconnectTid = false; - - private string _service; - - private byte[] _password; - - private int _passwordLength; - - internal string path; - - private static byte[] _batchLimits = { 1, 1, 1, 1, 1, 1, 1, 1, 0 }; - - static SmbComTreeConnectAndX() - { - string s; - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) != - null) - { - _batchLimits[0] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory")) - != null) - { - _batchLimits[2] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Delete")) != null) - { - _batchLimits[3] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory")) - != null) - { - _batchLimits[4] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.OpenAndX")) != null) - { - _batchLimits[5] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Rename")) != null) - { - _batchLimits[6] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.Transaction")) != null) - { - _batchLimits[7] = byte.Parse(s); - } - if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation")) - != null) - { - _batchLimits[8] = byte.Parse(s); - } - } - - internal SmbComTreeConnectAndX(SmbSession session, string path, string service, ServerMessageBlock - andx) : base(andx) - { - this._session = session; - this.path = path; - this._service = service; - Command = SmbComTreeConnectAndx; - } - - internal override int GetBatchLimit(byte command) - { - int c = command & unchecked(0xFF); - switch (c) - { - case SmbComCheckDirectory: - { - // why isn't this just return batchLimits[c]? - return _batchLimits[0]; - } - - case SmbComCreateDirectory: - { - return _batchLimits[2]; - } - - case SmbComDelete: - { - return _batchLimits[3]; - } - - case SmbComDeleteDirectory: - { - return _batchLimits[4]; - } - - case SmbComOpenAndx: - { - return _batchLimits[5]; - } - - case SmbComRename: - { - return _batchLimits[6]; - } - - case SmbComTransaction: - { - return _batchLimits[7]; - } - - case SmbComQueryInformation: - { - return _batchLimits[8]; - } - } - return 0; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal - || _session.Auth.Password.Length > 0)) - { - if (_session.transport.Server.EncryptedPasswords) - { - // encrypted - _password = _session.Auth.GetAnsiHash(_session.transport.Server.EncryptionKey); - _passwordLength = _password.Length; - } - else - { - if (DisablePlainTextPasswords) - { - throw new RuntimeException("Plain text passwords are disabled"); - } - // plain text - _password = new byte[(_session.Auth.Password.Length + 1) * 2]; - _passwordLength = WriteString(_session.Auth.Password, _password, 0); - } - } - else - { - // no password in tree connect - _passwordLength = 1; - } - dst[dstIndex++] = _disconnectTid ? unchecked((byte)unchecked(0x01)) : unchecked( - (byte)unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - WriteInt2(_passwordLength, dst, dstIndex); - return 4; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal - || _session.Auth.Password.Length > 0)) - { - Array.Copy(_password, 0, dst, dstIndex, _passwordLength); - dstIndex += _passwordLength; - } - else - { - // no password in tree connect - dst[dstIndex++] = unchecked(unchecked(0x00)); - } - dstIndex += WriteString(path, dst, dstIndex); - try - { -// Array.Copy(Runtime.GetBytesForString(_service, "ASCII"), 0, dst, dstIndex - //, _service.Length); - Array.Copy(Runtime.GetBytesForString(_service, "UTF-8"), 0, dst, dstIndex - , _service.Length); - } - catch (UnsupportedEncodingException) - { - return 0; - } - dstIndex += _service.Length; - dst[dstIndex++] = unchecked((byte)('\0')); - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - string result = "SmbComTreeConnectAndX[" + base.ToString() + ",disconnectTid=" - + _disconnectTid + ",passwordLength=" + _passwordLength + ",password=" + Hexdump. - ToHexString(_password, _passwordLength, 0) + ",path=" + path + ",service=" + _service - + "]"; - return result; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs deleted file mode 100644 index add660b266..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeConnectAndXResponse.cs +++ /dev/null @@ -1,84 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class SmbComTreeConnectAndXResponse : AndXServerMessageBlock - { - private const int SmbSupportSearchBits = unchecked(0x0001); - - private const int SmbShareIsInDfs = unchecked(0x0002); - - internal bool SupportSearchBits; - - internal bool ShareIsInDfs; - - internal string Service; - - internal string NativeFileSystem = string.Empty; - - internal SmbComTreeConnectAndXResponse(ServerMessageBlock andx) : base(andx) - { - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - SupportSearchBits = (buffer[bufferIndex] & SmbSupportSearchBits) == SmbSupportSearchBits; - ShareIsInDfs = (buffer[bufferIndex] & SmbShareIsInDfs) == SmbShareIsInDfs; - return 2; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - int start = bufferIndex; - int len = ReadStringLength(buffer, bufferIndex, 32); - try - { - //Service = Runtime.GetStringForBytes(buffer, bufferIndex, len, "ASCII"); - Service = Runtime.GetStringForBytes(buffer, bufferIndex, len, "UTF-8"); - } - catch (UnsupportedEncodingException) - { - return 0; - } - bufferIndex += len + 1; - // win98 observed not returning nativeFileSystem - return bufferIndex - start; - } - - public override string ToString() - { - string result = "SmbComTreeConnectAndXResponse[" + base.ToString() + ",supportSearchBits=" - + SupportSearchBits + ",shareIsInDfs=" + ShareIsInDfs + ",service=" + Service + - ",nativeFileSystem=" + NativeFileSystem + "]"; - return result; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs deleted file mode 100644 index d9eb5b2ebe..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComTreeDisconnect.cs +++ /dev/null @@ -1,52 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComTreeDisconnect : ServerMessageBlock - { - public SmbComTreeDisconnect() - { - Command = SmbComTreeDisconnect; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComTreeDisconnect[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs deleted file mode 100644 index 418a69d1d3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWrite.cs +++ /dev/null @@ -1,106 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal class SmbComWrite : ServerMessageBlock - { - private int _fid; - - private int _count; - - private int _offset; - - private int _remaining; - - private int _off; - - private byte[] _b; - - public SmbComWrite() - { - Command = SmbComWrite; - } - - internal SmbComWrite(int fid, int offset, int remaining, byte[] b, int off, int len - ) - { - this._fid = fid; - _count = len; - this._offset = offset; - this._remaining = remaining; - this._b = b; - this._off = off; - Command = SmbComWrite; - } - - internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int - off, int len) - { - this._fid = fid; - this._offset = (int)(offset & unchecked(0xFFFFFFFFL)); - this._remaining = remaining; - this._b = b; - this._off = off; - _count = len; - Digest = null; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_fid, dst, dstIndex); - dstIndex += 2; - WriteInt2(_count, dst, dstIndex); - dstIndex += 2; - WriteInt4(_offset, dst, dstIndex); - dstIndex += 4; - WriteInt2(_remaining, dst, dstIndex); - dstIndex += 2; - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - dst[dstIndex++] = 0x01; - WriteInt2(_count, dst, dstIndex); - dstIndex += 2; - Array.Copy(_b, _off, dst, dstIndex, _count); - dstIndex += _count; - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComWrite[" + base.ToString() + ",fid=" + _fid + ",count=" + - _count + ",offset=" + _offset + ",remaining=" + _remaining + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs deleted file mode 100644 index b182fd7ffd..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndX.cs +++ /dev/null @@ -1,150 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal class SmbComWriteAndX : AndXServerMessageBlock - { - private static readonly int ReadAndxBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX" - , 1); - - private static readonly int CloseBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.Close" - , 1); - - private int _fid; - - private int _remaining; - - private int _dataLength; - - private int _dataOffset; - - private int _off; - - private byte[] _b; - - private long _offset; - - private int _pad; - - internal int WriteMode; - - public SmbComWriteAndX() : base(null) - { - Command = SmbComWriteAndx; - } - - internal SmbComWriteAndX(int fid, long offset, int remaining, byte[] b, int off, - int len, ServerMessageBlock andx) : base(andx) - { - this._fid = fid; - this._offset = offset; - this._remaining = remaining; - this._b = b; - this._off = off; - _dataLength = len; - Command = SmbComWriteAndx; - } - - internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int - off, int len) - { - this._fid = fid; - this._offset = offset; - this._remaining = remaining; - this._b = b; - this._off = off; - _dataLength = len; - Digest = null; - } - - internal override int GetBatchLimit(byte command) - { - if (command == SmbComReadAndx) - { - return ReadAndxBatchLimit; - } - if (command == SmbComClose) - { - return CloseBatchLimit; - } - return 0; - } - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - _dataOffset = (dstIndex - HeaderStart) + 26; - // 26 = off from here to pad - _pad = (_dataOffset - HeaderStart) % 4; - _pad = _pad == 0 ? 0 : 4 - _pad; - _dataOffset += _pad; - WriteInt2(_fid, dst, dstIndex); - dstIndex += 2; - WriteInt4(_offset, dst, dstIndex); - dstIndex += 4; - for (int i = 0; i < 4; i++) - { - dst[dstIndex++] = 0xFF; - } - WriteInt2(WriteMode, dst, dstIndex); - dstIndex += 2; - WriteInt2(_remaining, dst, dstIndex); - dstIndex += 2; - dst[dstIndex++] = 0x00; - dst[dstIndex++] =0x00; - WriteInt2(_dataLength, dst, dstIndex); - dstIndex += 2; - WriteInt2(_dataOffset, dst, dstIndex); - dstIndex += 2; - WriteInt4(_offset >> 32, dst, dstIndex); - dstIndex += 4; - return dstIndex - start; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - while (_pad-- > 0) - { - dst[dstIndex++] = 0xEE; - } - Array.Copy(_b, _off, dst, dstIndex, _dataLength); - dstIndex += _dataLength; - return dstIndex - start; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - return 0; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComWriteAndX[" + base.ToString() + ",fid=" + _fid + ",offset=" - + _offset + ",writeMode=" + WriteMode + ",remaining=" + _remaining + ",dataLength=" - + _dataLength + ",dataOffset=" + _dataOffset + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs deleted file mode 100644 index c6749b6cbb..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteAndXResponse.cs +++ /dev/null @@ -1,50 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComWriteAndXResponse : AndXServerMessageBlock - { - internal long Count; - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL); - return 8; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComWriteAndXResponse[" + base.ToString() + ",count=" + Count + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs deleted file mode 100644 index 785d406c15..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbComWriteResponse.cs +++ /dev/null @@ -1,50 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class SmbComWriteResponse : ServerMessageBlock - { - internal long Count; - - internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex - ) - { - Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL); - return 8; - } - - internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) - { - return 0; - } - - public override string ToString() - { - return "SmbComWriteResponse[" + base.ToString() + ",count=" + Count + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs deleted file mode 100644 index 0793c75415..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbConstants.cs +++ /dev/null @@ -1,302 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections.Generic; -using System.Net; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal static class SmbConstants - { - public static readonly int DefaultPort = 445; - - public static readonly int DefaultMaxMpxCount = 10; - - public static readonly int DefaultResponseTimeout = 30000; - - public static readonly int DefaultSoTimeout = 35000; - - public static readonly int DefaultRcvBufSize = 60416; - - public static readonly int DefaultSndBufSize = 16644; - - public static readonly int DefaultSsnLimit = 250; - - public static readonly int DefaultConnTimeout = 35000; - - public static readonly IPAddress Laddr = Config.GetLocalHost(); - - public static readonly int Lport = Config.GetInt("jcifs.smb.client.lport", 0); - - public static readonly int MaxMpxCount = Config.GetInt("jcifs.smb.client.maxMpxCount", DefaultMaxMpxCount - ); - - public static readonly int SndBufSize = Config.GetInt("jcifs.smb.client.snd_buf_size", DefaultSndBufSize - ); - - public static readonly int RcvBufSize = Config.GetInt("jcifs.smb.client.rcv_buf_size", DefaultRcvBufSize - ); - - public static readonly bool UseUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode", - true); - - public static readonly bool ForceUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode" - , false); - - public static readonly bool UseNtstatus = Config.GetBoolean("jcifs.smb.client.useNtStatus" - , true); - - public static readonly bool Signpref = Config.GetBoolean("jcifs.smb.client.signingPreferred" - , false); - - public static readonly bool UseNtsmbs = Config.GetBoolean("jcifs.smb.client.useNTSmbs", true - ); - - public static readonly bool UseExtsec = Config.GetBoolean("jcifs.smb.client.useExtendedSecurity" - , true); - - public static readonly string NetbiosHostname = Config.GetProperty("jcifs.netbios.hostname" - , null); - - public static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3); - - public static readonly int FlagsNone = unchecked(0x00); - - public static readonly int FlagsLockAndReadWriteAndUnlock = unchecked(0x01); - - public static readonly int FlagsReceiveBufferPosted = unchecked(0x02); - - public static readonly int FlagsPathNamesCaseless = unchecked(0x08); - - public static readonly int FlagsPathNamesCanonicalized = unchecked(0x10); - - public static readonly int FlagsOplockRequestedOrGranted = unchecked(0x20); - - public static readonly int FlagsNotifyOfModifyAction = unchecked(0x40); - - public static readonly int FlagsResponse = unchecked(0x80); - - public static readonly int Flags2None = unchecked(0x0000); - - public static readonly int Flags2LongFilenames = unchecked(0x0001); - - public static readonly int Flags2ExtendedAttributes = unchecked(0x0002); - - public static readonly int Flags2SecuritySignatures = unchecked(0x0004); - - public static readonly int Flags2ExtendedSecurityNegotiation = unchecked(0x0800); - - public static readonly int Flags2ResolvePathsInDfs = unchecked(0x1000); - - public static readonly int Flags2PermitReadIfExecutePerm = unchecked(0x2000); - - public static readonly int Flags2Status32 = unchecked(0x4000); - - public static readonly int Flags2Unicode = unchecked(0x8000); - - public static readonly int CapNone = unchecked(0x0000); - - public static readonly int CapRawMode = unchecked(0x0001); - - public static readonly int CapMpxMode = unchecked(0x0002); - - public static readonly int CapUnicode = unchecked(0x0004); - - public static readonly int CapLargeFiles = unchecked(0x0008); - - public static readonly int CapNtSmbs = unchecked(0x0010); - - public static readonly int CapRpcRemoteApis = unchecked(0x0020); - - public static readonly int CapStatus32 = unchecked(0x0040); - - public static readonly int CapLevelIiOplocks = unchecked(0x0080); - - public static readonly int CapLockAndRead = unchecked(0x0100); - - public static readonly int CapNtFind = unchecked(0x0200); - - public static readonly int CapDfs = unchecked(0x1000); - - public static readonly int CapExtendedSecurity = unchecked((int)(0x80000000)); - - public static readonly int AttrReadonly = unchecked(0x01); - - public static readonly int AttrHidden = unchecked(0x02); - - public static readonly int AttrSystem = unchecked(0x04); - - public static readonly int AttrVolume = unchecked(0x08); - - public static readonly int AttrDirectory = unchecked(0x10); - - public static readonly int AttrArchive = unchecked(0x20); - - public static readonly int AttrCompressed = unchecked(0x800); - - public static readonly int AttrNormal = unchecked(0x080); - - public static readonly int AttrTemporary = unchecked(0x100); - - public static readonly int FileReadData = unchecked(0x00000001); - - public static readonly int FileWriteData = unchecked(0x00000002); - - public static readonly int FileAppendData = unchecked(0x00000004); - - public static readonly int FileReadEa = unchecked(0x00000008); - - public static readonly int FileWriteEa = unchecked(0x00000010); - - public static readonly int FileExecute = unchecked(0x00000020); - - public static readonly int FileDelete = unchecked(0x00000040); - - public static readonly int FileReadAttributes = unchecked(0x00000080); - - public static readonly int FileWriteAttributes = unchecked(0x00000100); - - public static readonly int Delete = unchecked(0x00010000); - - public static readonly int ReadControl = unchecked(0x00020000); - - public static readonly int WriteDac = unchecked(0x00040000); - - public static readonly int WriteOwner = unchecked(0x00080000); - - public static readonly int Synchronize = unchecked(0x00100000); - - public static readonly int GenericAll = unchecked(0x10000000); - - public static readonly int GenericExecute = unchecked(0x20000000); - - public static readonly int GenericWrite = unchecked(0x40000000); - - public static readonly int GenericRead = unchecked((int)(0x80000000)); - - public static readonly int FlagsTargetMustBeFile = unchecked(0x0001); - - public static readonly int FlagsTargetMustBeDirectory = unchecked(0x0002); - - public static readonly int FlagsCopyTargetModeAscii = unchecked(0x0004); - - public static readonly int FlagsCopySourceModeAscii = unchecked(0x0008); - - public static readonly int FlagsVerifyAllWrites = unchecked(0x0010); - - public static readonly int FlagsTreeCopy = unchecked(0x0020); - - public static readonly int OpenFunctionFailIfExists = unchecked(0x0000); - - public static readonly int OpenFunctionOverwriteIfExists = unchecked(0x0020); - - public static readonly int Pid = (int)(new Random().NextDouble() * 65536d); - - public static readonly int SecurityShare = unchecked(0x00); - - public static readonly int SecurityUser = unchecked(0x01); - - public static readonly int CmdOffset = 4; - - public static readonly int ErrorCodeOffset = 5; - - public static readonly int FlagsOffset = 9; - - public static readonly int SignatureOffset = 14; - - public static readonly int TidOffset = 24; - - public static readonly int HeaderLength = 32; - - public static readonly long MillisecondsBetween1970And1601 = 11644473600000L; - - public static readonly TimeZoneInfo Tz = TimeZoneInfo.Local; - - public static readonly bool UseBatching = Config.GetBoolean("jcifs.smb.client.useBatching" - , true); - - public static readonly string OemEncoding = Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding - ); - - public static readonly string UniEncoding = "UTF-16LE"; - - public static readonly int DefaultFlags2 = Flags2LongFilenames | Flags2ExtendedAttributes - | (UseExtsec ? Flags2ExtendedSecurityNegotiation : 0) | (Signpref ? Flags2SecuritySignatures - : 0) | (UseNtstatus ? Flags2Status32 : 0) | (UseUnicode ? Flags2Unicode : 0 - ); - - public static readonly int DefaultCapabilities = (UseNtsmbs ? CapNtSmbs : 0) | (UseNtstatus - ? CapStatus32 : 0) | (UseUnicode ? CapUnicode : 0) | CapDfs; - - public static readonly int Flags2 = Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2 - ); - - public static readonly int Capabilities = Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities - ); - - public static readonly bool TcpNodelay = Config.GetBoolean("jcifs.smb.client.tcpNoDelay", - false); - - public static readonly int ResponseTimeout = Config.GetInt("jcifs.smb.client.responseTimeout" - , DefaultResponseTimeout); - - public static readonly List Connections = new List(); - - public static readonly int SsnLimit = Config.GetInt("jcifs.smb.client.ssnLimit", DefaultSsnLimit - ); - - public static readonly int SoTimeout = Config.GetInt("jcifs.smb.client.soTimeout", DefaultSoTimeout - ); - - public static readonly int ConnTimeout = Config.GetInt("jcifs.smb.client.connTimeout", DefaultConnTimeout - ); - - public static readonly string NativeOs = Config.GetProperty("jcifs.smb.client.nativeOs", Runtime - .GetProperty("os.name")); - - public static readonly string NativeLanman = Config.GetProperty("jcifs.smb.client.nativeLanMan" - , "jCIFS"); - - public static readonly int VcNumber = 1; - - public static SmbTransport NullTransport = new SmbTransport(null, 0, null, 0); - // file attribute encoding - // extended file attribute encoding(others same as above) - // access mask encoding - // 1 - // 2 - // 3 - // 4 - // 5 - // 6 - // 7 - // 8 - // 9 - // 16 - // 17 - // 18 - // 19 - // 20 - // 28 - // 29 - // 30 - // 31 - // flags for move and copy - // open function - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs deleted file mode 100644 index ea8a0b8466..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbException.cs +++ /dev/null @@ -1,212 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - ///

- /// There are hundreds of error codes that may be returned by a CIFS - /// server. - /// - /// - /// There are hundreds of error codes that may be returned by a CIFS - /// server. Rather than represent each with it's own Exception - /// class, this class represents all of them. For many of the popular - /// error codes, constants and text messages like "The device is not ready" - /// are provided. - ///

- /// The jCIFS client maps DOS error codes to NTSTATUS codes. This means that - /// the user may recieve a different error from a legacy server than that of - /// a newer varient such as Windows NT and above. If you should encounter - /// such a case, please report it to jcifs at samba dot org and we will - /// change the mapping. - /// - - public class SmbException : IOException - { - - internal static string GetMessageByCode(int errcode) - { - if (errcode == 0) - { - return "NT_STATUS_SUCCESS"; - } - if ((errcode & unchecked((int)(0xC0000000))) == unchecked((int)(0xC0000000))) - { - int min = 1; - int max = NtStatus.NtStatusCodes.Length - 1; - while (max >= min) - { - int mid = (min + max) / 2; - if (errcode > NtStatus.NtStatusCodes[mid]) - { - min = mid + 1; - } - else - { - if (errcode < NtStatus.NtStatusCodes[mid]) - { - max = mid - 1; - } - else - { - return NtStatus.NtStatusMessages[mid]; - } - } - } - } - else - { - int min = 0; - int max = DosError.DosErrorCodes.Length - 1; - while (max >= min) - { - int mid = (min + max) / 2; - if (errcode > DosError.DosErrorCodes[mid][0]) - { - min = mid + 1; - } - else - { - if (errcode < DosError.DosErrorCodes[mid][0]) - { - max = mid - 1; - } - else - { - return DosError.DosErrorMessages[mid]; - } - } - } - } - return "0x" + Hexdump.ToHexString(errcode, 8); - } - - internal static int GetStatusByCode(int errcode) - { - if ((errcode & unchecked((int)(0xC0000000))) != 0) - { - return errcode; - } - int min = 0; - int max = DosError.DosErrorCodes.Length - 1; - while (max >= min) - { - int mid = (min + max) / 2; - if (errcode > DosError.DosErrorCodes[mid][0]) - { - min = mid + 1; - } - else - { - if (errcode < DosError.DosErrorCodes[mid][0]) - { - max = mid - 1; - } - else - { - return DosError.DosErrorCodes[mid][1]; - } - } - } - return NtStatus.NtStatusUnsuccessful; - } - - internal static string GetMessageByWinerrCode(int errcode) - { - int min = 0; - int max = WinError.WinerrCodes.Length - 1; - while (max >= min) - { - int mid = (min + max) / 2; - if (errcode > WinError.WinerrCodes[mid]) - { - min = mid + 1; - } - else - { - if (errcode < WinError.WinerrCodes[mid]) - { - max = mid - 1; - } - else - { - return WinError.WinerrMessages[mid]; - } - } - } - return errcode + string.Empty; - } - - private int _status; - - private Exception _rootCause; - - public SmbException() - { - } - - internal SmbException(int errcode, Exception rootCause) : base(GetMessageByCode(errcode - )) - { - _status = GetStatusByCode(errcode); - this._rootCause = rootCause; - } - - public SmbException(string msg) : base(msg) - { - _status = NtStatus.NtStatusUnsuccessful; - } - - public SmbException(string msg, Exception rootCause) : base(msg) - { - this._rootCause = rootCause; - _status = NtStatus.NtStatusUnsuccessful; - } - - public SmbException(int errcode, bool winerr) : base(winerr ? GetMessageByWinerrCode - (errcode) : GetMessageByCode(errcode)) - { - _status = winerr ? errcode : GetStatusByCode(errcode); - } - - public virtual int GetNtStatus() - { - return _status; - } - - public virtual Exception GetRootCause() - { - return _rootCause; - } - - public override string ToString() - { - if (_rootCause != null) - { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - Runtime.PrintStackTrace(_rootCause, pw); - return base.ToString() + "\n" + sw; - } - return base.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs deleted file mode 100644 index 7fd9f0d84e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFile.cs +++ /dev/null @@ -1,3735 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; -using SharpCifs.Dcerpc; -using SharpCifs.Dcerpc.Msrpc; -using SharpCifs.Netbios; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - ///

This class represents a resource on an SMB network. - /// - /// This class represents a resource on an SMB network. Mainly these - /// resources are files and directories however an SmbFile - /// may also refer to servers and workgroups. If the resource is a file or - /// directory the methods of SmbFile follow the behavior of - /// the well known - /// Sharpen.FilePath - /// class. One fundamental difference - /// is the usage of a URL scheme [1] to specify the target file or - /// directory. SmbFile URLs have the following syntax: - ///
-    /// smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]]
-    /// 
- /// This example: - ///
-    /// smb://storage15/public/foo.txt
-    /// 
- /// would reference the file foo.txt in the share - /// public on the server storage15. In addition - /// to referencing files and directories, jCIFS can also address servers, - /// and workgroups. - ///

- /// Important: all SMB URLs that represent - /// workgroups, servers, shares, or directories require a trailing slash '/'. - /// - ///

- /// When using the java.net.URL class with - /// 'smb://' URLs it is necessary to first call the static - /// jcifs.Config.registerSmbURLHandler(); method. This is required - /// to register the SMB protocol handler. - ///

- /// The userinfo component of the SMB URL (domain;user:pass) must - /// be URL encoded if it contains reserved characters. According to RFC 2396 - /// these characters are non US-ASCII characters and most meta characters - /// however jCIFS will work correctly with anything but '@' which is used - /// to delimit the userinfo component from the server and '%' which is the - /// URL escape character itself. - ///

- /// The server - /// component may a traditional NetBIOS name, a DNS name, or IP - /// address. These name resolution mechanisms and their resolution order - /// can be changed (See Setting Name - /// Resolution Properties). The servername and path components are - /// not case sensitive but the domain, username, and password components - /// are. It is also likely that properties must be specified for jcifs - /// to function (See Setting - /// JCIFS Properties). Here are some examples of SMB URLs with brief - /// descriptions of what they do: - ///

[1] This URL scheme is based largely on the SMB - /// Filesharing URL Scheme IETF draft. - ///

- /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ///
SMB URL Examples
URLDescription
smb://users-nyc;miallen:mypass@angus/tmp/ - /// This URL references a share called tmp on the server - /// angus as user miallen who's password is - /// mypass. - ///
- /// smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt - /// A relativly sophisticated example that references a file - /// msmith1's desktop as user Administrator. Notice the '@' is URL encoded with the '%40' hexcode escape. - ///
smb://angus/ - /// This references only a server. The behavior of some methods is different - /// in this context(e.g. you cannot delete a server) however - /// as you might expect the list method will list the available - /// shares on this server. - ///
smb://myworkgroup/ - /// This syntactically is identical to the above example. However if - /// myworkgroup happends to be a workgroup(which is indeed - /// suggested by the name) the list method will return - /// a list of servers that have registered themselves as members of - /// myworkgroup. - ///
smb:// - /// Just as smb://server/ lists shares and - /// smb://workgroup/ lists servers, the smb:// - /// URL lists all available workgroups on a netbios LAN. Again, - /// in this context many methods are not valid and return default - /// values(e.g. isHidden will always return false). - ///
smb://angus.foo.net/d/jcifs/pipes.doc - /// The server name may also be a DNS name as it is in this example. See - /// Setting Name Resolution Properties - /// for details. - ///
smb://192.168.1.15/ADMIN$/ - /// The server name may also be an IP address. See <a - /// href="../../../resolver.html">Setting Name Resolution Properties - /// for details. - ///
- /// smb://domain;username:password@server/share/path/to/file.txt - /// A prototypical example that uses all the fields. - ///
smb://myworkgroup/angus/ <-- ILLEGAL - /// Despite the hierarchial relationship between workgroups, servers, and - /// filesystems this example is not valid. - ///
- /// smb://server/share/path/to/dir <-- ILLEGAL - /// URLs that represent workgroups, servers, shares, or directories require a trailing slash '/'. - ///
- /// smb://MYGROUP/?SERVER=192.168.10.15 - /// SMB URLs support some query string parameters. In this example - /// the SERVER parameter is used to override the - /// server name service lookup to contact the server 192.168.10.15 - /// (presumably known to be a master - /// browser) for the server list in workgroup MYGROUP. - ///
- ///

A second constructor argument may be specified to augment the URL - /// for better programmatic control when processing many files under - /// a common base. This is slightly different from the corresponding - /// java.io.File usage; a '/' at the beginning of the second - /// parameter will still use the server component of the first parameter. The - /// examples below illustrate the resulting URLs when this second contructor - /// argument is used. - ///

- /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ///
- /// Examples Of SMB URLs When Augmented With A Second Constructor Parameter
- /// First ParameterSecond ParameterResult
- /// smb://host/share/a/b/ - /// - /// c/d/ - /// - /// smb://host/share/a/b/c/d/ - ///
- /// smb://host/share/foo/bar/ - /// - /// /share2/zig/zag - /// - /// smb://host/share2/zig/zag - ///
- /// smb://host/share/foo/bar/ - /// - /// ../zip/ - /// - /// smb://host/share/foo/zip/ - ///
- /// smb://host/share/zig/zag - /// - /// smb://foo/bar/ - /// - /// smb://foo/bar/ - ///
- /// smb://host/share/foo/ - /// - /// ../.././.././../foo/ - /// - /// smb://host/foo/ - ///
- /// smb://host/share/zig/zag - /// - /// / - /// - /// smb://host/ - ///
- /// smb://server/ - /// - /// ../ - /// - /// smb://server/ - ///
- /// smb:// - /// - /// myworkgroup/ - /// - /// smb://myworkgroup/ - ///
- /// smb://myworkgroup/ - /// - /// angus/ - /// - /// smb://myworkgroup/angus/ <-- ILLEGAL
(But if you first create an SmbFile with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second String parameter jCIFS will factor out the 'workgroup'.) - ///
- ///

Instances of the SmbFile class are immutable; that is, - /// once created, the abstract pathname represented by an SmbFile object - /// will never change. - /// - /// Sharpen.FilePath - public class SmbFile : UrlConnection - { - internal const int ORdonly = 0x01; - - internal const int OWronly = 0x02; - - internal const int ORdwr = 0x03; - - internal const int OAppend = 0x04; - - internal const int OCreat = 0x0010; - - internal const int OExcl = 0x0020; - - internal const int OTrunc = 0x0040; - - ///

- /// When specified as the shareAccess constructor parameter, - /// other SMB clients (including other threads making calls into jCIFS) - /// will not be permitted to access the target file and will receive "The - /// file is being accessed by another process" message. - /// - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients (including other threads making calls into jCIFS) - /// will not be permitted to access the target file and will receive "The - /// file is being accessed by another process" message. - /// - public const int FileNoShare = 0x00; - - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to read from the target file while - /// this file is open. - /// - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to read from the target file while - /// this file is open. This constant may be logically OR'd with other share - /// access flags. - /// - public const int FileShareRead = 0x01; - - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to write to the target file while - /// this file is open. - /// - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to write to the target file while - /// this file is open. This constant may be logically OR'd with other share - /// access flags. - /// - public const int FileShareWrite = 0x02; - - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to delete the target file while - /// this file is open. - /// - /// - /// When specified as the shareAccess constructor parameter, - /// other SMB clients will be permitted to delete the target file while - /// this file is open. This constant may be logically OR'd with other share - /// access flags. - /// - public const int FileShareDelete = 0x04; - - /// - /// A file with this bit on as returned by getAttributes() or set - /// with setAttributes() will be read-only - /// - public const int AttrReadonly = 0x01; - - /// - /// A file with this bit on as returned by getAttributes() or set - /// with setAttributes() will be hidden - /// - public const int AttrHidden = 0x02; - - /// - /// A file with this bit on as returned by getAttributes() or set - /// with setAttributes() will be a system file - /// - public const int AttrSystem = 0x04; - - /// - /// A file with this bit on as returned by getAttributes() is - /// a volume - /// - public const int AttrVolume = 0x08; - - /// - /// A file with this bit on as returned by getAttributes() is - /// a directory - /// - public const int AttrDirectory = 0x10; - - /// - /// A file with this bit on as returned by getAttributes() or set - /// with setAttributes() is an archived file - /// - public const int AttrArchive = 0x20; - - internal const int AttrCompressed = 0x800; - - internal const int AttrNormal = 0x080; - - internal const int AttrTemporary = 0x100; - - internal const int AttrGetMask = 0x7FFF; - - internal const int AttrSetMask = 0x30A7; - - internal const int DefaultAttrExpirationPeriod = 5000; - - internal static readonly int HashDot = ".".GetHashCode(); - - internal static readonly int HashDotDot = "..".GetHashCode(); - - //internal static LogStream log = LogStream.GetInstance(); - public LogStream Log - { - get { return LogStream.GetInstance(); } - } - - internal static long AttrExpirationPeriod; - - internal static bool IgnoreCopyToException; - - static SmbFile() - { - // Open Function Encoding - // create if the file does not exist - // fail if the file exists - // truncate if the file exists - // share access - // file attribute encoding - // extended file attribute encoding(others same as above) - /*try - { - Sharpen.Runtime.GetType("jcifs.Config"); - } - catch (TypeLoadException cnfe) - { - Sharpen.Runtime.PrintStackTrace(cnfe); - }*/ - - AttrExpirationPeriod = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod - ); - IgnoreCopyToException = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException" - , true); - Dfs = new Dfs(); - } - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a regular file or directory. - /// - public const int TypeFilesystem = 0x01; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a workgroup. - /// - public const int TypeWorkgroup = 0x02; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a server. - /// - public const int TypeServer = 0x04; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a share. - /// - public const int TypeShare = 0x08; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a named pipe. - /// - public const int TypeNamedPipe = 0x10; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a printer. - /// - public const int TypePrinter = 0x20; - - /// - /// Returned by - /// GetType() - /// if the resource this SmbFile - /// represents is a communications device. - /// - public const int TypeComm = 0x40; - - private string _canon; - - private string _share; - - private long _createTime; - - private long _lastModified; - - private int _attributes; - - private long _attrExpiration; - - private long _size; - - private long _sizeExpiration; - - private bool _isExists; - - private int _shareAccess = FileShareRead | FileShareWrite | FileShareDelete; - - private bool _enableDfs = Config.GetBoolean("jcifs.smb.client.enabledfs", false); - - private SmbComBlankResponse _blankResp; - - private DfsReferral _dfsReferral; - - protected internal static Dfs Dfs; - - internal NtlmPasswordAuthentication Auth; - - internal SmbTree Tree; - - internal string Unc; - - internal int Fid; - - internal int Type; - - internal bool Opened; - - internal int TreeNum; - - public bool EnableDfs - { - get { return _enableDfs; } - set { _enableDfs = value; } - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such as - /// a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such as - /// a file or directory. See the description and examples of smb URLs above. - /// - /// A URL string - /// - /// If the parent and child parameters - /// do not follow the prescribed syntax - /// - public SmbFile(string url) - : this(new Uri(url)) - { - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. The second parameter is a relative path from - /// the parent SmbFile. See the description above for examples - /// of using the second name parameter. - /// - /// A base SmbFile - /// A path string relative to the parent paremeter - /// - /// If the parent and child parameters - /// do not follow the prescribed syntax - /// - /// If the server or workgroup of the context file cannot be determined - /// - public SmbFile(SmbFile context, string name) - : this(context.IsWorkgroup0 - () ? new Uri("smb://" + name) : new Uri(context.Url.AbsoluteUri + name), - context.Auth) - { - - this._enableDfs = context.EnableDfs; - - if (!context.IsWorkgroup0()) - { - Addresses = context.Addresses; - - if (context._share != null) - { - Tree = context.Tree; - _dfsReferral = context._dfsReferral; - } - } - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. The second parameter is a relative path from - /// the parent. See the description above for examples of - /// using the second chile parameter. - /// - /// A URL string - /// A path string relative to the context paremeter - /// - /// If the context and name parameters - /// do not follow the prescribed syntax - /// - /*public SmbFile(string context, string name) - : this(new Uri(new Uri(null, context), name)) - { - }*/ - - public SmbFile(string context, string name) - : this(new Uri(context + name)) - { - - } - - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// A URL string - /// The credentials the client should use for authentication - /// If the url parameter does not follow the prescribed syntax - /// - public SmbFile(string url, NtlmPasswordAuthentication auth) - : this(new Uri(url, UriKind.RelativeOrAbsolute), - auth) - { - - } - - /// Constructs an SmbFile representing a file on an SMB network. - /// - /// Constructs an SmbFile representing a file on an SMB network. The - /// shareAccess parameter controls what permissions other - /// clients have when trying to access the same file while this instance - /// is still open. This value is either FILE_NO_SHARE or any - /// combination of FILE_SHARE_READ, FILE_SHARE_WRITE, - /// and FILE_SHARE_DELETE logically OR'd together. - /// - /// A URL string - /// The credentials the client should use for authentication - /// Specifies what access other clients have while this file is open. - /// - /// If the url parameter does not follow the prescribed syntax - /// - public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess) - : this - (new Uri(url), auth) - { - // Initially null; set by getUncPath; dir must end with '/' - // Can be null - // For getDfsPath() and getServerWithDfs() - // Cannot be null - // Initially null - // Initially null; set by getUncPath; never ends with '/' - // Initially 0; set by open() - if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != - 0) - { - throw new RuntimeException("Illegal shareAccess parameter"); - } - this._shareAccess = shareAccess; - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. The second parameter is a relative path from - /// the context. See the description above for examples of - /// using the second name parameter. - /// - /// A URL string - /// A path string relative to the context paremeter - /// The credentials the client should use for authentication - /// - /// If the context and name parameters - /// do not follow the prescribed syntax - /// - public SmbFile(string context, string name, NtlmPasswordAuthentication auth) - : this - (new Uri(context + name) - , auth) - { - - } - - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. The second parameter is a relative path from - /// the context. See the description above for examples of - /// using the second name parameter. The shareAccess - /// parameter controls what permissions other clients have when trying - /// to access the same file while this instance is still open. This - /// value is either FILE_NO_SHARE or any combination - /// of FILE_SHARE_READ, FILE_SHARE_WRITE, and - /// FILE_SHARE_DELETE logically OR'd together. - /// - /// A URL string - /// A path string relative to the context paremeter - /// The credentials the client should use for authentication - /// Specifies what access other clients have while this file is open. - /// - /// - /// If the context and name parameters - /// do not follow the prescribed syntax - /// - public SmbFile(string context, string name, NtlmPasswordAuthentication auth, int - shareAccess) - : this(new Uri(context + name), auth) - { - if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != - 0) - { - throw new RuntimeException("Illegal shareAccess parameter"); - } - this._shareAccess = shareAccess; - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory. The second parameter is a relative path from - /// the context. See the description above for examples of - /// using the second name parameter. The shareAccess - /// parameter controls what permissions other clients have when trying - /// to access the same file while this instance is still open. This - /// value is either FILE_NO_SHARE or any combination - /// of FILE_SHARE_READ, FILE_SHARE_WRITE, and - /// FILE_SHARE_DELETE logically OR'd together. - /// - /// A base SmbFile - /// A path string relative to the context file path - /// Specifies what access other clients have while this file is open. - /// - /// - /// If the context and name parameters - /// do not follow the prescribed syntax - /// - /// - public SmbFile(SmbFile context, string name, int shareAccess) - : this(context.IsWorkgroup0() ? new Uri("smb://" + name) : new Uri( - context.Url.AbsoluteUri + name), context.Auth) - { - if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != - 0) - { - throw new RuntimeException("Illegal shareAccess parameter"); - } - - if (!context.IsWorkgroup0()) - { - this.Addresses = context.Addresses; - - if (context._share != null || context.Tree != null) - { - Tree = context.Tree; - _dfsReferral = context._dfsReferral; - } - } - - this._shareAccess = shareAccess; - this._enableDfs = context.EnableDfs; - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory from a URL object. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory from a URL object. - /// - /// The URL of the target resource - protected SmbFile(Uri url) - : this(url, new NtlmPasswordAuthentication(url.GetUserInfo - ())) - { - } - - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory from a URL object and an - /// NtlmPasswordAuthentication object. - /// - /// - /// Constructs an SmbFile representing a resource on an SMB network such - /// as a file or directory from a URL object and an - /// NtlmPasswordAuthentication object. - /// - /// The URL of the target resource - /// The credentials the client should use for authentication - public SmbFile(Uri url, NtlmPasswordAuthentication auth) - { - this.Auth = auth ?? new NtlmPasswordAuthentication(url.GetUserInfo()); - Url = url; - GetUncPath0(); - } - - /// - /// - /*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes - , long createTime, long lastModified, long size) - : this(context.IsWorkgroup0() ? - new Uri(null, "smb://" + name + "/") : new Uri(context.url, - name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/ - internal SmbFile(SmbFile context, string name, int type, int attributes - , long createTime, long lastModified, long size) - : this(context.IsWorkgroup0() ? - new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri + - name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty))) - { - Auth = context.Auth; - if (context._share != null) - { - Tree = context.Tree; - _dfsReferral = context._dfsReferral; - } - int last = name.Length - 1; - if (name[last] == '/') - { - name = Runtime.Substring(name, 0, last); - } - if (context._share == null) - { - Unc = "\\"; - } - else - { - if (context.Unc.Equals("\\")) - { - Unc = '\\' + name; - } - else - { - Unc = context.Unc + '\\' + name; - } - } - - if (!context.IsWorkgroup0()) - { - Addresses = context.Addresses; - } - - this._enableDfs = context.EnableDfs; - - this.Type = type; - this._attributes = attributes; - this._createTime = createTime; - this._lastModified = lastModified; - this._size = size; - _isExists = true; - _attrExpiration = _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - } - - private SmbComBlankResponse Blank_resp() - { - if (_blankResp == null) - { - _blankResp = new SmbComBlankResponse(); - } - return _blankResp; - } - - /// - internal virtual void ResolveDfs(ServerMessageBlock request) - { - if (!_enableDfs) - { - Connect0(); - return; - } - - if (request is SmbComClose) - { - return; - } - Connect0(); - DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc - , Auth); - if (dr != null) - { - string service = null; - if (request != null) - { - switch (request.Command) - { - case ServerMessageBlock.SmbComTransaction: - case ServerMessageBlock.SmbComTransaction2: - { - switch (((SmbComTransaction)request).SubCommand & 0xFF) - { - case SmbComTransaction.Trans2GetDfsReferral: - { - break; - } - - default: - { - service = "A:"; - break; - } - } - break; - } - - default: - { - service = "A:"; - break; - } - } - } - DfsReferral start = dr; - SmbException se = null; - do - { - try - { - if (Log.Level >= 2) - { - Log.WriteLine("DFS redirect: " + dr); - } - UniAddress addr = UniAddress.GetByName(dr.Server); - SmbTransport trans = SmbTransport.GetSmbTransport(addr, Url.Port); - trans.Connect(); - Tree = trans.GetSmbSession(Auth).GetSmbTree(dr.Share, service); - if (dr != start && dr.Key != null) - { - dr.Map.Put(dr.Key, dr); - } - se = null; - break; - } - catch (IOException ioe) - { - if (ioe is SmbException) - { - se = (SmbException)ioe; - } - else - { - se = new SmbException(dr.Server, ioe); - } - } - dr = dr.Next; - } - while (dr != start); - if (se != null) - { - throw se; - } - if (Log.Level >= 3) - { - Log.WriteLine(dr); - } - _dfsReferral = dr; - if (dr.PathConsumed < 0) - { - dr.PathConsumed = 0; - } - else - { - if (dr.PathConsumed > Unc.Length) - { - dr.PathConsumed = Unc.Length; - } - } - string dunc = Runtime.Substring(Unc, dr.PathConsumed); - if (dunc.Equals(string.Empty)) - { - dunc = "\\"; - } - if (!dr.Path.Equals(string.Empty)) - { - dunc = "\\" + dr.Path + dunc; - } - Unc = dunc; - if (request != null && request.Path != null && request.Path.EndsWith("\\") && dunc - .EndsWith("\\") == false) - { - dunc += "\\"; - } - if (request != null) - { - request.Path = dunc; - request.Flags2 |= SmbConstants.Flags2ResolvePathsInDfs; - } - } - else - { - if (Tree.InDomainDfs && !(request is NtTransQuerySecurityDesc) && !(request is SmbComClose - ) && !(request is SmbComFindClose2)) - { - throw new SmbException(NtStatus.NtStatusNotFound, false); - } - if (request != null) - { - request.Flags2 &= ~SmbConstants.Flags2ResolvePathsInDfs; - } - } - } - - /// - internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response - ) - { - for (; ; ) - { - ResolveDfs(request); - try - { - Tree.Send(request, response); - break; - } - catch (DfsReferral dre) - { - if (dre.ResolveHashes) - { - throw; - } - request.Reset(); - } - } - } - - internal static string QueryLookup(string query, string param) - { - char[] instr = query.ToCharArray(); - int i; - int ch; - int st; - int eq; - st = eq = 0; - for (i = 0; i < instr.Length; i++) - { - ch = instr[i]; - if (ch == '&') - { - if (eq > st) - { - string p = new string(instr, st, eq - st); - if (Runtime.EqualsIgnoreCase(p, param)) - { - eq++; - return new string(instr, eq, i - eq); - } - } - st = i + 1; - } - else - { - if (ch == '=') - { - eq = i; - } - } - } - if (eq > st) - { - string p = new string(instr, st, eq - st); - if (Runtime.EqualsIgnoreCase(p, param)) - { - eq++; - return new string(instr, eq, instr.Length - eq); - } - } - return null; - } - - internal UniAddress[] Addresses; - - internal int AddressIndex; - - /// - internal virtual UniAddress GetAddress() - { - if (AddressIndex == 0) - { - return GetFirstAddress(); - } - return Addresses[AddressIndex - 1]; - } - - /// - internal virtual UniAddress GetFirstAddress() - { - AddressIndex = 0; - string host = Url.GetHost(); - string path = Url.AbsolutePath; - string query = Url.GetQuery(); - - if (Addresses != null && Addresses.Length > 0) - { - return GetNextAddress(); - } - - if (query != null) - { - string server = QueryLookup(query, "server"); - if (!string.IsNullOrEmpty(server)) - { - Addresses = new UniAddress[1]; - Addresses[0] = UniAddress.GetByName(server); - return GetNextAddress(); - } - string address = QueryLookup(query, "address"); - if (!string.IsNullOrEmpty(address)) - { - byte[] ip = Extensions.GetAddressByName(address).GetAddressBytes(); - Addresses = new UniAddress[1]; - //addresses[0] = new UniAddress(IPAddress.Parse(host, ip)); - Addresses[0] = new UniAddress(IPAddress.Parse(host)); - return GetNextAddress(); - } - } - if (host.Length == 0) - { - try - { - NbtAddress addr = NbtAddress.GetByName(NbtAddress.MasterBrowserName, 0x01, null); - Addresses = new UniAddress[1]; - Addresses[0] = UniAddress.GetByName(addr.GetHostAddress()); - } - catch (UnknownHostException uhe) - { - NtlmPasswordAuthentication.InitDefaults(); - if (NtlmPasswordAuthentication.DefaultDomain.Equals("?")) - { - throw; - } - Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, true - ); - } - } - else - { - if (path.Length == 0 || path.Equals("/")) - { - Addresses = UniAddress.GetAllByName(host, true); - } - else - { - Addresses = UniAddress.GetAllByName(host, false); - } - } - return GetNextAddress(); - } - - internal virtual UniAddress GetNextAddress() - { - UniAddress addr = null; - if (AddressIndex < Addresses.Length) - { - addr = Addresses[AddressIndex++]; - } - return addr; - } - - internal virtual bool HasNextAddress() - { - return AddressIndex < Addresses.Length; - } - - /// - internal virtual void Connect0() - { - try - { - Connect(); - } - catch (UnknownHostException uhe) - { - throw new SmbException("Failed to connect to server", uhe); - } - catch (SmbException se) - { - throw; - } - catch (IOException ioe) - { - throw new SmbException("Failed to connect to server", ioe); - } - } - - /// - internal virtual void DoConnect() - { - SmbTransport trans; - UniAddress addr; - addr = GetAddress(); - - if (Tree != null && Tree.Session.transport.Address.Equals(addr)) - { - trans = Tree.Session.transport; - } - else - { - trans = SmbTransport.GetSmbTransport(addr, Url.Port); - Tree = trans.GetSmbSession(Auth).GetSmbTree(_share, null); - } - - - string hostName = GetServerWithDfs(); - if (_enableDfs) - { - Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null; - } - if (Tree.InDomainDfs) - { - Tree.ConnectionState = 2; - } - try - { - if (Log.Level >= 3) - { - Log.WriteLine("doConnect: " + addr); - } - Tree.TreeConnect(null, null); - } - catch (SmbAuthException sae) - { - NtlmPasswordAuthentication a; - SmbSession ssn; - if (_share == null) - { - // IPC$ - try "anonymous" credentials - ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Null); - Tree = ssn.GetSmbTree(null, null); - Tree.TreeConnect(null, null); - } - else - { - if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae) - ) != null) - { - Auth = a; - ssn = trans.GetSmbSession(Auth); - Tree = ssn.GetSmbTree(_share, null); - Tree.InDomainDfs = Dfs.Resolve(hostName, Tree.Share, null, Auth) != null; - if (Tree.InDomainDfs) - { - Tree.ConnectionState = 2; - } - Tree.TreeConnect(null, null); - } - else - { - if (Log.Level >= 1 && HasNextAddress()) - { - Runtime.PrintStackTrace(sae, Log); - } - throw; - } - } - } - } - - /// It is not necessary to call this method directly. - /// - /// It is not necessary to call this method directly. This is the - /// URLConnection implementation of connect(). - /// - /// - public void Connect() - { - SmbTransport trans; - SmbSession ssn; - UniAddress addr; - if (IsConnected()) - { - return; - } - GetUncPath0(); - GetFirstAddress(); - for (; ; ) - { - try - { - DoConnect(); - return; - } - catch (SmbAuthException sae) - { - throw; - } - catch (SmbException se) - { - // Prevents account lockout on servers with multiple IPs - if (GetNextAddress() == null) - { - throw; - } - else - { - RemoveCurrentAddress(); - } - - if (Log.Level >= 3) - { - Runtime.PrintStackTrace(se, Log); - } - } - } - } - - internal virtual bool IsConnected() - { - return Tree != null && Tree.ConnectionState == 2; - } - - /// - internal virtual int Open0(int flags, int access, int attrs, int options) - { - int f; - Connect0(); - if (Log.Level >= 3) - { - Log.WriteLine("open0: " + Unc); - } - if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs)) - { - SmbComNtCreateAndXResponse response = new SmbComNtCreateAndXResponse(); - SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc, flags, access, _shareAccess - , attrs, options, null); - if (this is SmbNamedPipe) - { - request.Flags0 |= 0x16; - request.DesiredAccess |= 0x20000; - response.IsExtended = true; - } - Send(request, response); - f = response.Fid; - _attributes = response.ExtFileAttributes & AttrGetMask; - _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - _isExists = true; - } - else - { - SmbComOpenAndXResponse response = new SmbComOpenAndXResponse(); - Send(new SmbComOpenAndX(Unc, access, flags, null), response); - f = response.Fid; - } - return f; - } - - /// - internal virtual void Open(int flags, int access, int attrs, int options) - { - if (IsOpen()) - { - return; - } - Fid = Open0(flags, access, attrs, options); - Opened = true; - TreeNum = Tree.TreeNum; - } - - internal virtual bool IsOpen() - { - bool ans = Opened && IsConnected() && TreeNum == Tree.TreeNum; - return ans; - } - - /// - internal virtual void Close(int f, long lastWriteTime) - { - if (Log.Level >= 3) - { - Log.WriteLine("close: " + f); - } - Send(new SmbComClose(f, lastWriteTime), Blank_resp()); - } - - /// - internal virtual void Close(long lastWriteTime) - { - if (IsOpen() == false) - { - return; - } - Close(Fid, lastWriteTime); - Opened = false; - } - - /// - internal virtual void Close() - { - Close(0L); - } - - /// - /// Returns the NtlmPasswordAuthentication object used as - /// credentials with this file or pipe. - /// - /// - /// Returns the NtlmPasswordAuthentication object used as - /// credentials with this file or pipe. This can be used to retrieve the - /// username for example: - /// - /// String username = f.getPrincipal().getName(); - /// - /// The Principal object returned will never be null - /// however the username can be null indication anonymous - /// credentials were used (e.g. some IPC$ services). - /// - public virtual Principal GetPrincipal() - { - return Auth; - } - - /// Returns the last component of the target URL. - /// - /// Returns the last component of the target URL. This will - /// effectively be the name of the file or directory represented by this - /// SmbFile or in the case of URLs that only specify a server - /// or workgroup, the server or workgroup will be returned. The name of - /// the root URL smb:// is also smb://. If this - /// SmbFile refers to a workgroup, server, share, or directory, - /// the name will include a trailing slash '/' so that composing new - /// SmbFiles will maintain the trailing slash requirement. - /// - /// - /// The last component of the URL associated with this SMB - /// resource or smb:// if the resource is smb:// - /// itself. - /// - public virtual string GetName() - { - GetUncPath0(); - if (_canon.Length > 1) - { - int i = _canon.Length - 2; - while (_canon[i] != '/') - { - i--; - } - return Runtime.Substring(_canon, i + 1); - } - if (_share != null) - { - return _share + '/'; - } - if (Url.GetHost().Length > 0) - { - return Url.GetHost() + '/'; - } - return "smb://"; - } - - /// - /// Everything but the last component of the URL representing this SMB - /// resource is effectivly it's parent. - /// - /// - /// Everything but the last component of the URL representing this SMB - /// resource is effectivly it's parent. The root URL smb:// - /// does not have a parent. In this case smb:// is returned. - /// - /// - /// The parent directory of this SMB resource or - /// smb:// if the resource refers to the root of the URL - /// hierarchy which incedentally is also smb://. - /// - public virtual string GetParent() - { - string str = Url.Authority; - if (str.Length > 0) - { - StringBuilder sb = new StringBuilder("smb://"); - sb.Append(str); - GetUncPath0(); - if (_canon.Length > 1) - { - sb.Append(_canon); - } - else - { - sb.Append('/'); - } - str = sb.ToString(); - int i = str.Length - 2; - while (str[i] != '/') - { - i--; - } - return Runtime.Substring(str, 0, i + 1); - } - return "smb://"; - } - - /// Returns the full uncanonicalized URL of this SMB resource. - /// - /// Returns the full uncanonicalized URL of this SMB resource. An - /// SmbFile constructed with the result of this method will - /// result in an SmbFile that is equal to the original. - /// - /// The uncanonicalized full URL of this SMB resource. - public virtual string GetPath() - { - return Url.ToString(); - } - - internal virtual string GetUncPath0() - { - if (Unc == null) - { - char[] instr = Url.LocalPath.ToCharArray(); - char[] outstr = new char[instr.Length]; - int length = instr.Length; - int i; - int o; - int state; - - state = 0; - o = 0; - for (i = 0; i < length; i++) - { - switch (state) - { - case 0: - { - if (instr[i] != '/') - { - return null; - } - outstr[o++] = instr[i]; - state = 1; - break; - } - - case 1: - { - if (instr[i] == '/') - { - break; - } - if (instr[i] == '.' && ((i + 1) >= length || instr[i + 1] == '/')) - { - i++; - break; - } - if ((i + 1) < length && instr[i] == '.' && instr[i + 1] == '.' && ((i + 2) >= length - || instr[i + 2] == '/')) - { - i += 2; - if (o == 1) - { - break; - } - do - { - o--; - } - while (o > 1 && outstr[o - 1] != '/'); - break; - } - state = 2; - goto case 2; - } - - case 2: - { - if (instr[i] == '/') - { - state = 1; - } - outstr[o++] = instr[i]; - break; - } - } - } - _canon = new string(outstr, 0, o); - if (o > 1) - { - o--; - i = _canon.IndexOf('/', 1); - if (i < 0) - { - _share = Runtime.Substring(_canon, 1); - Unc = "\\"; - } - else - { - if (i == o) - { - _share = Runtime.Substring(_canon, 1, i); - Unc = "\\"; - } - else - { - _share = Runtime.Substring(_canon, 1, i); - Unc = Runtime.Substring(_canon, i, outstr[o] == '/' ? o : o + 1); - Unc = Unc.Replace('/', '\\'); - } - } - } - else - { - _share = null; - Unc = "\\"; - } - } - return Unc; - } - - /// Retuns the Windows UNC style path with backslashs intead of forward slashes. - /// - /// Retuns the Windows UNC style path with backslashs intead of forward slashes. - /// - /// The UNC path. - public virtual string GetUncPath() - { - GetUncPath0(); - if (_share == null) - { - return "\\\\" + Url.GetHost(); - } - return "\\\\" + Url.GetHost() + _canon.Replace('/', '\\'); - } - - /// - /// Returns the full URL of this SMB resource with '.' and '..' components - /// factored out. - /// - /// - /// Returns the full URL of this SMB resource with '.' and '..' components - /// factored out. An SmbFile constructed with the result of - /// this method will result in an SmbFile that is equal to - /// the original. - /// - /// The canonicalized URL of this SMB resource. - public virtual string GetCanonicalPath() - { - string str = Url.Authority; - GetUncPath0(); - if (str.Length > 0) - { - return "smb://" + Url.Authority + _canon; - } - return "smb://"; - } - - /// Retrieves the share associated with this SMB resource. - /// - /// Retrieves the share associated with this SMB resource. In - /// the case of smb://, smb://workgroup/, - /// and smb://server/ URLs which do not specify a share, - /// null will be returned. - /// - /// The share component or null if there is no share - public virtual string GetShare() - { - return _share; - } - - internal virtual string GetServerWithDfs() - { - if (_dfsReferral != null) - { - return _dfsReferral.Server; - } - return GetServer(); - } - - /// Retrieve the hostname of the server for this SMB resource. - /// - /// Retrieve the hostname of the server for this SMB resource. If this - /// SmbFile references a workgroup, the name of the workgroup - /// is returned. If this SmbFile refers to the root of this - /// SMB network hierarchy, null is returned. - /// - /// - /// The server or workgroup name or null if this - /// SmbFile refers to the root smb:// resource. - /// - public virtual string GetServer() - { - string str = Url.GetHost(); - if (str.Length == 0) - { - return null; - } - return str; - } - - /// Returns type of of object this SmbFile represents. - /// Returns type of of object this SmbFile represents. - /// - /// TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE, - /// TYPE_PRINTER, TYPE_NAMED_PIPE, or TYPE_COMM. - /// - /// - public new virtual int GetType() - { - if (Type == 0) - { - if (GetUncPath0().Length > 1) - { - Type = TypeFilesystem; - } - else - { - if (_share != null) - { - // treeConnect good enough to test service type - Connect0(); - if (_share.Equals("IPC$")) - { - Type = TypeNamedPipe; - } - else - { - if (Tree.Service.Equals("LPT1:")) - { - Type = TypePrinter; - } - else - { - if (Tree.Service.Equals("COMM")) - { - Type = TypeComm; - } - else - { - Type = TypeShare; - } - } - } - } - else - { - if (string.IsNullOrEmpty(Url.Authority)) - { - Type = TypeWorkgroup; - } - else - { - UniAddress addr; - try - { - addr = GetAddress(); - } - catch (UnknownHostException uhe) - { - throw new SmbException(Url.ToString(), uhe); - } - if (addr.GetAddress() is NbtAddress) - { - int code = ((NbtAddress)addr.GetAddress()).GetNameType(); - if (code == 0x1d || code == 0x1b) - { - Type = TypeWorkgroup; - return Type; - } - } - Type = TypeServer; - } - } - } - } - return Type; - } - - /// - internal virtual bool IsWorkgroup0() - { - if (Type == TypeWorkgroup || Url.GetHost().Length == 0) - { - Type = TypeWorkgroup; - return true; - } - GetUncPath0(); - if (_share == null) - { - UniAddress addr = GetAddress(); - if (addr.GetAddress() is NbtAddress) - { - int code = ((NbtAddress)addr.GetAddress()).GetNameType(); - if (code == 0x1d || code == 0x1b) - { - Type = TypeWorkgroup; - return true; - } - } - Type = TypeServer; - } - return false; - } - - /// - internal virtual IInfo QueryPath(string path, int infoLevel) - { - Connect0(); - if (Log.Level >= 3) - { - Log.WriteLine("queryPath: " + path); - } - if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs)) - { - Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse - (infoLevel); - Send(new Trans2QueryPathInformation(path, infoLevel), response); - return response.Info; - } - else - { - SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(Tree - .Session.transport.Server.ServerTimeZone * 1000 * 60L); - Send(new SmbComQueryInformation(path), response); - return response; - } - } - - /// Tests to see if the SMB resource exists. - /// - /// Tests to see if the SMB resource exists. If the resource refers - /// only to a server, this method determines if the server exists on the - /// network and is advertising SMB services. If this resource refers to - /// a workgroup, this method determines if the workgroup name is valid on - /// the local SMB network. If this SmbFile refers to the root - /// smb:// resource true is always returned. If - /// this SmbFile is a traditional file or directory, it will - /// be queried for on the specified server as expected. - /// - /// - /// true if the resource exists or is alive or - /// false otherwise - /// - /// - public virtual bool Exists() - { - if (_attrExpiration > Runtime.CurrentTimeMillis()) - { - return _isExists; - } - _attributes = AttrReadonly | AttrDirectory; - _createTime = 0L; - _lastModified = 0L; - _isExists = false; - try - { - if (Url.GetHost().Length == 0) - { - } - else - { - if (_share == null) - { - if (GetType() == TypeWorkgroup) - { - UniAddress.GetByName(Url.GetHost(), true); - } - else - { - UniAddress.GetByName(Url.GetHost()).GetHostName(); - } - } - else - { - if (GetUncPath0().Length == 1 || Runtime.EqualsIgnoreCase(_share, "IPC$")) - { - Connect0(); - } - else - { - // treeConnect is good enough - IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO - ); - _attributes = info.GetAttributes(); - _createTime = info.GetCreateTime(); - _lastModified = info.GetLastWriteTime(); - } - } - } - _isExists = true; - } - catch (UnknownHostException) - { - } - catch (SmbException se) - { - switch (se.GetNtStatus()) - { - case NtStatus.NtStatusNoSuchFile: - case NtStatus.NtStatusObjectNameInvalid: - case NtStatus.NtStatusObjectNameNotFound: - case NtStatus.NtStatusObjectPathNotFound: - { - break; - } - - default: - { - throw; - } - } - } - _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - return _isExists; - } - - /// - /// Tests to see if the file this SmbFile represents can be - /// read. - /// - /// - /// Tests to see if the file this SmbFile represents can be - /// read. Because any file, directory, or other resource can be read if it - /// exists, this method simply calls the exists method. - /// - /// true if the file is read-only - /// - public virtual bool CanRead() - { - if (GetType() == TypeNamedPipe) - { - // try opening the pipe for reading? - return true; - } - return Exists(); - } - - // try opening and catch sharing violation? - /// - /// Tests to see if the file this SmbFile represents - /// exists and is not marked read-only. - /// - /// - /// Tests to see if the file this SmbFile represents - /// exists and is not marked read-only. By default, resources are - /// considered to be read-only and therefore for smb://, - /// smb://workgroup/, and smb://server/ resources - /// will be read-only. - /// - /// - /// true if the resource exists is not marked - /// read-only - /// - /// - public virtual bool CanWrite() - { - if (GetType() == TypeNamedPipe) - { - // try opening the pipe for writing? - return true; - } - return Exists() && (_attributes & AttrReadonly) == 0; - } - - /// Tests to see if the file this SmbFile represents is a directory. - /// - /// Tests to see if the file this SmbFile represents is a directory. - /// - /// true if this SmbFile is a directory - /// - public virtual bool IsDirectory() - { - if (GetUncPath0().Length == 1) - { - return true; - } - if (!Exists()) - { - return false; - } - return (_attributes & AttrDirectory) == AttrDirectory; - } - - /// Tests to see if the file this SmbFile represents is not a directory. - /// - /// Tests to see if the file this SmbFile represents is not a directory. - /// - /// true if this SmbFile is not a directory - /// - public virtual bool IsFile() - { - if (GetUncPath0().Length == 1) - { - return false; - } - Exists(); - return (_attributes & AttrDirectory) == 0; - } - - /// - /// Tests to see if the file this SmbFile represents is marked as - /// hidden. - /// - /// - /// Tests to see if the file this SmbFile represents is marked as - /// hidden. This method will also return true for shares with names that - /// end with '$' such as IPC$ or C$. - /// - /// true if the SmbFile is marked as being hidden - /// - public virtual bool IsHidden() - { - if (_share == null) - { - return false; - } - if (GetUncPath0().Length == 1) - { - if (_share.EndsWith("$")) - { - return true; - } - return false; - } - Exists(); - return (_attributes & AttrHidden) == AttrHidden; - } - - /// - /// If the path of this SmbFile falls within a DFS volume, - /// this method will return the referral path to which it maps. - /// - /// - /// If the path of this SmbFile falls within a DFS volume, - /// this method will return the referral path to which it maps. Otherwise - /// null is returned. - /// - /// - public virtual string GetDfsPath() - { - ResolveDfs(null); - if (_dfsReferral == null) - { - return null; - } - string path = "smb:/" + _dfsReferral.Server + "/" + _dfsReferral.Share + Unc; - path = path.Replace('\\', '/'); - if (IsDirectory()) - { - path += '/'; - } - return path; - } - - /// Retrieve the time this SmbFile was created. - /// - /// Retrieve the time this SmbFile was created. The value - /// returned is suitable for constructing a - /// System.DateTime - /// object - /// (i.e. seconds since Epoch 1970). Times should be the same as those - /// reported using the properties dialog of the Windows Explorer program. - /// For Win95/98/Me this is actually the last write time. It is currently - /// not possible to retrieve the create time from files on these systems. - /// - /// - /// The number of milliseconds since the 00:00:00 GMT, January 1, - /// 1970 as a long value - /// - /// - public virtual long CreateTime() - { - if (GetUncPath0().Length > 1) - { - Exists(); - return _createTime; - } - return 0L; - } - - /// - /// Retrieve the last time the file represented by this - /// SmbFile was modified. - /// - /// - /// Retrieve the last time the file represented by this - /// SmbFile was modified. The value returned is suitable for - /// constructing a - /// System.DateTime - /// object (i.e. seconds since Epoch - /// 1970). Times should be the same as those reported using the properties - /// dialog of the Windows Explorer program. - /// - /// - /// The number of milliseconds since the 00:00:00 GMT, January 1, - /// 1970 as a long value - /// - /// - public virtual long LastModified() - { - if (GetUncPath0().Length > 1) - { - Exists(); - return _lastModified; - } - return 0L; - } - - /// List the contents of this SMB resource. - /// - /// List the contents of this SMB resource. The list returned by this - /// method will be; - ///
    - ///
  • files and directories contained within this resource if the - /// resource is a normal disk file directory, - ///
  • all available NetBIOS workgroups or domains if this resource is - /// the top level URL smb://, - ///
  • all servers registered as members of a NetBIOS workgroup if this - /// resource refers to a workgroup in a smb://workgroup/ URL, - ///
  • all browseable shares of a server including printers, IPC - /// services, or disk volumes if this resource is a server URL in the form - /// smb://server/, - ///
  • or null if the resource cannot be resolved. - ///
- ///
- /// - /// A String[] array of files and directories, - /// workgroups, servers, or shares depending on the context of the - /// resource URL - /// - /// - public virtual string[] List() - { - return List("*", AttrDirectory | AttrHidden | AttrSystem, null, null); - } - - /// List the contents of this SMB resource. - /// - /// List the contents of this SMB resource. The list returned will be - /// identical to the list returned by the parameterless list() - /// method minus filenames filtered by the specified filter. - /// - /// a filename filter to exclude filenames from the results - /// # @return An array of filenames - /// - public virtual string[] List(ISmbFilenameFilter filter) - { - return List("*", AttrDirectory | AttrHidden | AttrSystem, filter, null); - } - - /// - /// List the contents of this SMB resource as an array of - /// SmbFile objects. - /// - /// - /// List the contents of this SMB resource as an array of - /// SmbFile objects. This method is much more efficient than - /// the regular list method when querying attributes of each - /// file in the result set. - ///

- /// The list of SmbFiles returned by this method will be; - ///

    - ///
  • files and directories contained within this resource if the - /// resource is a normal disk file directory, - ///
  • all available NetBIOS workgroups or domains if this resource is - /// the top level URL smb://, - ///
  • all servers registered as members of a NetBIOS workgroup if this - /// resource refers to a workgroup in a smb://workgroup/ URL, - ///
  • all browseable shares of a server including printers, IPC - /// services, or disk volumes if this resource is a server URL in the form - /// smb://server/, - ///
  • or null if the resource cannot be resolved. - ///
- ///
- /// - /// An array of SmbFile objects representing file - /// and directories, workgroups, servers, or shares depending on the context - /// of the resource URL - /// - /// - public virtual SmbFile[] ListFiles() - { - return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null); - } - - /// - /// The CIFS protocol provides for DOS "wildcards" to be used as - /// a performance enhancement. - /// - /// - /// The CIFS protocol provides for DOS "wildcards" to be used as - /// a performance enhancement. The client does not have to filter - /// the names and the server does not have to return all directory - /// entries. - ///

- /// The wildcard expression may consist of two special meta - /// characters in addition to the normal filename characters. The '*' - /// character matches any number of characters in part of a name. If - /// the expression begins with one or more '?'s then exactly that - /// many characters will be matched whereas if it ends with '?'s - /// it will match that many characters or less. - ///

- /// Wildcard expressions will not filter workgroup names or server names. - ///

-        /// winnt> ls c?o
-        /// clock.avi                  -rw--      82944 Mon Oct 14 1996 1:38 AM
-        /// Cookies                    drw--          0 Fri Nov 13 1998 9:42 PM
-        /// 2 items in 5ms
-        /// 
- ///
- /// a wildcard expression - /// SmbException - /// - /// An array of SmbFile objects representing file - /// and directories, workgroups, servers, or shares depending on the context - /// of the resource URL - /// - /// - public virtual SmbFile[] ListFiles(string wildcard) - { - return ListFiles(wildcard, AttrDirectory | AttrHidden | AttrSystem, null, null - ); - } - - /// List the contents of this SMB resource. - /// - /// List the contents of this SMB resource. The list returned will be - /// identical to the list returned by the parameterless listFiles() - /// method minus files filtered by the specified filename filter. - /// - /// a filter to exclude files from the results - /// An array of SmbFile objects - /// SmbException - /// - public virtual SmbFile[] ListFiles(ISmbFilenameFilter filter) - { - return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, filter, null); - } - - /// List the contents of this SMB resource. - /// - /// List the contents of this SMB resource. The list returned will be - /// identical to the list returned by the parameterless listFiles() - /// method minus filenames filtered by the specified filter. - /// - /// a file filter to exclude files from the results - /// An array of SmbFile objects - /// - public virtual SmbFile[] ListFiles(ISmbFileFilter filter) - { - return ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, filter); - } - - /// - internal virtual string[] List(string wildcard, int searchAttributes, ISmbFilenameFilter - fnf, ISmbFileFilter ff) - { - List list = new List(); - DoEnum(list, false, wildcard, searchAttributes, fnf, ff); - - return Collections.ToArray(list); //Collections.ToArray(list); - } - - /// - internal virtual SmbFile[] ListFiles(string wildcard, int searchAttributes - , ISmbFilenameFilter fnf, ISmbFileFilter ff) - { - List list = new List(); - DoEnum(list, true, wildcard, searchAttributes, fnf, ff); - - return Collections.ToArray(list); //Collections.ToArray(list); - } - - /// - internal virtual void DoEnum(List list, bool files, string wildcard, int searchAttributes - , ISmbFilenameFilter fnf, ISmbFileFilter ff) - { - if (ff != null && ff is DosFileFilter) - { - DosFileFilter dff = (DosFileFilter)ff; - if (dff.Wildcard != null) - { - wildcard = dff.Wildcard; - } - searchAttributes = dff.Attributes; - } - try - { - int hostlen = Url.GetHost() != null ? Url.GetHost().Length : 0; - if (hostlen == 0 || GetType() == TypeWorkgroup) - { - DoNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff); - } - else - { - if (_share == null) - { - DoShareEnum(list, files, wildcard, searchAttributes, fnf, ff); - } - else - { - DoFindFirstNext(list, files, wildcard, searchAttributes, fnf, ff); - } - } - } - catch (UnknownHostException uhe) - { - throw new SmbException(Url.ToString(), uhe); - } - catch (UriFormatException mue) - { - throw new SmbException(Url.ToString(), mue); - } - } - - private void RemoveCurrentAddress() - { - if (AddressIndex >= 1) - { - UniAddress[] aux = new UniAddress[Addresses.Length - 1]; - - Array.Copy(Addresses, 1, aux, 0, Addresses.Length - 1); - - Addresses = aux; - AddressIndex--; - } - } - - /// - /// - /// - internal virtual void DoShareEnum(List list, bool files, string wildcard, int - searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) - { - string p = Url.AbsolutePath; - IOException last = null; - IFileEntry[] entries; - UniAddress addr; - IFileEntry e; - Hashtable map; - if (p.LastIndexOf('/') != (p.Length - 1)) - { - throw new SmbException(Url + " directory must end with '/'"); - } - if (GetType() != TypeServer) - { - throw new SmbException("The requested list operations is invalid: " + Url); - } - map = new Hashtable(); - if (_enableDfs && Dfs.IsTrustedDomain(GetServer(), Auth)) - { - try - { - entries = DoDfsRootEnum(); - for (int ei = 0; ei < entries.Length; ei++) - { - e = entries[ei]; - if (map.ContainsKey(e) == false) - { - map.Put(e, e); - } - } - } - catch (IOException ioe) - { - if (Log.Level >= 4) - { - Runtime.PrintStackTrace(ioe, Log); - } - } - } - addr = GetFirstAddress(); - while (addr != null) - { - try - { - last = null; - - DoConnect(); - try - { - entries = DoMsrpcShareEnum(); - } - catch (IOException ioe) - { - if (Log.Level >= 3) - { - Runtime.PrintStackTrace(ioe, Log); - } - entries = DoNetShareEnum(); - } - for (int ei = 0; ei < entries.Length; ei++) - { - e = entries[ei]; - if (map.ContainsKey(e) == false) - { - map.Put(e, e); - } - } - break; - } - catch (IOException ioe) - { - if (Log.Level >= 3) - { - Runtime.PrintStackTrace(ioe, Log); - } - last = ioe; - - if (!(ioe is SmbAuthException)) - { - RemoveCurrentAddress(); - - addr = GetNextAddress(); - } - else - { - break; - } - } - - } - if (last != null && map.Count == 0) - { - if (last is SmbException == false) - { - throw new SmbException(Url.ToString(), last); - } - throw (SmbException)last; - } - //Iterator iter = map.Keys.Iterator(); - //while (iter.HasNext()) - foreach (var item in map.Keys) - { - e = (IFileEntry)item; - string name = e.GetName(); - if (fnf != null && fnf.Accept(this, name) == false) - { - continue; - } - if (name.Length > 0) - { - // if !files we don't need to create SmbFiles here - SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly - | AttrDirectory, 0L, 0L, 0L); - if (ff != null && ff.Accept(f) == false) - { - continue; - } - if (files) - { - list.Add(f); - } - else - { - list.Add(name); - } - } - } - } - - /// - internal virtual IFileEntry[] DoDfsRootEnum() - { - MsrpcDfsRootEnum rpc; - DcerpcHandle handle = null; - IFileEntry[] entries; - handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\netdfs]" - , Auth); - try - { - rpc = new MsrpcDfsRootEnum(GetServer()); - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, true); - } - return rpc.GetEntries(); - } - finally - { - try - { - handle.Close(); - } - catch (IOException ioe) - { - if (Log.Level >= 4) - { - Runtime.PrintStackTrace(ioe, Log); - } - } - } - } - - /// - internal virtual IFileEntry[] DoMsrpcShareEnum() - { - MsrpcShareEnum rpc; - DcerpcHandle handle; - rpc = new MsrpcShareEnum(Url.GetHost()); - handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\srvsvc]" - , Auth); - try - { - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, true); - } - return rpc.GetEntries(); - } - finally - { - try - { - handle.Close(); - } - catch (IOException ioe) - { - if (Log.Level >= 4) - { - Runtime.PrintStackTrace(ioe, Log); - } - } - } - } - - /// - internal virtual IFileEntry[] DoNetShareEnum() - { - SmbComTransaction req = new NetShareEnum(); - SmbComTransactionResponse resp = new NetShareEnumResponse(); - Send(req, resp); - if (resp.Status != WinError.ErrorSuccess) - { - throw new SmbException(resp.Status, true); - } - return resp.Results; - } - - /// - /// - /// - internal virtual void DoNetServerEnum(List list, bool files, string wildcard - , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) - { - int listType = Url.GetHost().Length == 0 ? 0 : GetType(); - SmbComTransaction req; - SmbComTransactionResponse resp; - if (listType == 0) - { - Connect0(); - req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName, NetServerEnum2 - .SvTypeDomainEnum); - resp = new NetServerEnum2Response(); - } - else - { - if (listType == TypeWorkgroup) - { - req = new NetServerEnum2(Url.GetHost(), NetServerEnum2.SvTypeAll); - resp = new NetServerEnum2Response(); - } - else - { - throw new SmbException("The requested list operations is invalid: " + Url); - } - } - bool more; - do - { - int n; - Send(req, resp); - if (resp.Status != WinError.ErrorSuccess && resp.Status != WinError.ErrorMoreData) - { - throw new SmbException(resp.Status, true); - } - more = resp.Status == WinError.ErrorMoreData; - n = more ? resp.NumEntries - 1 : resp.NumEntries; - for (int i = 0; i < n; i++) - { - IFileEntry e = resp.Results[i]; - string name = e.GetName(); - if (fnf != null && fnf.Accept(this, name) == false) - { - continue; - } - if (name.Length > 0) - { - // if !files we don't need to create SmbFiles here - SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly - | AttrDirectory, 0L, 0L, 0L); - if (ff != null && ff.Accept(f) == false) - { - continue; - } - if (files) - { - list.Add(f); - } - else - { - list.Add(name); - } - } - } - if (GetType() != TypeWorkgroup) - { - break; - } - req.SubCommand = unchecked(SmbComTransaction.NetServerEnum3); - req.Reset(0, ((NetServerEnum2Response)resp).LastName); - resp.Reset(); - } - while (more); - } - - /// - /// - /// - internal virtual void DoFindFirstNext(List list, bool files, string wildcard - , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) - { - SmbComTransaction req; - Trans2FindFirst2Response resp; - int sid; - string path = GetUncPath0(); - string p = Url.AbsolutePath; - if (p.LastIndexOf('/') != (p.Length - 1)) - { - throw new SmbException(Url + " directory must end with '/'"); - } - req = new Trans2FindFirst2(path, wildcard, searchAttributes); - resp = new Trans2FindFirst2Response(); - if (Log.Level >= 3) - { - Log.WriteLine("doFindFirstNext: " + req.Path); - } - Send(req, resp); - sid = resp.Sid; - req = new Trans2FindNext2(sid, resp.ResumeKey, resp.LastName); - resp.SubCommand = SmbComTransaction.Trans2FindNext2; - for (; ; ) - { - for (int i = 0; i < resp.NumEntries; i++) - { - IFileEntry e = resp.Results[i]; - string name = e.GetName(); - if (name.Length < 3) - { - int h = name.GetHashCode(); - if (h == HashDot || h == HashDotDot) - { - if (name.Equals(".") || name.Equals("..")) - { - continue; - } - } - } - if (fnf != null && fnf.Accept(this, name) == false) - { - continue; - } - if (name.Length > 0) - { - SmbFile f = new SmbFile(this, name, TypeFilesystem, e.GetAttributes - (), e.CreateTime(), e.LastModified(), e.Length()); - if (ff != null && ff.Accept(f) == false) - { - continue; - } - if (files) - { - list.Add(f); - } - else - { - list.Add(name); - } - } - } - if (resp.IsEndOfSearch || resp.NumEntries == 0) - { - break; - } - req.Reset(resp.ResumeKey, resp.LastName); - resp.Reset(); - Send(req, resp); - } - try - { - Send(new SmbComFindClose2(sid), Blank_resp()); - } - catch (SmbException se) - { - if (Log.Level >= 4) - { - Runtime.PrintStackTrace(se, Log); - } - } - } - - /// - /// Changes the name of the file this SmbFile represents to the name - /// designated by the SmbFile argument. - /// - /// - /// Changes the name of the file this SmbFile represents to the name - /// designated by the SmbFile argument. - ///

- /// Remember: SmbFiles are immutible and therefore - /// the path associated with this SmbFile object will not - /// change). To access the renamed file it is necessary to construct a - /// new SmbFile. - /// - /// An SmbFile that represents the new pathname - /// If the dest argument is null - /// - /// - public virtual void RenameTo(SmbFile dest) - { - if (GetUncPath0().Length == 1 || dest.GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - ResolveDfs(null); - dest.ResolveDfs(null); - if (!Tree.Equals(dest.Tree)) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - if (Log.Level >= 3) - { - Log.WriteLine("renameTo: " + Unc + " -> " + dest.Unc); - } - _attrExpiration = _sizeExpiration = 0; - dest._attrExpiration = 0; - Send(new SmbComRename(Unc, dest.Unc), Blank_resp()); - } - - internal class WriterThread : Thread - { - internal byte[] B; - - internal int N; - - internal long Off; - - internal bool Ready; - - internal SmbFile Dest; - - internal SmbException E; - - internal bool UseNtSmbs; - - internal SmbComWriteAndX Reqx; - - internal SmbComWrite Req; - - internal ServerMessageBlock Resp; - - /// - public WriterThread(SmbFile enclosing) - : base("JCIFS-WriterThread") - { - this._enclosing = enclosing; - UseNtSmbs = this._enclosing.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs); - if (UseNtSmbs) - { - Reqx = new SmbComWriteAndX(); - Resp = new SmbComWriteAndXResponse(); - } - else - { - Req = new SmbComWrite(); - Resp = new SmbComWriteResponse(); - } - Ready = false; - } - - internal virtual void Write(byte[] b, int n, SmbFile dest, long off) - { - lock (this) - { - this.B = b; - this.N = n; - this.Dest = dest; - this.Off = off; - Ready = false; - Runtime.Notify(this); - } - } - - public override void Run() - { - lock (this) - { - try - { - for (; ; ) - { - Runtime.Notify(this); - Ready = true; - while (Ready) - { - Runtime.Wait(this); - } - if (N == -1) - { - return; - } - if (UseNtSmbs) - { - Reqx.SetParam(Dest.Fid, Off, N, B, 0, N); - Dest.Send(Reqx, Resp); - } - else - { - Req.SetParam(Dest.Fid, Off, N, B, 0, N); - Dest.Send(Req, Resp); - } - } - } - catch (SmbException e) - { - this.E = e; - } - catch (Exception x) - { - E = new SmbException("WriterThread", x); - } - Runtime.Notify(this); - } - } - - private readonly SmbFile _enclosing; - } - - /// - internal virtual void CopyTo0(SmbFile dest, byte[][] b, int bsize, WriterThread - w, SmbComReadAndX req, SmbComReadAndXResponse resp) - { - int i; - if (_attrExpiration < Runtime.CurrentTimeMillis()) - { - _attributes = AttrReadonly | AttrDirectory; - _createTime = 0L; - _lastModified = 0L; - _isExists = false; - IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO - ); - _attributes = info.GetAttributes(); - _createTime = info.GetCreateTime(); - _lastModified = info.GetLastWriteTime(); - _isExists = true; - _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - } - if (IsDirectory()) - { - SmbFile[] files; - SmbFile ndest; - string path = dest.GetUncPath0(); - if (path.Length > 1) - { - try - { - dest.Mkdir(); - dest.SetPathInformation(_attributes, _createTime, _lastModified); - } - catch (SmbException se) - { - if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied && se.GetNtStatus() != NtStatus - .NtStatusObjectNameCollision) - { - throw; - } - } - } - files = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null); - try - { - for (i = 0; i < files.Length; i++) - { - ndest = new SmbFile(dest, files[i].GetName(), files[i].Type, files[i]._attributes, - files[i]._createTime, files[i]._lastModified, files[i]._size); - files[i].CopyTo0(ndest, b, bsize, w, req, resp); - } - } - catch (UnknownHostException uhe) - { - throw new SmbException(Url.ToString(), uhe); - } - catch (UriFormatException mue) - { - throw new SmbException(Url.ToString(), mue); - } - } - else - { - long off; - try - { - Open(ORdonly, 0, AttrNormal, 0); - try - { - dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData | - SmbConstants.FileWriteAttributes, _attributes, 0); - } - catch (SmbAuthException sae) - { - if ((dest._attributes & AttrReadonly) != 0) - { - dest.SetPathInformation(dest._attributes & ~AttrReadonly, 0L, 0L); - dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData | - SmbConstants.FileWriteAttributes, _attributes, 0); - } - else - { - throw; - } - } - i = 0; - off = 0L; - for (; ; ) - { - req.SetParam(Fid, off, bsize); - resp.SetParam(b[i], 0); - Send(req, resp); - lock (w) - { - if (w.E != null) - { - throw w.E; - } - while (!w.Ready) - { - try - { - Runtime.Wait(w); - } - catch (Exception ie) - { - throw new SmbException(dest.Url.ToString(), ie); - } - } - if (w.E != null) - { - throw w.E; - } - if (resp.DataLength <= 0) - { - break; - } - w.Write(b[i], resp.DataLength, dest, off); - } - i = i == 1 ? 0 : 1; - off += resp.DataLength; - } - dest.Send(new Trans2SetFileInformation(dest.Fid, _attributes, _createTime, _lastModified - ), new Trans2SetFileInformationResponse()); - dest.Close(0L); - } - catch (SmbException se) - { - if (IgnoreCopyToException == false) - { - throw new SmbException("Failed to copy file from [" + ToString() + "] to [" - + dest + "]", se); - } - if (Log.Level > 1) - { - Runtime.PrintStackTrace(se, Log); - } - } - finally - { - Close(); - } - } - } - - ///

- /// This method will copy the file or directory represented by this - /// SmbFile and it's sub-contents to the location specified by the - /// dest parameter. - /// - /// - /// This method will copy the file or directory represented by this - /// SmbFile and it's sub-contents to the location specified by the - /// dest parameter. This file and the destination file do not - /// need to be on the same host. This operation does not copy extended - /// file attibutes such as ACLs but it does copy regular attributes as - /// well as create and last write times. This method is almost twice as - /// efficient as manually copying as it employs an additional write - /// thread to read and write data concurrently. - ///

- /// It is not possible (nor meaningful) to copy entire workgroups or - /// servers. - /// - /// the destination file or directory - /// SmbException - /// - public virtual void CopyTo(SmbFile dest) - { - SmbComReadAndX req; - SmbComReadAndXResponse resp; - WriterThread w; - int bsize; - byte[][] b; - if (_share == null || dest._share == null) - { - throw new SmbException("Invalid operation for workgroups or servers"); - } - req = new SmbComReadAndX(); - resp = new SmbComReadAndXResponse(); - Connect0(); - dest.Connect0(); - ResolveDfs(null); - try - { - if (GetAddress().Equals(dest.GetAddress()) && _canon.RegionMatches(true, 0, dest._canon - , 0, Math.Min(_canon.Length, dest._canon.Length))) - { - throw new SmbException("Source and destination paths overlap."); - } - } - catch (UnknownHostException) - { - } - w = new WriterThread(this); - w.SetDaemon(true); - w.Start(); - SmbTransport t1 = Tree.Session.transport; - SmbTransport t2 = dest.Tree.Session.transport; - if (t1.SndBufSize < t2.SndBufSize) - { - t2.SndBufSize = t1.SndBufSize; - } - else - { - t1.SndBufSize = t2.SndBufSize; - } - bsize = Math.Min(t1.RcvBufSize - 70, t1.SndBufSize - 70); - b = new[] { new byte[bsize], new byte[bsize] }; - try - { - CopyTo0(dest, b, bsize, w, req, resp); - } - finally - { - w.Write(null, -1, null, 0); - } - } - - ///

- /// This method will delete the file or directory specified by this - /// SmbFile. - /// - /// - /// This method will delete the file or directory specified by this - /// SmbFile. If the target is a directory, the contents of - /// the directory will be deleted as well. If a file within the directory or - /// it's sub-directories is marked read-only, the read-only status will - /// be removed and the file will be deleted. - /// - /// SmbException - /// - public virtual void Delete() - { - Exists(); - GetUncPath0(); - Delete(Unc); - } - - /// - internal virtual void Delete(string fileName) - { - if (GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - if (Runtime.CurrentTimeMillis() > _attrExpiration) - { - _attributes = AttrReadonly | AttrDirectory; - _createTime = 0L; - _lastModified = 0L; - _isExists = false; - IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO - ); - _attributes = info.GetAttributes(); - _createTime = info.GetCreateTime(); - _lastModified = info.GetLastWriteTime(); - _attrExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - _isExists = true; - } - if ((_attributes & AttrReadonly) != 0) - { - SetReadWrite(); - } - if (Log.Level >= 3) - { - Log.WriteLine("delete: " + fileName); - } - if ((_attributes & AttrDirectory) != 0) - { - try - { - SmbFile[] l = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null - ); - for (int i = 0; i < l.Length; i++) - { - l[i].Delete(); - } - } - catch (SmbException se) - { - if (se.GetNtStatus() != NtStatus.NtStatusNoSuchFile) - { - throw; - } - } - Send(new SmbComDeleteDirectory(fileName), Blank_resp()); - } - else - { - Send(new SmbComDelete(fileName), Blank_resp()); - } - _attrExpiration = _sizeExpiration = 0; - } - - /// Returns the length of this SmbFile in bytes. - /// - /// Returns the length of this SmbFile in bytes. If this object - /// is a TYPE_SHARE the total capacity of the disk shared in - /// bytes is returned. If this object is a directory or a type other than - /// TYPE_SHARE, 0L is returned. - /// - /// - /// The length of the file in bytes or 0 if this - /// SmbFile is not a file. - /// - /// SmbException - /// - public virtual long Length() - { - if (_sizeExpiration > Runtime.CurrentTimeMillis()) - { - return _size; - } - if (GetType() == TypeShare) - { - Trans2QueryFsInformationResponse response; - int level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION; - response = new Trans2QueryFsInformationResponse(level); - Send(new Trans2QueryFsInformation(level), response); - _size = response.Info.GetCapacity(); - } - else - { - if (GetUncPath0().Length > 1 && Type != TypeNamedPipe) - { - IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO - ); - _size = info.GetSize(); - } - else - { - _size = 0L; - } - } - _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - return _size; - } - - /// - /// This method returns the free disk space in bytes of the drive this share - /// represents or the drive on which the directory or file resides. - /// - /// - /// This method returns the free disk space in bytes of the drive this share - /// represents or the drive on which the directory or file resides. Objects - /// other than TYPE_SHARE or TYPE_FILESYSTEM will result - /// in 0L being returned. - /// - /// - /// the free disk space in bytes of the drive on which this file or - /// directory resides - /// - /// - public virtual long GetDiskFreeSpace() - { - if (GetType() == TypeShare || Type == TypeFilesystem) - { - int level = Trans2QueryFsInformationResponse.SmbFsFullSizeInformation; - try - { - return QueryFsInformation(level); - } - catch (SmbException ex) - { - switch (ex.GetNtStatus()) - { - case NtStatus.NtStatusInvalidInfoClass: - case NtStatus.NtStatusUnsuccessful: - { - // NetApp Filer - // SMB_FS_FULL_SIZE_INFORMATION not supported by the server. - level = Trans2QueryFsInformationResponse.SMB_INFO_ALLOCATION; - return QueryFsInformation(level); - } - } - throw; - } - } - return 0L; - } - - /// - private long QueryFsInformation(int level) - { - Trans2QueryFsInformationResponse response; - response = new Trans2QueryFsInformationResponse(level); - Send(new Trans2QueryFsInformation(level), response); - if (Type == TypeShare) - { - _size = response.Info.GetCapacity(); - _sizeExpiration = Runtime.CurrentTimeMillis() + AttrExpirationPeriod; - } - return response.Info.GetFree(); - } - - /// - /// Creates a directory with the path specified by this - /// SmbFile. - /// - /// - /// Creates a directory with the path specified by this - /// SmbFile. For this method to be successful, the target - /// must not already exist. This method will fail when - /// used with smb://, smb://workgroup/, - /// smb://server/, or smb://server/share/ URLs - /// because workgroups, servers, and shares cannot be dynamically created - /// (although in the future it may be possible to create shares). - /// - /// SmbException - /// - public virtual void Mkdir() - { - string path = GetUncPath0(); - if (path.Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - if (Log.Level >= 3) - { - Log.WriteLine("mkdir: " + path); - } - Send(new SmbComCreateDirectory(path), Blank_resp()); - _attrExpiration = _sizeExpiration = 0; - } - - /// - /// Creates a directory with the path specified by this SmbFile - /// and any parent directories that do not exist. - /// - /// - /// Creates a directory with the path specified by this SmbFile - /// and any parent directories that do not exist. This method will fail - /// when used with smb://, smb://workgroup/, - /// smb://server/, or smb://server/share/ URLs - /// because workgroups, servers, and shares cannot be dynamically created - /// (although in the future it may be possible to create shares). - /// - /// SmbException - /// - public virtual void Mkdirs() - { - SmbFile parent; - try - { - parent = new SmbFile(GetParent(), Auth); - } - catch (IOException) - { - return; - } - if (parent.Exists() == false) - { - parent.Mkdirs(); - } - Mkdir(); - } - - /// Create a new file but fail if it already exists. - /// - /// Create a new file but fail if it already exists. The check for - /// existance of the file and it's creation are an atomic operation with - /// respect to other filesystem activities. - /// - /// - public virtual void CreateNewFile() - { - if (GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - Close(Open0(ORdwr | OCreat | OExcl, 0, AttrNormal, 0), 0L); - } - - /// - internal virtual void SetPathInformation(int attrs, long ctime, long mtime) - { - int f; - int dir; - Exists(); - dir = _attributes & AttrDirectory; - f = Open0(ORdonly, SmbConstants.FileWriteAttributes, dir, dir != 0 ? 0x0001 - : 0x0040); - Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), new Trans2SetFileInformationResponse - ()); - Close(f, 0L); - _attrExpiration = 0; - } - - /// Set the create time of the file. - /// - /// Set the create time of the file. The time is specified as milliseconds - /// from Jan 1, 1970 which is the same as that which is returned by the - /// createTime() method. - ///

- /// This method does not apply to workgroups, servers, or shares. - /// - /// the create time as milliseconds since Jan 1, 1970 - /// - public virtual void SetCreateTime(long time) - { - if (GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - SetPathInformation(0, time, 0L); - } - - ///

Set the last modified time of the file. - /// - /// Set the last modified time of the file. The time is specified as milliseconds - /// from Jan 1, 1970 which is the same as that which is returned by the - /// lastModified(), getLastModified(), and getDate() methods. - ///

- /// This method does not apply to workgroups, servers, or shares. - /// - /// the last modified time as milliseconds since Jan 1, 1970 - /// - public virtual void SetLastModified(long time) - { - if (GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - SetPathInformation(0, 0L, time); - } - - ///

Return the attributes of this file. - /// - /// Return the attributes of this file. Attributes are represented as a - /// bitset that must be masked with ATTR_* constants to determine - /// if they are set or unset. The value returned is suitable for use with - /// the setAttributes() method. - /// - /// the ATTR_* attributes associated with this file - /// SmbException - /// - public virtual int GetAttributes() - { - if (GetUncPath0().Length == 1) - { - return 0; - } - Exists(); - return _attributes & AttrGetMask; - } - - /// Set the attributes of this file. - /// - /// Set the attributes of this file. Attributes are composed into a - /// bitset by bitwise ORing the ATTR_* constants. Setting the - /// value returned by getAttributes will result in both files - /// having the same attributes. - /// - /// SmbException - /// - public virtual void SetAttributes(int attrs) - { - if (GetUncPath0().Length == 1) - { - throw new SmbException("Invalid operation for workgroups, servers, or shares"); - } - SetPathInformation(attrs & AttrSetMask, 0L, 0L); - } - - /// Make this file read-only. - /// - /// Make this file read-only. This is shorthand for setAttributes( - /// getAttributes() | ATTR_READ_ONLY ). - /// - /// SmbException - /// - public virtual void SetReadOnly() - { - SetAttributes(GetAttributes() | AttrReadonly); - } - - /// Turn off the read-only attribute of this file. - /// - /// Turn off the read-only attribute of this file. This is shorthand for - /// setAttributes( getAttributes() & ~ATTR_READONLY ). - /// - /// SmbException - /// - public virtual void SetReadWrite() - { - SetAttributes(GetAttributes() & ~AttrReadonly); - } - - /// - /// Computes a hashCode for this file based on the URL string and IP - /// address if the server. - /// - /// - /// Computes a hashCode for this file based on the URL string and IP - /// address if the server. The hashing function uses the hashcode of the - /// server address, the canonical representation of the URL, and does not - /// compare authentication information. In essance, two - /// SmbFile objects that refer to - /// the same file should generate the same hashcode provided it is possible - /// to make such a determination. - /// - /// A hashcode for this abstract file - /// SmbException - public override int GetHashCode() - { - int hash; - try - { - hash = GetAddress().GetHashCode(); - } - catch (UnknownHostException) - { - hash = GetServer().ToUpper().GetHashCode(); - } - GetUncPath0(); - return hash + _canon.ToUpper().GetHashCode(); - } - - protected internal virtual bool PathNamesPossiblyEqual(string path1, string path2 - ) - { - int p1; - int p2; - int l1; - int l2; - // if unsure return this method returns true - p1 = path1.LastIndexOf('/'); - p2 = path2.LastIndexOf('/'); - l1 = path1.Length - p1; - l2 = path2.Length - p2; - // anything with dots voids comparison - if (l1 > 1 && path1[p1 + 1] == '.') - { - return true; - } - if (l2 > 1 && path2[p2 + 1] == '.') - { - return true; - } - return l1 == l2 && path1.RegionMatches(true, p1, path2, p2, l1); - } - - /// Tests to see if two SmbFile objects are equal. - /// - /// Tests to see if two SmbFile objects are equal. Two - /// SmbFile objects are equal when they reference the same SMB - /// resource. More specifically, two SmbFile objects are - /// equals if their server IP addresses are equal and the canonicalized - /// representation of their URLs, minus authentication parameters, are - /// case insensitivly and lexographically equal. - ///

- /// For example, assuming the server angus resolves to the - /// 192.168.1.15 IP address, the below URLs would result in - /// SmbFiles that are equal. - ///

-        /// smb://192.168.1.15/share/DIR/foo.txt
-        /// smb://angus/share/data/../dir/foo.txt
-        /// 
- ///
- /// Another SmbFile object to compare for equality - /// - /// true if the two objects refer to the same SMB resource - /// and false otherwise - /// - /// SmbException - public override bool Equals(object obj) - { - if (obj is SmbFile) - { - SmbFile f = (SmbFile)obj; - bool ret; - if (this == f) - { - return true; - } - if (PathNamesPossiblyEqual(Url.AbsolutePath, f.Url.AbsolutePath)) - { - GetUncPath0(); - f.GetUncPath0(); - if (Runtime.EqualsIgnoreCase(_canon, f._canon)) - { - try - { - ret = GetAddress().Equals(f.GetAddress()); - } - catch (UnknownHostException) - { - ret = Runtime.EqualsIgnoreCase(GetServer(), f.GetServer()); - } - return ret; - } - } - } - return false; - } - - /// Returns the string representation of this SmbFile object. - /// - /// Returns the string representation of this SmbFile object. This will - /// be the same as the URL used to construct this SmbFile. - /// This method will return the same value - /// as getPath. - /// - /// The original URL representation of this SMB resource - /// SmbException - public override string ToString() - { - return Url.ToString(); - } - - /// This URLConnection method just returns the result of length(). - /// This URLConnection method just returns the result of length(). - /// the length of this file or 0 if it refers to a directory - public int GetContentLength() - { - try - { - return (int)(Length() & unchecked(0xFFFFFFFFL)); - } - catch (SmbException) - { - } - return 0; - } - - /// This URLConnection method just returns the result of lastModified. - /// - /// This URLConnection method just returns the result of lastModified. - /// - /// the last modified data as milliseconds since Jan 1, 1970 - public long GetDate() - { - try - { - return LastModified(); - } - catch (SmbException) - { - } - return 0L; - } - - /// This URLConnection method just returns the result of lastModified. - /// - /// This URLConnection method just returns the result of lastModified. - /// - /// the last modified data as milliseconds since Jan 1, 1970 - public long GetLastModified() - { - try - { - return LastModified(); - } - catch (SmbException) - { - } - return 0L; - } - - /// This URLConnection method just returns a new SmbFileInputStream created with this file. - /// - /// This URLConnection method just returns a new SmbFileInputStream created with this file. - /// - /// thrown by SmbFileInputStream constructor - /// - public InputStream GetInputStream() - { - return new SmbFileInputStream(this); - } - - /// This URLConnection method just returns a new SmbFileOutputStream created with this file. - /// - /// This URLConnection method just returns a new SmbFileOutputStream created with this file. - /// - /// thrown by SmbFileOutputStream constructor - /// - public OutputStream GetOutputStream() - { - return new SmbFileOutputStream(this); - } - - /// - private void ProcessAces(Ace[] aces, bool resolveSids) - { - string server = GetServerWithDfs(); - int ai; - if (resolveSids) - { - Sid[] sids = new Sid[aces.Length]; - string[] names = null; - for (ai = 0; ai < aces.Length; ai++) - { - sids[ai] = aces[ai].Sid; - } - for (int off = 0; off < sids.Length; off += 64) - { - int len = sids.Length - off; - if (len > 64) - { - len = 64; - } - Sid.ResolveSids(server, Auth, sids, off, len); - } - } - else - { - for (ai = 0; ai < aces.Length; ai++) - { - aces[ai].Sid.OriginServer = server; - aces[ai].Sid.OriginAuth = Auth; - } - } - } - - /// - /// Return an array of Access Control Entry (ACE) objects representing - /// the security descriptor associated with this file or directory. - /// - /// - /// Return an array of Access Control Entry (ACE) objects representing - /// the security descriptor associated with this file or directory. - /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. - /// - /// - /// Attempt to resolve the SIDs within each ACE form - /// their numeric representation to their corresponding account names. - /// - /// - public virtual Ace[] GetSecurity(bool resolveSids) - { - int f; - Ace[] aces; - f = Open0(ORdonly, SmbConstants.ReadControl, 0, IsDirectory() ? 1 : 0); - NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04); - NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse( - ); - try - { - Send(request, response); - } - finally - { - Close(f, 0L); - } - aces = response.SecurityDescriptor.Aces; - if (aces != null) - { - ProcessAces(aces, resolveSids); - } - return aces; - } - - /// - /// Return an array of Access Control Entry (ACE) objects representing - /// the share permissions on the share exporting this file or directory. - /// - /// - /// Return an array of Access Control Entry (ACE) objects representing - /// the share permissions on the share exporting this file or directory. - /// If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. - ///

- /// Note that this is different from calling getSecurity on a - /// share. There are actually two different ACLs for shares - the ACL on - /// the share and the ACL on the folder being shared. - /// Go to Computer Management - /// > System Tools > Shared Folders > Shares and - /// look at the Properties for a share. You will see two tabs - one - /// for "Share Permissions" and another for "Security". These correspond to - /// the ACLs returned by getShareSecurity and getSecurity - /// respectively. - /// - /// - /// Attempt to resolve the SIDs within each ACE form - /// their numeric representation to their corresponding account names. - /// - /// - public virtual Ace[] GetShareSecurity(bool resolveSids) - { - string p = Url.AbsolutePath; - MsrpcShareGetInfo rpc; - DcerpcHandle handle; - Ace[] aces; - ResolveDfs(null); - string server = GetServerWithDfs(); - rpc = new MsrpcShareGetInfo(server, Tree.Share); - handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", Auth); - try - { - handle.Sendrecv(rpc); - if (rpc.Retval != 0) - { - throw new SmbException(rpc.Retval, true); - } - aces = rpc.GetSecurity(); - if (aces != null) - { - ProcessAces(aces, resolveSids); - } - } - finally - { - try - { - handle.Close(); - } - catch (IOException ioe) - { - if (Log.Level >= 1) - { - Runtime.PrintStackTrace(ioe, Log); - } - } - } - return aces; - } - - ///

- /// Return an array of Access Control Entry (ACE) objects representing - /// the security descriptor associated with this file or directory. - /// - /// - /// Return an array of Access Control Entry (ACE) objects representing - /// the security descriptor associated with this file or directory. - ///

- /// Initially, the SIDs within each ACE will not be resolved however when - /// getType(), getDomainName(), getAccountName(), - /// or toString() is called, the names will attempt to be - /// resolved. If the names cannot be resolved (e.g. due to temporary - /// network failure), the said methods will return default values (usually - /// S-X-Y-Z strings of fragments of). - ///

- /// Alternatively getSecurity(true) may be used to resolve all - /// SIDs together and detect network failures. - /// - /// - public virtual Ace[] GetSecurity() - { - return GetSecurity(false); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs deleted file mode 100644 index 2ebcfa20f4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileExtensions.cs +++ /dev/null @@ -1,133 +0,0 @@ -// SmbFileExtensions.cs implementation by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using System; -using System.Threading.Tasks; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - public static class SmbFileExtensions - { - ///

- /// Get file's creation date converted to local timezone - /// - /// - /// - public static DateTime GetLocalCreateTime(this SmbFile smbFile) - { - return TimeZoneInfo.ConvertTime(Extensions.CreateDateFromUTC(smbFile.CreateTime()), - TimeZoneInfo.Local); - } - - /// - /// Get file's last modified date converted to local timezone - /// - /// - /// - public static DateTime GetLocalLastModified(this SmbFile smbFile) - { - return TimeZoneInfo.ConvertTime(Extensions.CreateDateFromUTC(smbFile.LastModified()), - TimeZoneInfo.Local); - } - - - /// - /// List files async - /// - /// - /// - public static Task ListFilesAsync(this SmbFile smbFile) - { - return Task.Run(() => smbFile.ListFiles()); - } - - /// - /// List files async - /// - /// - /// - /// - public static Task ListFilesAsync(this SmbFile smbFile, string wildcard) - { - return Task.Run(() => smbFile.ListFiles(wildcard)); - } - - /// - /// List files async - /// - /// - /// - public static Task ListAsync(this SmbFile smbFile) - { - return Task.Run(() => smbFile.List()); - } - - /// - /// MkDir async method - /// - /// - /// - public static Task MkDirAsync(this SmbFile smbFile) - { - return Task.Run(() => smbFile.Mkdir()); - } - - - /// - /// Delete file async - /// - /// - /// - public static Task DeleteAsync(this SmbFile smbFile) - { - return Task.Run(() => smbFile.Delete()); - } - - /// - /// Rename file async - /// - /// - /// - /// - public static Task RenameToAsync(this SmbFile smbFile, SmbFile destination) - { - return Task.Run(() => smbFile.RenameTo(destination)); - } - - /// - /// Get input stream async - /// - /// - /// - public static Task GetInputStreamAsync(this SmbFile smbFile) - { - return Task.Run(() => smbFile.GetInputStream()); - } - - - /// - /// Get output stream async - /// - /// - /// - /// - public static Task GetOutputStreamAsync(this SmbFile smbFile, bool append = false) - { - return Task.Run(() => new SmbFileOutputStream(smbFile, append) as OutputStream); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs deleted file mode 100644 index 196bfc1b6d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileFilter.cs +++ /dev/null @@ -1,24 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public interface ISmbFileFilter - { - /// - bool Accept(SmbFile file); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs deleted file mode 100644 index a9a0ea1129..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileInputStream.cs +++ /dev/null @@ -1,339 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util.Sharpen; -using SharpCifs.Util.Transport; - -namespace SharpCifs.Smb -{ - /// This InputStream can read bytes from a file on an SMB file server. - /// This InputStream can read bytes from a file on an SMB file server. Offsets are 64 bits. - /// - public class SmbFileInputStream : InputStream - { - private long _fp; - - private int _readSize; - - private int _openFlags; - - private int _access; - - private byte[] _tmp = new byte[1]; - - internal SmbFile File; - - /// - /// Creates an - /// System.IO.InputStream - /// for reading bytes from a file on - /// an SMB server addressed by the url parameter. See - /// SmbFile - /// for a detailed description and examples of the smb - /// URL syntax. - /// - /// An smb URL string representing the file to read from - /// - /// - /// - public SmbFileInputStream(string url) : this(new SmbFile(url)) - { - } - - /// - /// Creates an - /// System.IO.InputStream - /// for reading bytes from a file on - /// an SMB server represented by the - /// SmbFile - /// parameter. See - /// SmbFile - /// for a detailed description and examples of - /// the smb URL syntax. - /// - /// An SmbFile specifying the file to read from - /// - /// - /// - public SmbFileInputStream(SmbFile file) : this(file, SmbFile.ORdonly) - { - } - - /// - /// - /// - internal SmbFileInputStream(SmbFile file, int openFlags) - { - this.File = file; - this._openFlags = openFlags & 0xFFFF; - _access = ((int)(((uint)openFlags) >> 16)) & 0xFFFF; - if (file.Type != SmbFile.TypeNamedPipe) - { - file.Open(openFlags, _access, SmbFile.AttrNormal, 0); - this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc); - } - else - { - file.Connect0(); - } - _readSize = Math.Min(file.Tree.Session.transport.RcvBufSize - 70, file.Tree.Session - .transport.Server.MaxBufferSize - 70); - } - - protected internal virtual IOException SeToIoe(SmbException se) - { - IOException ioe = se; - Exception root = se.GetRootCause(); - if (root is TransportException) - { - ioe = (TransportException)root; - root = ((TransportException)ioe).GetRootCause(); - } - if (root is Exception) - { - ioe = new IOException(root.Message); - ioe.InitCause(root); - } - return ioe; - } - - /// Closes this input stream and releases any system resources associated with the stream. - /// - /// Closes this input stream and releases any system resources associated with the stream. - /// - /// if a network error occurs - public override void Close() - { - try - { - File.Close(); - _tmp = null; - } - catch (SmbException se) - { - throw SeToIoe(se); - } - } - - /// Reads a byte of data from this input stream. - /// Reads a byte of data from this input stream. - /// if a network error occurs - public override int Read() - { - // need oplocks to cache otherwise use BufferedInputStream - if (Read(_tmp, 0, 1) == -1) - { - return -1; - } - return _tmp[0] & unchecked(0xFF); - } - - /// Reads up to b.length bytes of data from this input stream into an array of bytes. - /// - /// Reads up to b.length bytes of data from this input stream into an array of bytes. - /// - /// if a network error occurs - public override int Read(byte[] b) - { - return Read(b, 0, b.Length); - } - - /// Reads up to len bytes of data from this input stream into an array of bytes. - /// - /// Reads up to len bytes of data from this input stream into an array of bytes. - /// - /// if a network error occurs - public override int Read(byte[] b, int off, int len) - { - return ReadDirect(b, off, len); - } - - /// - public virtual int ReadDirect(byte[] b, int off, int len) - { - if (len <= 0) - { - return 0; - } - - long start = _fp; - if (_tmp == null) - { - throw new IOException("Bad file descriptor"); - } - - // ensure file is open - File.Open(_openFlags, _access, SmbFile.AttrNormal, 0); - if (File.Log.Level >= 4) - { - File.Log.WriteLine("read: fid=" + File.Fid + ",off=" + off + ",len=" + len); - } - - SmbComReadAndXResponse response = new SmbComReadAndXResponse(b, off); - if (File.Type == SmbFile.TypeNamedPipe) - { - response.ResponseTimeout = 0; - } - - int r; - int n; - do - { - r = len > _readSize ? _readSize : len; - if (File.Log.Level >= 4) - { - File.Log.WriteLine("read: len=" + len + ",r=" + r + ",fp=" + _fp); - } - - try - { - SmbComReadAndX request = new SmbComReadAndX(File.Fid, _fp, r, null); - if (File.Type == SmbFile.TypeNamedPipe) - { - request.MinCount = request.MaxCount = request.Remaining = 1024; - } - //‚±‚±‚Å“Ç‚Ýž‚ñ‚Å‚¢‚é‚炵‚¢B - File.Send(request, response); - } - catch (SmbException se) - { - if (File.Type == SmbFile.TypeNamedPipe && se.GetNtStatus() == NtStatus.NtStatusPipeBroken) - { - return -1; - } - throw SeToIoe(se); - } - - if ((n = response.DataLength) <= 0) - { - return (int)((_fp - start) > 0L ? _fp - start : -1); - } - - _fp += n; - len -= n; - response.Off += n; - } - while (len > 0 && n == r); - - - return (int)(_fp - start); - } - - /// This stream class is unbuffered. - /// - /// This stream class is unbuffered. Therefore this method will always - /// return 0 for streams connected to regular files. However, a - /// stream created from a Named Pipe this method will query the server using a - /// "peek named pipe" operation and return the number of available bytes - /// on the server. - /// - /// - public override int Available() - { - SmbNamedPipe pipe; - TransPeekNamedPipe req; - TransPeekNamedPipeResponse resp; - if (File.Type != SmbFile.TypeNamedPipe) - { - return 0; - } - try - { - pipe = (SmbNamedPipe)File; - File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal - , 0); - req = new TransPeekNamedPipe(File.Unc, File.Fid); - resp = new TransPeekNamedPipeResponse(pipe); - pipe.Send(req, resp); - if (resp.status == TransPeekNamedPipeResponse.StatusDisconnected || resp.status - == TransPeekNamedPipeResponse.StatusServerEndClosed) - { - File.Opened = false; - return 0; - } - return resp.Available; - } - catch (SmbException se) - { - throw SeToIoe(se); - } - } - - /// Skip n bytes of data on this stream. - /// - /// Skip n bytes of data on this stream. This operation will not result - /// in any IO with the server. Unlink InputStream value less than - /// the one provided will not be returned if it exceeds the end of the file - /// (if this is a problem let us know). - /// - /// - public override long Skip(long n) - { - if (n > 0) - { - _fp += n; - return n; - } - return 0; - } - - - /// - /// Position in Stream - /// - /// - /// Add by dobes - /// mod interface to WrappedSystemStream readable, for random access. - /// - internal override long Position { - get { return this._fp; } - set - { - var tmpPos = value; - var length = File.Length(); - if (tmpPos < 0) - tmpPos = 0; - else if (length < tmpPos) - tmpPos = length; - this._fp = tmpPos; - } - } - - /// - /// - /// - /// - /// - /// Add by dobes - /// mod interface to WrappedSystemStream readable, for random access. - /// - internal override bool CanSeek() - { - return (File.Length() >= 0); - } - - /// - /// Get file length - /// - public override long Length - { - get { return File.Length(); } - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs deleted file mode 100644 index 58c704dd70..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFileOutputStream.cs +++ /dev/null @@ -1,335 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - /// This OutputStream can write bytes to a file on an SMB file server. - /// - /// This OutputStream can write bytes to a file on an SMB file server. - /// - public class SmbFileOutputStream : OutputStream - { - private SmbFile _file; - - private bool _append; - - private bool _useNtSmbs; - - private int _openFlags; - - private int _access; - - private int _writeSize; - - private long _fp; - - private byte[] _tmp = new byte[1]; - - private SmbComWriteAndX _reqx; - - private SmbComWriteAndXResponse _rspx; - - private SmbComWrite _req; - - private SmbComWriteResponse _rsp; - - /// - /// Creates an - /// System.IO.OutputStream - /// for writing to a file - /// on an SMB server addressed by the URL parameter. See - /// SmbFile - /// for a detailed description and examples of - /// the smb URL syntax. - /// - /// An smb URL string representing the file to write to - /// - /// - /// - public SmbFileOutputStream(string url) : this(url, false) - { - } - - /// - /// Creates an - /// System.IO.OutputStream - /// for writing bytes to a file on - /// an SMB server represented by the - /// SmbFile - /// parameter. See - /// SmbFile - /// for a detailed description and examples of - /// the smb URL syntax. - /// - /// An SmbFile specifying the file to write to - /// - /// - /// - public SmbFileOutputStream(SmbFile file) : this(file, false) - { - } - - /// - /// Creates an - /// System.IO.OutputStream - /// for writing bytes to a file on an - /// SMB server addressed by the URL parameter. See - /// SmbFile - /// for a detailed description and examples of the smb URL syntax. If the - /// second argument is true, then bytes will be written to the - /// end of the file rather than the beginning. - /// - /// An smb URL string representing the file to write to - /// Append to the end of file - /// - /// - /// - public SmbFileOutputStream(string url, bool append) : this(new SmbFile(url), append - ) - { - } - - /// - /// Creates an - /// System.IO.OutputStream - /// for writing bytes to a file - /// on an SMB server addressed by the SmbFile parameter. See - /// SmbFile - /// for a detailed description and examples of - /// the smb URL syntax. If the second argument is true, then - /// bytes will be written to the end of the file rather than the beginning. - /// - /// An SmbFile representing the file to write to - /// Append to the end of file - /// - /// - /// - public SmbFileOutputStream(SmbFile file, bool append) : this(file, append, append - ? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend : SmbFile.OCreat | SmbFile - .OWronly | SmbFile.OTrunc) - { - } - - /// - /// Creates an - /// System.IO.OutputStream - /// for writing bytes to a file - /// on an SMB server addressed by the SmbFile parameter. See - /// SmbFile - /// for a detailed description and examples of - /// the smb URL syntax. - ///

- /// The second parameter specifies how the file should be shared. If - /// SmbFile.FILE_NO_SHARE is specified the client will - /// have exclusive access to the file. An additional open command - /// from jCIFS or another application will fail with the "file is being - /// accessed by another process" error. The FILE_SHARE_READ, - /// FILE_SHARE_WRITE, and FILE_SHARE_DELETE may be - /// combined with the bitwise OR '|' to specify that other peocesses may read, - /// write, and/or delete the file while the jCIFS user has the file open. - ///

- /// An smb URL representing the file to write to - /// File sharing flag: SmbFile.FILE_NOSHARE or any combination of SmbFile.FILE_READ, SmbFile.FILE_WRITE, and SmbFile.FILE_DELETE - /// - /// - /// - /// - public SmbFileOutputStream(string url, int shareAccess) : this(new SmbFile(url, string.Empty - , null, shareAccess), false) - { - } - - /// - /// - /// - internal SmbFileOutputStream(SmbFile file, bool append, int openFlags) - { - this._file = file; - this._append = append; - this._openFlags = openFlags; - _access = ((int)(((uint)openFlags) >> 16)) & 0xFFFF; - if (append) - { - try - { - _fp = file.Length(); - } - catch (SmbAuthException sae) - { - throw; - } - catch (SmbException) - { - _fp = 0L; - } - } - if (file is SmbNamedPipe && file.Unc.StartsWith("\\pipe\\")) - { - file.Unc = Runtime.Substring(file.Unc, 5); - file.Send(new TransWaitNamedPipe("\\pipe" + file.Unc), new TransWaitNamedPipeResponse - ()); - } - file.Open(openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal, - 0); - this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc); - _writeSize = file.Tree.Session.transport.SndBufSize - 70; - _useNtSmbs = file.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs - ); - if (_useNtSmbs) - { - _reqx = new SmbComWriteAndX(); - _rspx = new SmbComWriteAndXResponse(); - } - else - { - _req = new SmbComWrite(); - _rsp = new SmbComWriteResponse(); - } - } - - /// - /// Closes this output stream and releases any system resources associated - /// with it. - /// - /// - /// Closes this output stream and releases any system resources associated - /// with it. - /// - /// if a network error occurs - public override void Close() - { - _file.Close(); - _tmp = null; - } - - /// Writes the specified byte to this file output stream. - /// Writes the specified byte to this file output stream. - /// if a network error occurs - public override void Write(int b) - { - _tmp[0] = unchecked((byte)b); - Write(_tmp, 0, 1); - } - - /// - /// Writes b.length bytes from the specified byte array to this - /// file output stream. - /// - /// - /// Writes b.length bytes from the specified byte array to this - /// file output stream. - /// - /// if a network error occurs - public override void Write(byte[] b) - { - Write(b, 0, b.Length); - } - - public virtual bool IsOpen() - { - return _file.IsOpen(); - } - - /// - internal virtual void EnsureOpen() - { - // ensure file is open - if (_file.IsOpen() == false) - { - _file.Open(_openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal, - 0); - if (_append) - { - _fp = _file.Length(); - } - } - } - - /// - /// Writes len bytes from the specified byte array starting at - /// offset off to this file output stream. - /// - /// - /// Writes len bytes from the specified byte array starting at - /// offset off to this file output stream. - /// - /// The array - /// if a network error occurs - public override void Write(byte[] b, int off, int len) - { - if (_file.IsOpen() == false && _file is SmbNamedPipe) - { - _file.Send(new TransWaitNamedPipe("\\pipe" + _file.Unc), new TransWaitNamedPipeResponse - ()); - } - WriteDirect(b, off, len, 0); - } - - /// Just bypasses TransWaitNamedPipe - used by DCERPC bind. - /// Just bypasses TransWaitNamedPipe - used by DCERPC bind. - /// - public virtual void WriteDirect(byte[] b, int off, int len, int flags) - { - if (len <= 0) - { - return; - } - if (_tmp == null) - { - throw new IOException("Bad file descriptor"); - } - EnsureOpen(); - /*if (file.log.level >= 4) - { - file.log.WriteLine("write: fid=" + file.fid + ",off=" + off + ",len=" + len); - }*/ - int w; - do - { - w = len > _writeSize ? _writeSize : len; - if (_useNtSmbs) - { - _reqx.SetParam(_file.Fid, _fp, len - w, b, off, w); - if ((flags & 1) != 0) - { - _reqx.SetParam(_file.Fid, _fp, len, b, off, w); - _reqx.WriteMode = 0x8; - } - else - { - _reqx.WriteMode = 0; - } - _file.Send(_reqx, _rspx); - _fp += _rspx.Count; - len -= (int)_rspx.Count; - off += (int)_rspx.Count; - } - else - { - _req.SetParam(_file.Fid, _fp, len - w, b, off, w); - _fp += _rsp.Count; - len -= (int)_rsp.Count; - off += (int)_rsp.Count; - _file.Send(_req, _rsp); - } - } - while (len > 0); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs deleted file mode 100644 index b66dc133a1..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbFilenameFilter.cs +++ /dev/null @@ -1,24 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public interface ISmbFilenameFilter - { - /// - bool Accept(SmbFile dir, string name); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs deleted file mode 100644 index f09e16cca4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbNamedPipe.cs +++ /dev/null @@ -1,210 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - /// - /// This class will allow a Java program to read and write data to Named - /// Pipes and Transact NamedPipes. - /// - /// - /// This class will allow a Java program to read and write data to Named - /// Pipes and Transact NamedPipes. - ///

There are three Win32 function calls provided by the Windows SDK - /// that are important in the context of using jCIFS. They are: - ///

    - ///
  • CallNamedPipe A message-type pipe call that opens, - /// writes to, reads from, and closes the pipe in a single operation. - ///
  • TransactNamedPipe A message-type pipe call that - /// writes to and reads from an existing pipe descriptor in one operation. - ///
  • CreateFile, ReadFile, - /// WriteFile, and CloseFile A byte-type pipe can - /// be opened, written to, read from and closed using the standard Win32 - /// file operations. - ///
- ///

The jCIFS API maps all of these operations into the standard Java - /// XxxputStream interface. A special PIPE_TYPE - /// flags is necessary to distinguish which type of Named Pipe behavior - /// is desired. - ///

- /// - /// - /// - /// - /// - /// - ///
SmbNamedPipe Constructor Examples
Code SampleDescription
-	/// new SmbNamedPipe( "smb://server/IPC$/PIPE/foo",
-	/// SmbNamedPipe.PIPE_TYPE_RDWR |
-	/// SmbNamedPipe.PIPE_TYPE_CALL );
-	/// 
- /// Open the Named Pipe foo for reading and writing. The pipe will behave like the CallNamedPipe interface. - ///
-	/// new SmbNamedPipe( "smb://server/IPC$/foo",
-	/// SmbNamedPipe.PIPE_TYPE_RDWR |
-	/// SmbNamedPipe.PIPE_TYPE_TRANSACT );
-	/// 
- /// Open the Named Pipe foo for reading and writing. The pipe will behave like the TransactNamedPipe interface. - ///
-	/// new SmbNamedPipe( "smb://server/IPC$/foo",
-	/// SmbNamedPipe.PIPE_TYPE_RDWR );
-	/// 
- /// Open the Named Pipe foo for reading and writing. The pipe will - /// behave as though the CreateFile, ReadFile, - /// WriteFile, and CloseFile interface was - /// being used. - ///
- ///

See Using jCIFS to Connect to Win32 - /// Named Pipes for a detailed description of how to use jCIFS with - /// Win32 Named Pipe server processes. - /// - public class SmbNamedPipe : SmbFile - { - ///

The pipe should be opened read-only. - /// The pipe should be opened read-only. - public const int PipeTypeRdonly = ORdonly; - - /// The pipe should be opened only for writing. - /// The pipe should be opened only for writing. - public const int PipeTypeWronly = OWronly; - - /// The pipe should be opened for both reading and writing. - /// The pipe should be opened for both reading and writing. - public const int PipeTypeRdwr = ORdwr; - - /// Pipe operations should behave like the CallNamedPipe Win32 Named Pipe function. - /// - /// Pipe operations should behave like the CallNamedPipe Win32 Named Pipe function. - /// - public const int PipeTypeCall = unchecked(0x0100); - - /// Pipe operations should behave like the TransactNamedPipe Win32 Named Pipe function. - /// - /// Pipe operations should behave like the TransactNamedPipe Win32 Named Pipe function. - /// - public const int PipeTypeTransact = unchecked(0x0200); - - public const int PipeTypeDceTransact = unchecked(0x0200) | unchecked(0x0400); - - internal InputStream PipeIn; - - internal OutputStream PipeOut; - - internal int PipeType; - - /// - /// Open the Named Pipe resource specified by the url - /// parameter. - /// - /// - /// Open the Named Pipe resource specified by the url - /// parameter. The pipeType parameter should be at least one of - /// the PIPE_TYPE flags combined with the bitwise OR - /// operator |. See the examples listed above. - /// - /// - /// - public SmbNamedPipe(string url, int pipeType) : base(url) - { - this.PipeType = pipeType; - Type = TypeNamedPipe; - } - - /// - /// - public SmbNamedPipe(string url, int pipeType, NtlmPasswordAuthentication auth) : - base(url, auth) - { - this.PipeType = pipeType; - Type = TypeNamedPipe; - } - - /// - /// - public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth) : base - (url, auth) - { - this.PipeType = pipeType; - Type = TypeNamedPipe; - } - - /// - /// Return the InputStream used to read information - /// from this pipe instance. - /// - /// - /// Return the InputStream used to read information - /// from this pipe instance. Presumably data would first be written - /// to the OutputStream associated with this Named - /// Pipe instance although this is not a requirement (e.g. a - /// read-only named pipe would write data to this stream on - /// connection). Reading from this stream may block. Therefore it - /// may be necessary that an addition thread be used to read and - /// write to a Named Pipe. - /// - /// - public virtual InputStream GetNamedPipeInputStream() - { - if (PipeIn == null) - { - if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact - ) == PipeTypeTransact) - { - PipeIn = new TransactNamedPipeInputStream(this); - } - else - { - PipeIn = new SmbFileInputStream(this, (PipeType & unchecked((int)(0xFFFF00FF))) | - OExcl); - } - } - return PipeIn; - } - - /// - /// Return the OutputStream used to write - /// information to this pipe instance. - /// - /// - /// Return the OutputStream used to write - /// information to this pipe instance. The act of writing data - /// to this stream will result in response data recieved in the - /// InputStream associated with this Named Pipe - /// instance (unless of course it does not elicite a response or the pipe is write-only). - /// - /// - public virtual OutputStream GetNamedPipeOutputStream() - { - if (PipeOut == null) - { - if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact - ) == PipeTypeTransact) - { - PipeOut = new TransactNamedPipeOutputStream(this); - } - else - { - PipeOut = new SmbFileOutputStream(this, false, (PipeType & unchecked((int)(0xFFFF00FF - ))) | OExcl); - } - } - return PipeOut; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs deleted file mode 100644 index 445a0656c8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbRandomAccessFile.cs +++ /dev/null @@ -1,506 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using System.Text; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - public class SmbRandomAccessFile //: DataOutput, DataInput - { - private const int WriteOptions = unchecked(0x0842); - - private SmbFile _file; - - private long _fp; - - private int _openFlags; - - private int _access; - - private int _readSize; - - private int _writeSize; - - private int _ch; - - private int _options; - - private byte[] _tmp = new byte[8]; - - private SmbComWriteAndXResponse _writeAndxResp; - - /// - /// - /// - public SmbRandomAccessFile(string url, string mode, int shareAccess) : this(new SmbFile - (url, string.Empty, null, shareAccess), mode) - { - } - - /// - /// - /// - public SmbRandomAccessFile(SmbFile file, string mode) - { - this._file = file; - if (mode.Equals("r")) - { - _openFlags = SmbFile.OCreat | SmbFile.ORdonly; - } - else - { - if (mode.Equals("rw")) - { - _openFlags = SmbFile.OCreat | SmbFile.ORdwr | SmbFile.OAppend; - _writeAndxResp = new SmbComWriteAndXResponse(); - _options = WriteOptions; - _access = SmbConstants.FileReadData | SmbConstants.FileWriteData; - } - else - { - throw new ArgumentException("Invalid mode"); - } - } - file.Open(_openFlags, _access, SmbFile.AttrNormal, _options); - _readSize = file.Tree.Session.transport.RcvBufSize - 70; - _writeSize = file.Tree.Session.transport.SndBufSize - 70; - _fp = 0L; - } - - /// - public virtual int Read() - { - if (Read(_tmp, 0, 1) == -1) - { - return -1; - } - return _tmp[0] & unchecked(0xFF); - } - - /// - public virtual int Read(byte[] b) - { - return Read(b, 0, b.Length); - } - - /// - public virtual int Read(byte[] b, int off, int len) - { - if (len <= 0) - { - return 0; - } - long start = _fp; - // ensure file is open - if (_file.IsOpen() == false) - { - _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options); - } - int r; - int n; - SmbComReadAndXResponse response = new SmbComReadAndXResponse(b, off); - do - { - r = len > _readSize ? _readSize : len; - _file.Send(new SmbComReadAndX(_file.Fid, _fp, r, null), response); - if ((n = response.DataLength) <= 0) - { - return (int)((_fp - start) > 0L ? _fp - start : -1); - } - _fp += n; - len -= n; - response.Off += n; - } - while (len > 0 && n == r); - return (int)(_fp - start); - } - - /// - public void ReadFully(byte[] b) - { - ReadFully(b, 0, b.Length); - } - - /// - public void ReadFully(byte[] b, int off, int len) - { - int n = 0; - int count; - do - { - count = Read(b, off + n, len - n); - if (count < 0) - { - throw new SmbException("EOF"); - } - n += count; - _fp += count; - } - while (n < len); - } - - /// - public virtual int SkipBytes(int n) - { - if (n > 0) - { - _fp += n; - return n; - } - return 0; - } - - /// - public virtual void Write(int b) - { - _tmp[0] = unchecked((byte)b); - Write(_tmp, 0, 1); - } - - /// - public virtual void Write(byte[] b) - { - Write(b, 0, b.Length); - } - - /// - public virtual void Write(byte[] b, int off, int len) - { - if (len <= 0) - { - return; - } - // ensure file is open - if (_file.IsOpen() == false) - { - _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options); - } - int w; - do - { - w = len > _writeSize ? _writeSize : len; - _file.Send(new SmbComWriteAndX(_file.Fid, _fp, len - w, b, off, w, null), _writeAndxResp - ); - _fp += _writeAndxResp.Count; - len -= (int)_writeAndxResp.Count; - off += (int)_writeAndxResp.Count; - } - while (len > 0); - } - - /// - public virtual long GetFilePointer() - { - return _fp; - } - - /// - public virtual void Seek(long pos) - { - _fp = pos; - } - - /// - public virtual long Length() - { - return _file.Length(); - } - - /// - public virtual void SetLength(long newLength) - { - // ensure file is open - if (_file.IsOpen() == false) - { - _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options); - } - SmbComWriteResponse rsp = new SmbComWriteResponse(); - _file.Send(new SmbComWrite(_file.Fid, (int)(newLength & unchecked(0xFFFFFFFFL)), 0, _tmp, 0, 0), rsp); - } - - /// - public virtual void Close() - { - _file.Close(); - } - - /// - public bool ReadBoolean() - { - if ((Read(_tmp, 0, 1)) < 0) - { - throw new SmbException("EOF"); - } - return _tmp[0] != unchecked(unchecked(0x00)); - } - - /// - public byte ReadByte() - { - if ((Read(_tmp, 0, 1)) < 0) - { - throw new SmbException("EOF"); - } - return _tmp[0]; - } - - /// - public int ReadUnsignedByte() - { - if ((Read(_tmp, 0, 1)) < 0) - { - throw new SmbException("EOF"); - } - return _tmp[0] & unchecked(0xFF); - } - - /// - public short ReadShort() - { - if ((Read(_tmp, 0, 2)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_uint16be(_tmp, 0); - } - - /// - public int ReadUnsignedShort() - { - if ((Read(_tmp, 0, 2)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_uint16be(_tmp, 0) & unchecked(0xFFFF); - } - - /// - public char ReadChar() - { - if ((Read(_tmp, 0, 2)) < 0) - { - throw new SmbException("EOF"); - } - return (char)Encdec.Dec_uint16be(_tmp, 0); - } - - /// - public int ReadInt() - { - if ((Read(_tmp, 0, 4)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_uint32be(_tmp, 0); - } - - /// - public long ReadLong() - { - if ((Read(_tmp, 0, 8)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_uint64be(_tmp, 0); - } - - /// - public float ReadFloat() - { - if ((Read(_tmp, 0, 4)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_floatbe(_tmp, 0); - } - - /// - public double ReadDouble() - { - if ((Read(_tmp, 0, 8)) < 0) - { - throw new SmbException("EOF"); - } - return Encdec.Dec_doublebe(_tmp, 0); - } - - /// - public string ReadLine() - { - StringBuilder input = new StringBuilder(); - int c = -1; - bool eol = false; - while (!eol) - { - switch (c = Read()) - { - case -1: - case '\n': - { - eol = true; - break; - } - - case '\r': - { - eol = true; - long cur = _fp; - if (Read() != '\n') - { - _fp = cur; - } - break; - } - - default: - { - input.Append((char)c); - break; - } - } - } - if ((c == -1) && (input.Length == 0)) - { - return null; - } - return input.ToString(); - } - - /// - public string ReadUtf() - { - int size = ReadUnsignedShort(); - byte[] b = new byte[size]; - Read(b, 0, size); - try - { - return Encdec.Dec_utf8(b, 0, size); - } - catch (IOException ioe) - { - throw new SmbException(string.Empty, ioe); - } - } - - /// - public void WriteBoolean(bool v) - { - _tmp[0] = unchecked((byte)(v ? 1 : 0)); - Write(_tmp, 0, 1); - } - - /// - public void WriteByte(int v) - { - _tmp[0] = unchecked((byte)v); - Write(_tmp, 0, 1); - } - - /// - public void WriteShort(int v) - { - Encdec.Enc_uint16be((short)v, _tmp, 0); - Write(_tmp, 0, 2); - } - - /// - public void WriteChar(int v) - { - Encdec.Enc_uint16be((short)v, _tmp, 0); - Write(_tmp, 0, 2); - } - - /// - public void WriteInt(int v) - { - Encdec.Enc_uint32be(v, _tmp, 0); - Write(_tmp, 0, 4); - } - - /// - public void WriteLong(long v) - { - Encdec.Enc_uint64be(v, _tmp, 0); - Write(_tmp, 0, 8); - } - - /// - public void WriteFloat(float v) - { - Encdec.Enc_floatbe(v, _tmp, 0); - Write(_tmp, 0, 4); - } - - /// - public void WriteDouble(double v) - { - Encdec.Enc_doublebe(v, _tmp, 0); - Write(_tmp, 0, 8); - } - - /// - public void WriteBytes(string s) - { - byte[] b = Runtime.GetBytesForString(s); - Write(b, 0, b.Length); - } - - /// - /* public void WriteChars(string s) - { - int clen = s.Length; - int blen = 2 * clen; - byte[] b = new byte[blen]; - char[] c = new char[clen]; - Sharpen.Runtime.GetCharsForString(s, 0, clen, c, 0); - for (int i = 0, j = 0; i < clen; i++) - { - b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 8))); - b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 0))); - } - Write(b, 0, blen); - }*/ - - /// - public void WriteUtf(string str) - { - int len = str.Length; - int ch; - int size = 0; - byte[] dst; - for (int i = 0; i < len; i++) - { - ch = str[i]; - size += ch > unchecked(0x07F) ? (ch > unchecked(0x7FF) ? 3 : 2) : 1; - } - dst = new byte[size]; - WriteShort(size); - try - { - Encdec.Enc_utf8(str, dst, 0, size); - } - catch (IOException ioe) - { - throw new SmbException(string.Empty, ioe); - } - Write(dst, 0, size); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs deleted file mode 100644 index 6dc5087d0c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbSession.cs +++ /dev/null @@ -1,570 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using SharpCifs.Netbios; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - public sealed class SmbSession - { - private static readonly string LogonShare = Config.GetProperty("jcifs.smb.client.logonShare" - , null); - - private static readonly int LookupRespLimit = Config.GetInt("jcifs.netbios.lookupRespLimit" - , 3); - - private static readonly string Domain = Config.GetProperty("jcifs.smb.client.domain" - , null); - - private static readonly string Username = Config.GetProperty("jcifs.smb.client.username" - , null); - - private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy" - , 60 * 10) * 60; - - internal static NbtAddress[] DcList; - - internal static long DcListExpiration; - - internal static int DcListCounter; - - /// - private static NtlmChallenge Interrogate(NbtAddress addr) - { - UniAddress dc = new UniAddress(addr); - SmbTransport trans = SmbTransport.GetSmbTransport(dc, 0); - if (Username == null) - { - trans.Connect(); - if (SmbTransport.LogStatic.Level >= 3) - { - SmbTransport.LogStatic.WriteLine("Default credentials (jcifs.smb.client.username/password)" - + " not specified. SMB signing may not work propertly." + " Skipping DC interrogation." - ); - } - } - else - { - SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default - ); - ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null); - } - return new NtlmChallenge(trans.Server.EncryptionKey, dc); - } - - /// - /// - public static NtlmChallenge GetChallengeForDomain() - { - if (Domain == null) - { - throw new SmbException("A domain was not specified"); - } - lock (Domain) - { - long now = Runtime.CurrentTimeMillis(); - int retry = 1; - do - { - if (DcListExpiration < now) - { - NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, - null); - DcListExpiration = now + CachePolicy * 1000L; - if (list != null && list.Length > 0) - { - DcList = list; - } - else - { - DcListExpiration = now + 1000 * 60 * 15; - if (SmbTransport.LogStatic.Level >= 2) - { - SmbTransport.LogStatic.WriteLine("Failed to retrieve DC list from WINS"); - } - } - } - int max = Math.Min(DcList.Length, LookupRespLimit); - for (int j = 0; j < max; j++) - { - int i = DcListCounter++ % max; - if (DcList[i] != null) - { - try - { - return Interrogate(DcList[i]); - } - catch (SmbException se) - { - if (SmbTransport.LogStatic.Level >= 2) - { - SmbTransport.LogStatic.WriteLine("Failed validate DC: " + DcList[i]); - if (SmbTransport.LogStatic.Level > 2) - { - Runtime.PrintStackTrace(se, SmbTransport.LogStatic); - } - } - } - DcList[i] = null; - } - } - DcListExpiration = 0; - } - while (retry-- > 0); - DcListExpiration = now + 1000 * 60 * 15; - } - throw new UnknownHostException("Failed to negotiate with a suitable domain controller for " - + Domain); - } - - /// - /// - public static byte[] GetChallenge(UniAddress dc) - { - return GetChallenge(dc, 0); - } - - /// - /// - public static byte[] GetChallenge(UniAddress dc, int port) - { - SmbTransport trans = SmbTransport.GetSmbTransport(dc, port); - trans.Connect(); - return trans.Server.EncryptionKey; - } - - /// - /// Authenticate arbitrary credentials represented by the - /// NtlmPasswordAuthentication object against the domain controller - /// specified by the UniAddress parameter. - /// - /// - /// Authenticate arbitrary credentials represented by the - /// NtlmPasswordAuthentication object against the domain controller - /// specified by the UniAddress parameter. If the credentials are - /// not accepted, an SmbAuthException will be thrown. If an error - /// occurs an SmbException will be thrown. If the credentials are - /// valid, the method will return without throwing an exception. See the - /// last FAQ question. - ///

- /// See also the jcifs.smb.client.logonShare property. - /// - /// - public static void Logon(UniAddress dc, NtlmPasswordAuthentication auth) - { - Logon(dc, -1, auth); - } - - /// - public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth - ) - { - SmbTree tree = SmbTransport.GetSmbTransport(dc, port).GetSmbSession(auth).GetSmbTree - (LogonShare, null); - if (LogonShare == null) - { - tree.TreeConnect(null, null); - } - else - { - Trans2FindFirst2 req = new Trans2FindFirst2("\\", "*", SmbFile.AttrDirectory); - Trans2FindFirst2Response resp = new Trans2FindFirst2Response(); - tree.Send(req, resp); - } - } - - internal int ConnectionState; - - internal int Uid; - - internal List Trees; - - private UniAddress _address; - - private int _port; - - private int _localPort; - - private IPAddress _localAddr; - - internal SmbTransport transport; - - internal NtlmPasswordAuthentication Auth; - - internal long Expiration; - - internal string NetbiosName; - - internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort - , NtlmPasswordAuthentication auth) - { - // Transport parameters allows trans to be removed from CONNECTIONS - this._address = address; - this._port = port; - this._localAddr = localAddr; - this._localPort = localPort; - this.Auth = auth; - Trees = new List(); - ConnectionState = 0; - } - - internal SmbTree GetSmbTree(string share, string service) - { - lock (this) - { - SmbTree t; - if (share == null) - { - share = "IPC$"; - } - /*for (IEnumeration e = trees.GetEnumerator(); e.MoveNext(); ) - { - t = (SmbTree)e.Current; - if (t.Matches(share, service)) - { - return t; - } - }*/ - foreach (var e in Trees) - { - t = (SmbTree)e; - if (t.Matches(share, service)) - { - return t; - } - } - - t = new SmbTree(this, share, service); - Trees.Add(t); - return t; - } - } - - internal bool Matches(NtlmPasswordAuthentication auth) - { - return this.Auth == auth || this.Auth.Equals(auth); - } - - internal SmbTransport Transport() - { - lock (this) - { - if (transport == null) - { - transport = SmbTransport.GetSmbTransport(_address, _port, _localAddr, _localPort, null - ); - } - return transport; - } - } - - /// - internal void Send(ServerMessageBlock request, ServerMessageBlock response) - { - lock (Transport()) - { - if (response != null) - { - response.Received = false; - } - Expiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout; - SessionSetup(request, response); - if (response != null && response.Received) - { - return; - } - if (request is SmbComTreeConnectAndX) - { - SmbComTreeConnectAndX tcax = (SmbComTreeConnectAndX)request; - if (NetbiosName != null && tcax.path.EndsWith("\\IPC$")) - { - tcax.path = "\\\\" + NetbiosName + "\\IPC$"; - } - } - request.Uid = Uid; - request.Auth = Auth; - try - { - transport.Send(request, response); - } - catch (SmbException se) - { - if (request is SmbComTreeConnectAndX) - { - Logoff(true); - } - request.Digest = null; - throw; - } - } - } - - /// - internal void SessionSetup(ServerMessageBlock andx, ServerMessageBlock andxResponse - ) - { - lock (Transport()) - { - NtlmContext nctx = null; - SmbException ex = null; - SmbComSessionSetupAndX request; - SmbComSessionSetupAndXResponse response; - byte[] token = new byte[0]; - int state = 10; - while (ConnectionState != 0) - { - if (ConnectionState == 2 || ConnectionState == 3) - { - // connected or disconnecting - return; - } - try - { - Runtime.Wait(transport); - } - catch (Exception ie) - { - throw new SmbException(ie.Message, ie); - } - } - ConnectionState = 1; - // trying ... - try - { - transport.Connect(); - if (transport.Log.Level >= 4) - { - transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username + ",primaryDomain=" - + Auth.Domain); - } - Uid = 0; - do - { - switch (state) - { - case 10: - { - if (Auth != NtlmPasswordAuthentication.Anonymous && transport.HasCapability(SmbConstants - .CapExtendedSecurity)) - { - state = 20; - break; - } - request = new SmbComSessionSetupAndX(this, andx, Auth); - response = new SmbComSessionSetupAndXResponse(andxResponse); - if (transport.IsSignatureSetupRequired(Auth)) - { - if (Auth.HashesExternal && NtlmPasswordAuthentication.DefaultPassword != NtlmPasswordAuthentication - .Blank) - { - transport.GetSmbSession(NtlmPasswordAuthentication.Default).GetSmbTree(LogonShare - , null).TreeConnect(null, null); - } - else - { - byte[] signingKey = Auth.GetSigningKey(transport.Server.EncryptionKey); - request.Digest = new SigningDigest(signingKey, false); - } - } - request.Auth = Auth; - try - { - transport.Send(request, response); - } - catch (SmbAuthException sae) - { - throw; - } - catch (SmbException se) - { - ex = se; - } - if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth. - Username) == false && transport.Server.Security != SmbConstants.SecurityShare && - Auth != NtlmPasswordAuthentication.Anonymous) - { - throw new SmbAuthException(NtStatus.NtStatusLogonFailure); - } - if (ex != null) - { - throw ex; - } - Uid = response.Uid; - if (request.Digest != null) - { - transport.Digest = request.Digest; - } - ConnectionState = 2; - state = 0; - break; - } - - case 20: - { - if (nctx == null) - { - bool doSigning = (transport.Flags2 & SmbConstants.Flags2SecuritySignatures - ) != 0; - nctx = new NtlmContext(Auth, doSigning); - } - if (SmbTransport.LogStatic.Level >= 4) - { - SmbTransport.LogStatic.WriteLine(nctx); - } - if (nctx.IsEstablished()) - { - NetbiosName = nctx.GetNetbiosName(); - ConnectionState = 2; - state = 0; - break; - } - try - { - token = nctx.InitSecContext(token, 0, token.Length); - } - catch (SmbException se) - { - try - { - transport.Disconnect(true); - } - catch (IOException) - { - } - Uid = 0; - throw; - } - if (token != null) - { - request = new SmbComSessionSetupAndX(this, null, token); - response = new SmbComSessionSetupAndXResponse(null); - if (transport.IsSignatureSetupRequired(Auth)) - { - byte[] signingKey = nctx.GetSigningKey(); - if (signingKey != null) - { - request.Digest = new SigningDigest(signingKey, true); - } - } - request.Uid = Uid; - Uid = 0; - try - { - transport.Send(request, response); - } - catch (SmbAuthException sae) - { - throw; - } - catch (SmbException se) - { - ex = se; - try - { - transport.Disconnect(true); - } - catch (Exception) - { - } - } - if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth. - Username) == false) - { - throw new SmbAuthException(NtStatus.NtStatusLogonFailure); - } - if (ex != null) - { - throw ex; - } - Uid = response.Uid; - if (request.Digest != null) - { - transport.Digest = request.Digest; - } - token = response.Blob; - } - break; - } - - default: - { - throw new SmbException("Unexpected session setup state: " + state); - } - } - } - while (state != 0); - } - catch (SmbException se) - { - Logoff(true); - ConnectionState = 0; - throw; - } - finally - { - Runtime.NotifyAll(transport); - } - } - } - - internal void Logoff(bool inError) - { - lock (Transport()) - { - if (ConnectionState != 2) - { - // not-connected - return; - } - ConnectionState = 3; - // disconnecting - NetbiosName = null; - - foreach (SmbTree t in Trees) - { - t.TreeDisconnect(inError); - } - - if (!inError && transport.Server.Security != SmbConstants.SecurityShare) - { - SmbComLogoffAndX request = new SmbComLogoffAndX(null); - request.Uid = Uid; - try - { - transport.Send(request, null); - } - catch (SmbException) - { - } - Uid = 0; - } - ConnectionState = 0; - Runtime.NotifyAll(transport); - } - } - - public override string ToString() - { - return "SmbSession[accountName=" + Auth.Username + ",primaryDomain=" + Auth.Domain - + ",uid=" + Uid + ",connectionState=" + ConnectionState + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs deleted file mode 100644 index 811c76794e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbShareInfo.cs +++ /dev/null @@ -1,104 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - public class SmbShareInfo : IFileEntry - { - protected internal string NetName; - - protected internal int Type; - - protected internal string Remark; - - public SmbShareInfo() - { - } - - public SmbShareInfo(string netName, int type, string remark) - { - this.NetName = netName; - this.Type = type; - this.Remark = remark; - } - - public virtual string GetName() - { - return NetName; - } - - public new virtual int GetType() - { - switch (Type & unchecked(0xFFFF)) - { - case 1: - { - return SmbFile.TypePrinter; - } - - case 3: - { - return SmbFile.TypeNamedPipe; - } - } - return SmbFile.TypeShare; - } - - public virtual int GetAttributes() - { - return SmbFile.AttrReadonly | SmbFile.AttrDirectory; - } - - public virtual long CreateTime() - { - return 0L; - } - - public virtual long LastModified() - { - return 0L; - } - - public virtual long Length() - { - return 0L; - } - - public override bool Equals(object obj) - { - if (obj is SmbShareInfo) - { - SmbShareInfo si = (SmbShareInfo)obj; - return NetName.Equals(si.NetName); - } - return false; - } - - public override int GetHashCode() - { - int hashCode = NetName.GetHashCode(); - return hashCode; - } - - public override string ToString() - { - return "SmbShareInfo[" + "netName=" + NetName + ",type=0x" + Hexdump.ToHexString - (Type, 8) + ",remark=" + Remark + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs deleted file mode 100644 index 800d6d9bc1..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTransport.cs +++ /dev/null @@ -1,977 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using SharpCifs.Netbios; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; -using SharpCifs.Util.Transport; - -namespace SharpCifs.Smb -{ - public class SmbTransport : Transport - { - internal static readonly byte[] Buf = new byte[0xFFFF]; - - internal static readonly SmbComNegotiate NegotiateRequest = new SmbComNegotiate( - ); - - internal static LogStream LogStatic = LogStream.GetInstance(); - - internal static Hashtable DfsRoots = null; - - - internal static SmbTransport GetSmbTransport(UniAddress address, int port - ) - { - lock (typeof(SmbTransport)) - { - return GetSmbTransport(address, port, SmbConstants.Laddr, SmbConstants.Lport, null); - } - } - - internal static SmbTransport GetSmbTransport(UniAddress address, int port - , IPAddress localAddr, int localPort, string hostName) - { - lock (typeof(SmbTransport)) - { - SmbTransport conn; - - lock (SmbConstants.Connections) - { - if (SmbConstants.SsnLimit != 1) - { - conn = - SmbConstants.Connections.FirstOrDefault( - c => - c.Matches(address, port, localAddr, localPort, hostName) && - (SmbConstants.SsnLimit == - 0 || c.Sessions.Count < SmbConstants.SsnLimit)); - - if (conn != null) - { - return conn; - } - - } - - conn = new SmbTransport(address, port, localAddr, localPort); - SmbConstants.Connections.Insert(0, conn); - } - return conn; - } - } - - internal class ServerData - { - internal byte Flags; - - internal int Flags2; - - internal int MaxMpxCount; - - internal int MaxBufferSize; - - internal int SessionKey; - - internal int Capabilities; - - internal string OemDomainName; - - internal int SecurityMode; - - internal int Security; - - internal bool EncryptedPasswords; - - internal bool SignaturesEnabled; - - internal bool SignaturesRequired; - - internal int MaxNumberVcs; - - internal int MaxRawSize; - - internal long ServerTime; - - internal int ServerTimeZone; - - internal int EncryptionKeyLength; - - internal byte[] EncryptionKey; - - internal byte[] Guid; - - internal ServerData(SmbTransport enclosing) - { - this._enclosing = enclosing; - } - - private readonly SmbTransport _enclosing; - } - - internal IPAddress LocalAddr; - - internal int LocalPort; - - internal UniAddress Address; - - internal SocketEx Socket; - - internal int Port; - - internal int Mid; - - internal OutputStream Out; - - internal InputStream In; - - internal byte[] Sbuf = new byte[512]; - - internal SmbComBlankResponse Key = new SmbComBlankResponse(); - - internal long SessionExpiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout; - - internal List Referrals = new List(); - - internal SigningDigest Digest; - - internal List Sessions = new List(); - - internal ServerData Server; - - internal int Flags2 = SmbConstants.Flags2; - - internal int MaxMpxCount = SmbConstants.MaxMpxCount; - - internal int SndBufSize = SmbConstants.SndBufSize; - - internal int RcvBufSize = SmbConstants.RcvBufSize; - - internal int Capabilities = SmbConstants.Capabilities; - - internal int SessionKey = 0x00000000; - - internal bool UseUnicode = SmbConstants.UseUnicode; - - internal string TconHostName; - - internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort - ) - { - Server = new ServerData(this); - this.Address = address; - this.Port = port; - this.LocalAddr = localAddr; - this.LocalPort = localPort; - } - - internal virtual SmbSession GetSmbSession() - { - lock (this) - { - return GetSmbSession(new NtlmPasswordAuthentication(null, null, null)); - } - } - - internal virtual SmbSession GetSmbSession(NtlmPasswordAuthentication auth) - { - lock (this) - { - SmbSession ssn; - long now; - - ssn = Sessions.FirstOrDefault(s => s.Matches(auth)); - if (ssn != null) - { - ssn.Auth = auth; - return ssn; - } - - if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis())) - { - SessionExpiration = now + SmbConstants.SoTimeout; - - foreach (var session in Sessions.Where(s => s.Expiration < now)) - { - session.Logoff(false); - } - } - ssn = new SmbSession(Address, Port, LocalAddr, LocalPort, auth); - ssn.transport = this; - Sessions.Add(ssn); - return ssn; - } - } - - internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr, - int localPort, string hostName) - { - if (hostName == null) - { - hostName = address.GetHostName(); - } - return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && address.Equals(this.Address) && (port == -1 || port == this.Port - || (port == 445 && this.Port == 139)) && (localAddr == this.LocalAddr || (localAddr - != null && localAddr.Equals(this.LocalAddr))) && localPort == this.LocalPort; - } - - /// - internal virtual bool HasCapability(int cap) - { - try - { - Connect(SmbConstants.ResponseTimeout); - } - catch (IOException ioe) - { - throw new SmbException(ioe.Message, ioe); - } - return (Capabilities & cap) == cap; - } - - internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth) - { - return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest == - null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null - .Equals(auth) == false; - } - - /// - internal virtual void Ssn139() - { - Name calledName = new Name(Address.FirstCalledName(), 0x20, null - ); - do - { - Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - if (LocalAddr != null) - { - Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort)); - } - - Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout); - Socket.SoTimeOut = SmbConstants.SoTimeout; - - Out = Socket.GetOutputStream(); - In = Socket.GetInputStream(); - SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName - ()); - Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0)); - if (Readn(In, Sbuf, 0, 4) < 4) - { - try - { - //Socket.`Close` method deleted - //Socket.Close(); - Socket.Dispose(); - } - catch (IOException) - { - } - throw new SmbException("EOF during NetBIOS session request"); - } - switch (Sbuf[0] & 0xFF) - { - case SessionServicePacket.PositiveSessionResponse: - { - if (Log.Level >= 4) - { - Log.WriteLine("session established ok with " + Address); - } - return; - } - - case SessionServicePacket.NegativeSessionResponse: - { - int errorCode = In.Read() & 0xFF; - switch (errorCode) - { - case NbtException.CalledNotPresent: - case NbtException.NotListeningCalled: - { - //Socket.`Close` method deleted - //Socket.Close(); - Socket.Dispose(); - break; - } - - default: - { - Disconnect(true); - throw new NbtException(NbtException.ErrSsnSrvc, errorCode); - } - } - break; - } - - case -1: - { - Disconnect(true); - throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused - ); - } - - default: - { - Disconnect(true); - throw new NbtException(NbtException.ErrSsnSrvc, 0); - } - } - } - while ((calledName.name = Address.NextCalledName()) != null); - throw new IOException("Failed to establish session with " + Address); - } - - /// - private void Negotiate(int port, ServerMessageBlock resp) - { - lock (Sbuf) - { - if (port == 139) - { - Ssn139(); - } - else - { - if (port == -1) - { - port = SmbConstants.DefaultPort; - } - // 445 - Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - if (LocalAddr != null) - { - Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort)); - } - - Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), port), SmbConstants.ConnTimeout); - Socket.SoTimeOut = SmbConstants.SoTimeout; - Out = Socket.GetOutputStream(); - In = Socket.GetInputStream(); - } - if (++Mid == 32000) - { - Mid = 1; - } - NegotiateRequest.Mid = Mid; - int n = NegotiateRequest.Encode(Sbuf, 4); - Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0); - if (Log.Level >= 4) - { - Log.WriteLine(NegotiateRequest); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, Sbuf, 4, n); - } - } - Out.Write(Sbuf, 0, 4 + n); - Out.Flush(); - if (PeekKey() == null) - { - throw new IOException("transport closed in negotiate"); - } - int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF; - if (size < 33 || (4 + size) > Sbuf.Length) - { - throw new IOException("Invalid payload size: " + size); - } - Readn(In, Sbuf, 4 + 32, size - 32); - resp.Decode(Sbuf, 4); - if (Log.Level >= 4) - { - Log.WriteLine(resp); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, Sbuf, 4, n); - } - } - } - } - - /// - public virtual void Connect() - { - try - { - base.Connect(SmbConstants.ResponseTimeout); - } - catch (TransportException te) - { - throw new SmbException("Failed to connect: " + Address, te); - } - } - - /// - protected internal override void DoConnect() - { - SmbComNegotiateResponse resp = new SmbComNegotiateResponse(Server); - try - { - Negotiate(Port, resp); - } - catch (ConnectException) - { - Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort; - Negotiate(Port, resp); - } - if (resp.DialectIndex > 10) - { - throw new SmbException("This client does not support the negotiated dialect."); - } - if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server - .EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0) - { - throw new SmbException("Unexpected encryption key length: " + Server.EncryptionKeyLength - ); - } - TconHostName = Address.GetHostName(); - if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref)) - { - Flags2 |= SmbConstants.Flags2SecuritySignatures; - } - else - { - Flags2 &= 0xFFFF ^ SmbConstants.Flags2SecuritySignatures; - } - MaxMpxCount = Math.Min(MaxMpxCount, Server.MaxMpxCount); - if (MaxMpxCount < 1) - { - MaxMpxCount = 1; - } - SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize); - Capabilities &= Server.Capabilities; - if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity) - { - Capabilities |= SmbConstants.CapExtendedSecurity; - } - // & doesn't copy high bit - if ((Capabilities & SmbConstants.CapUnicode) == 0) - { - // server doesn't want unicode - if (SmbConstants.ForceUnicode) - { - Capabilities |= SmbConstants.CapUnicode; - } - else - { - UseUnicode = false; - Flags2 &= 0xFFFF ^ SmbConstants.Flags2Unicode; - } - } - } - - /// - protected internal override void DoDisconnect(bool hard) - { - try - { - foreach (var ssn in Sessions) - { - ssn.Logoff(hard); - } - - Out.Close(); - In.Close(); - - //Socket.`Close` method deleted - //Socket.Close(); - Socket.Dispose(); - } - finally - { - Digest = null; - Socket = null; - TconHostName = null; - } - - } - - /// - protected internal override void MakeKey(ServerMessageBlock request) - { - if (++Mid == 32000) - { - Mid = 1; - } - request.Mid = Mid; - } - - /// - protected internal override ServerMessageBlock PeekKey() - { - int n; - do - { - if ((n = Readn(In, Sbuf, 0, 4)) < 4) - { - return null; - } - } - while (Sbuf[0] == 0x85); - if ((n = Readn(In, Sbuf, 4, 32)) < 32) - { - return null; - } - if (Log.Level >= 4) - { - Log.WriteLine("New data read: " + this); - Hexdump.ToHexdump(Log, Sbuf, 4, 32); - } - for (; ; ) - { - if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 && - Sbuf[4] == 0xFF && - Sbuf[5] == 'S' && - Sbuf[6] == 'M' && - Sbuf[7] == 'B') - { - break; - } - for (int i = 0; i < 35; i++) - { - Sbuf[i] = Sbuf[i + 1]; - } - int b; - if ((b = In.Read()) == -1) - { - return null; - } - Sbuf[35] = unchecked((byte)b); - } - Key.Mid = Encdec.Dec_uint16le(Sbuf, 34) & 0xFFFF; - return Key; - } - - /// - protected internal override void DoSend(ServerMessageBlock request) - { - lock (Buf) - { - ServerMessageBlock smb = request; - int n = smb.Encode(Buf, 4); - Encdec.Enc_uint32be(n & 0xFFFF, Buf, 0); - if (Log.Level >= 4) - { - do - { - Log.WriteLine(smb); - } - while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx - ) != null); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, Buf, 4, n); - } - } - Out.Write(Buf, 0, 4 + n); - } - } - - /// - protected internal virtual void DoSend0(ServerMessageBlock request) - { - try - { - DoSend(request); - } - catch (IOException ioe) - { - if (Log.Level > 2) - { - Runtime.PrintStackTrace(ioe, Log); - } - try - { - Disconnect(true); - } - catch (IOException ioe2) - { - Runtime.PrintStackTrace(ioe2, Log); - } - throw; - } - } - - /// - protected internal override void DoRecv(Response response) - { - ServerMessageBlock resp = (ServerMessageBlock)response; - resp.UseUnicode = UseUnicode; - resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity; - lock (Buf) - { - Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength); - int size = Encdec.Dec_uint16be(Buf, 2) & 0xFFFF; - if (size < (SmbConstants.HeaderLength + 1) || (4 + size) > RcvBufSize) - { - throw new IOException("Invalid payload size: " + size); - } - int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF)); - if (resp.Command == ServerMessageBlock.SmbComReadAndx && (errorCode == 0 || errorCode - == unchecked((int)(0x80000005)))) - { - // overflow indicator normal for pipe - SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp; - int off = SmbConstants.HeaderLength; - Readn(In, Buf, 4 + off, 27); - off += 27; - resp.Decode(Buf, 4); - int pad = r.DataOffset - off; - if (r.ByteCount > 0 && pad > 0 && pad < 4) - { - Readn(In, Buf, 4 + off, pad); - } - if (r.DataLength > 0) - { - Readn(In, r.B, r.Off, r.DataLength); - } - } - else - { - Readn(In, Buf, 4 + 32, size - 32); - resp.Decode(Buf, 4); - if (resp is SmbComTransactionResponse) - { - ((SmbComTransactionResponse)resp).Current(); - } - } - if (Digest != null && resp.ErrorCode == 0) - { - Digest.Verify(Buf, 4, resp); - } - if (Log.Level >= 4) - { - Log.WriteLine(response); - if (Log.Level >= 6) - { - Hexdump.ToHexdump(Log, Buf, 4, size); - } - } - } - } - - /// - protected internal override void DoSkip() - { - int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF; - if (size < 33 || (4 + size) > RcvBufSize) - { - In.Skip(In.Available()); - } - else - { - In.Skip(size - 32); - } - } - - /// - internal virtual void CheckStatus(ServerMessageBlock req, ServerMessageBlock resp - ) - { - resp.ErrorCode = SmbException.GetStatusByCode(resp.ErrorCode); - switch (resp.ErrorCode) - { - case NtStatus.NtStatusOk: - { - break; - } - - case NtStatus.NtStatusAccessDenied: - case NtStatus.NtStatusWrongPassword: - case NtStatus.NtStatusLogonFailure: - case NtStatus.NtStatusAccountRestriction: - case NtStatus.NtStatusInvalidLogonHours: - case NtStatus.NtStatusInvalidWorkstation: - case NtStatus.NtStatusPasswordExpired: - case NtStatus.NtStatusAccountDisabled: - case NtStatus.NtStatusAccountLockedOut: - case NtStatus.NtStatusTrustedDomainFailure: - { - throw new SmbAuthException(resp.ErrorCode); - } - - case NtStatus.NtStatusPathNotCovered: - { - if (req.Auth == null) - { - throw new SmbException(resp.ErrorCode, null); - } - DfsReferral dr = GetDfsReferrals(req.Auth, req.Path, 1); - if (dr == null) - { - throw new SmbException(resp.ErrorCode, null); - } - SmbFile.Dfs.Insert(req.Path, dr); - throw dr; - } - - case unchecked((int)(0x80000005)): - { - break; - } - - case NtStatus.NtStatusMoreProcessingRequired: - { - break; - } - - default: - { - throw new SmbException(resp.ErrorCode, null); - } - } - if (resp.VerifyFailed) - { - throw new SmbException("Signature verification failed."); - } - } - - /// - internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response - ) - { - Connect(); - request.Flags2 |= Flags2; - request.UseUnicode = UseUnicode; - request.Response = response; - if (request.Digest == null) - { - request.Digest = Digest; - } - try - { - if (response == null) - { - DoSend0(request); - return; - } - if (request is SmbComTransaction) - { - response.Command = request.Command; - SmbComTransaction req = (SmbComTransaction)request; - SmbComTransactionResponse resp = (SmbComTransactionResponse)response; - req.MaxBufferSize = SndBufSize; - resp.Reset(); - try - { - BufferCache.GetBuffers(req, resp); - req.Current(); - if (req.MoveNext()) - { - SmbComBlankResponse interim = new SmbComBlankResponse(); - Sendrecv(req, interim, SmbConstants.ResponseTimeout); - if (interim.ErrorCode != 0) - { - CheckStatus(req, interim); - } - req.Current(); - } - else - { - MakeKey(req); - } - lock (this) - { - response.Received = false; - resp.IsReceived = false; - try - { - ResponseMap.Put(req, resp); - do - { - DoSend0(req); - } - while (req.MoveNext() && req.Current() != null); - long timeout = SmbConstants.ResponseTimeout; - resp.Expiration = Runtime.CurrentTimeMillis() + timeout; - while (resp.MoveNext()) - { - Runtime.Wait(this, timeout); - timeout = resp.Expiration - Runtime.CurrentTimeMillis(); - if (timeout <= 0) - { - throw new TransportException(this + " timedout waiting for response to " + req); - } - } - if (response.ErrorCode != 0) - { - CheckStatus(req, resp); - } - } - catch (Exception ie) - { - if (ie is SmbException) - { - throw; - } - else - { - throw new TransportException(ie); - } - } - finally - { - //Sharpen.Collections.Remove(response_map, req); - ResponseMap.Remove(req); - } - } - } - finally - { - BufferCache.ReleaseBuffer(req.TxnBuf); - BufferCache.ReleaseBuffer(resp.TxnBuf); - } - } - else - { - response.Command = request.Command; - Sendrecv(request, response, SmbConstants.ResponseTimeout); - } - } - catch (SmbException se) - { - throw; - } - catch (IOException ioe) - { - throw new SmbException(ioe.Message, ioe); - } - CheckStatus(request, response); - } - - public override string ToString() - { - return base.ToString() + "[" + Address + ":" + Port + "]"; - } - - internal virtual void DfsPathSplit(string path, string[] result) - { - int ri = 0; - int rlast = result.Length - 1; - int i = 0; - int b = 0; - int len = path.Length; - do - { - if (ri == rlast) - { - result[rlast] = Runtime.Substring(path, b); - return; - } - if (i == len || path[i] == '\\') - { - result[ri++] = Runtime.Substring(path, b, i); - b = i + 1; - } - } - while (i++ < len); - while (ri < result.Length) - { - result[ri++] = string.Empty; - } - } - - /// - internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string - path, int rn) - { - SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null); - Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse(); - ipc.Send(new Trans2GetDfsReferral(path), resp); - if (resp.NumReferrals == 0) - { - return null; - } - if (rn == 0 || resp.NumReferrals < rn) - { - rn = resp.NumReferrals; - } - DfsReferral dr = new DfsReferral(); - string[] arr = new string[4]; - long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000; - int di = 0; - for (; ; ) - { - dr.ResolveHashes = auth.HashesExternal; - dr.Ttl = resp.Referrals[di].Ttl; - dr.Expiration = expiration; - if (path.Equals(string.Empty)) - { - dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower(); - } - else - { - DfsPathSplit(resp.Referrals[di].Node, arr); - dr.Server = arr[1]; - dr.Share = arr[2]; - dr.Path = arr[3]; - } - dr.PathConsumed = resp.PathConsumed; - di++; - if (di == rn) - { - break; - } - dr.Append(new DfsReferral()); - dr = dr.Next; - } - return dr.Next; - } - - /// - internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth, - string path, int rn) - { - SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null); - Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse(); - ipc.Send(new Trans2GetDfsReferral(path), resp); - if (rn == 0 || resp.NumReferrals < rn) - { - rn = resp.NumReferrals; - } - DfsReferral[] drs = new DfsReferral[rn]; - string[] arr = new string[4]; - long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000; - for (int di = 0; di < drs.Length; di++) - { - DfsReferral dr = new DfsReferral(); - dr.ResolveHashes = auth.HashesExternal; - dr.Ttl = resp.Referrals[di].Ttl; - dr.Expiration = expiration; - if (path.Equals(string.Empty)) - { - dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower(); - } - else - { - DfsPathSplit(resp.Referrals[di].Node, arr); - dr.Server = arr[1]; - dr.Share = arr[2]; - dr.Path = arr[3]; - } - dr.PathConsumed = resp.PathConsumed; - drs[di] = dr; - } - return drs; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs deleted file mode 100644 index 8dc068c4c9..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/SmbTree.cs +++ /dev/null @@ -1,250 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - class SmbTree - { - private static int _treeConnCounter; - - internal int ConnectionState; - - internal int Tid; - - internal string Share; - - internal string Service = "?????"; - - internal string Service0; - - internal SmbSession Session; - - internal bool InDfs; - - internal bool InDomainDfs; - - internal int TreeNum; - - internal SmbTree(SmbSession session, string share, string service) - { - // used by SmbFile.isOpen - this.Session = session; - this.Share = share.ToUpper(); - if (service != null && service.StartsWith("??") == false) - { - this.Service = service; - } - Service0 = this.Service; - ConnectionState = 0; - } - - internal virtual bool Matches(string share, string service) - { - return Runtime.EqualsIgnoreCase(this.Share, share) && (service == null || - service.StartsWith("??") || Runtime.EqualsIgnoreCase(this.Service, service - )); - } - - public override bool Equals(object obj) - { - if (obj is SmbTree) - { - SmbTree tree = (SmbTree)obj; - return Matches(tree.Share, tree.Service); - } - return false; - } - - /// - internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response - ) - { - lock (Session.Transport()) - { - if (response != null) - { - response.Received = false; - } - TreeConnect(request, response); - if (request == null || (response != null && response.Received)) - { - return; - } - if (Service.Equals("A:") == false) - { - switch (request.Command) - { - case ServerMessageBlock.SmbComOpenAndx: - case ServerMessageBlock.SmbComNtCreateAndx: - case ServerMessageBlock.SmbComReadAndx: - case ServerMessageBlock.SmbComWriteAndx: - case ServerMessageBlock.SmbComClose: - case ServerMessageBlock.SmbComTreeDisconnect: - { - break; - } - - case ServerMessageBlock.SmbComTransaction: - case ServerMessageBlock.SmbComTransaction2: - { - switch (((SmbComTransaction)request).SubCommand & unchecked(0xFF)) - { - case SmbComTransaction.NetShareEnum: - case SmbComTransaction.NetServerEnum2: - case SmbComTransaction.NetServerEnum3: - case SmbComTransaction.TransPeekNamedPipe: - case SmbComTransaction.TransWaitNamedPipe: - case SmbComTransaction.TransCallNamedPipe: - case SmbComTransaction.TransTransactNamedPipe: - case SmbComTransaction.Trans2GetDfsReferral: - { - break; - } - - default: - { - throw new SmbException("Invalid operation for " + Service + " service"); - } - } - break; - } - - default: - { - throw new SmbException("Invalid operation for " + Service + " service" + request); - } - } - } - request.Tid = Tid; - if (InDfs && !Service.Equals("IPC") && !string.IsNullOrEmpty(request.Path)) - { - request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs; - request.Path = '\\' + Session.Transport().TconHostName + '\\' + Share + request.Path; - } - try - { - Session.Send(request, response); - } - catch (SmbException se) - { - if (se.GetNtStatus() == NtStatus.NtStatusNetworkNameDeleted) - { - TreeDisconnect(true); - } - throw; - } - } - } - - /// - internal virtual void TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse - ) - { - lock (Session.Transport()) - { - string unc; - while (ConnectionState != 0) - { - if (ConnectionState == 2 || ConnectionState == 3) - { - // connected or disconnecting - return; - } - try - { - Runtime.Wait(Session.transport); - } - catch (Exception ie) - { - throw new SmbException(ie.Message, ie); - } - } - ConnectionState = 1; - // trying ... - try - { - Session.transport.Connect(); - unc = "\\\\" + Session.transport.TconHostName + '\\' + Share; - Service = Service0; - if (Session.transport.Log.Level >= 4) - { - Session.transport.Log.WriteLine("treeConnect: unc=" + unc + ",service=" + Service - ); - } - SmbComTreeConnectAndXResponse response = new SmbComTreeConnectAndXResponse(andxResponse - ); - SmbComTreeConnectAndX request = new SmbComTreeConnectAndX(Session, unc, Service, - andx); - Session.Send(request, response); - Tid = response.Tid; - Service = response.Service; - InDfs = response.ShareIsInDfs; - TreeNum = _treeConnCounter++; - ConnectionState = 2; - } - catch (SmbException se) - { - // connected - TreeDisconnect(true); - ConnectionState = 0; - throw; - } - } - } - - internal virtual void TreeDisconnect(bool inError) - { - lock (Session.Transport()) - { - if (ConnectionState != 2) - { - // not-connected - return; - } - ConnectionState = 3; - // disconnecting - if (!inError && Tid != 0) - { - try - { - Send(new SmbComTreeDisconnect(), null); - } - catch (SmbException se) - { - if (Session.transport.Log.Level > 1) - { - Runtime.PrintStackTrace(se, Session.transport.Log); - } - } - } - InDfs = false; - InDomainDfs = false; - ConnectionState = 0; - Runtime.NotifyAll(Session.transport); - } - } - - public override string ToString() - { - return "SmbTree[share=" + Share + ",service=" + Service + ",tid=" + Tid + ",inDfs=" - + InDfs + ",inDomainDfs=" + InDomainDfs + ",connectionState=" + ConnectionState - + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs deleted file mode 100644 index 2ef874882f..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2.cs +++ /dev/null @@ -1,146 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class Trans2FindFirst2 : SmbComTransaction - { - private const int FlagsCloseAfterThisRequest = unchecked(0x01); - - private const int FlagsCloseIfEndReached = unchecked(0x02); - - private const int FlagsReturnResumeKeys = unchecked(0x04); - - private const int FlagsResumeFromPreviousEnd = unchecked(0x08); - - private const int FlagsFindWithBackupIntent = unchecked(0x10); - - private const int DefaultListSize = 65535; - - private const int DefaultListCount = 200; - - private int _searchAttributes; - - private int _flags; - - private int _informationLevel; - - private int _searchStorageType = 0; - - private string _wildcard; - - internal const int SmbInfoStandard = 1; - - internal const int SmbInfoQueryEaSize = 2; - - internal const int SmbInfoQueryEasFromList = 3; - - internal const int SmbFindFileDirectoryInfo = unchecked(0x101); - - internal const int SmbFindFileFullDirectoryInfo = unchecked(0x102); - - internal const int SmbFileNamesInfo = unchecked(0x103); - - internal const int SmbFileBothDirectoryInfo = unchecked(0x104); - - internal static readonly int ListSize = Config.GetInt("jcifs.smb.client.listSize" - , DefaultListSize); - - internal static readonly int ListCount = Config.GetInt("jcifs.smb.client.listCount" - , DefaultListCount); - - internal Trans2FindFirst2(string filename, string wildcard, int searchAttributes) - { - // flags - // information levels - if (filename.Equals("\\")) - { - Path = filename; - } - else - { - Path = filename + "\\"; - } - this._wildcard = wildcard; - this._searchAttributes = searchAttributes & unchecked(0x37); - Command = SmbComTransaction2; - SubCommand = Trans2FindFirst2; - _flags = unchecked(0x00); - _informationLevel = SmbFileBothDirectoryInfo; - TotalDataCount = 0; - MaxParameterCount = 10; - MaxDataCount = ListSize; - MaxSetupCount = 0; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_searchAttributes, dst, dstIndex); - dstIndex += 2; - WriteInt2(ListCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(_flags, dst, dstIndex); - dstIndex += 2; - WriteInt2(_informationLevel, dst, dstIndex); - dstIndex += 2; - WriteInt4(_searchStorageType, dst, dstIndex); - dstIndex += 4; - dstIndex += WriteString(Path + _wildcard, dst, dstIndex); - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2FindFirst2[" + base.ToString() + ",searchAttributes=0x" - + Hexdump.ToHexString(_searchAttributes, 2) + ",searchCount=" + ListCount + ",flags=0x" - + Hexdump.ToHexString(_flags, 2) + ",informationLevel=0x" + Hexdump.ToHexString( - _informationLevel, 3) + ",searchStorageType=" + _searchStorageType + ",filename=" - + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs deleted file mode 100644 index 71f780ff38..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindFirst2Response.cs +++ /dev/null @@ -1,262 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class Trans2FindFirst2Response : SmbComTransactionResponse - { - internal const int SmbInfoStandard = 1; - - internal const int SmbInfoQueryEaSize = 2; - - internal const int SmbInfoQueryEasFromList = 3; - - internal const int SmbFindFileDirectoryInfo = unchecked(0x101); - - internal const int SmbFindFileFullDirectoryInfo = unchecked(0x102); - - internal const int SmbFileNamesInfo = unchecked(0x103); - - internal const int SmbFileBothDirectoryInfo = unchecked(0x104); - - internal class SmbFindFileBothDirectoryInfo : IFileEntry - { - internal int NextEntryOffset; - - internal int FileIndex; - - internal long CreationTime; - - internal long LastAccessTime; - - internal long LastWriteTime; - - internal long ChangeTime; - - internal long EndOfFile; - - internal long AllocationSize; - - internal int ExtFileAttributes; - - internal int FileNameLength; - - internal int EaSize; - - internal int ShortNameLength; - - internal string ShortName; - - internal string Filename; - - // information levels - public virtual string GetName() - { - return Filename; - } - - public virtual int GetType() - { - return SmbFile.TypeFilesystem; - } - - public virtual int GetAttributes() - { - return ExtFileAttributes; - } - - public virtual long CreateTime() - { - return CreationTime; - } - - public virtual long LastModified() - { - return LastWriteTime; - } - - public virtual long Length() - { - return EndOfFile; - } - - public override string ToString() - { - return "SmbFindFileBothDirectoryInfo[" + "nextEntryOffset=" + NextEntryOffset - + ",fileIndex=" + FileIndex + ",creationTime=" + Extensions.CreateDate - (CreationTime) + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime - ) + ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",changeTime=" - + Extensions.CreateDate(ChangeTime) + ",endOfFile=" + EndOfFile - + ",allocationSize=" + AllocationSize + ",extFileAttributes=" + ExtFileAttributes - + ",fileNameLength=" + FileNameLength + ",eaSize=" + EaSize + ",shortNameLength=" - + ShortNameLength + ",shortName=" + ShortName + ",filename=" + Filename - + "]"; - } - - internal SmbFindFileBothDirectoryInfo(Trans2FindFirst2Response enclosing) - { - this._enclosing = enclosing; - } - - private readonly Trans2FindFirst2Response _enclosing; - } - - internal int Sid; - - internal bool IsEndOfSearch; - - internal int EaErrorOffset; - - internal int LastNameOffset; - - internal int LastNameBufferIndex; - - internal string LastName; - - internal int ResumeKey; - - public Trans2FindFirst2Response() - { - Command = SmbComTransaction2; - SubCommand = Smb.SmbComTransaction.Trans2FindFirst2; - } - - internal virtual string ReadString(byte[] src, int srcIndex, int len) - { - string str = null; - try - { - if (UseUnicode) - { - // should Unicode alignment be corrected for here? - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding); - } - else - { - if (len > 0 && src[srcIndex + len - 1] == '\0') - { - len--; - } - str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding - ); - } - } - catch (UnsupportedEncodingException uee) - { - if (Log.Level > 1) - { - Runtime.PrintStackTrace(uee, Log); - } - } - return str; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - int start = bufferIndex; - if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2) - { - Sid = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - } - NumEntries = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - IsEndOfSearch = (buffer[bufferIndex] & unchecked(0x01)) == unchecked(0x01) ? true : false; - bufferIndex += 2; - EaErrorOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - LastNameOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - return bufferIndex - start; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - SmbFindFileBothDirectoryInfo e; - LastNameBufferIndex = bufferIndex + LastNameOffset; - Results = new SmbFindFileBothDirectoryInfo[NumEntries]; - for (int i = 0; i < NumEntries; i++) - { - Results[i] = e = new SmbFindFileBothDirectoryInfo(this); - e.NextEntryOffset = ReadInt4(buffer, bufferIndex); - e.FileIndex = ReadInt4(buffer, bufferIndex + 4); - e.CreationTime = ReadTime(buffer, bufferIndex + 8); - // e.lastAccessTime = readTime( buffer, bufferIndex + 16 ); - e.LastWriteTime = ReadTime(buffer, bufferIndex + 24); - // e.changeTime = readTime( buffer, bufferIndex + 32 ); - e.EndOfFile = ReadInt8(buffer, bufferIndex + 40); - // e.allocationSize = readInt8( buffer, bufferIndex + 48 ); - e.ExtFileAttributes = ReadInt4(buffer, bufferIndex + 56); - e.FileNameLength = ReadInt4(buffer, bufferIndex + 60); - // e.eaSize = readInt4( buffer, bufferIndex + 64 ); - // e.shortNameLength = buffer[bufferIndex + 68] & 0xFF; - // e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength ); - e.Filename = ReadString(buffer, bufferIndex + 94, e.FileNameLength); - if (LastNameBufferIndex >= bufferIndex && (e.NextEntryOffset == 0 || LastNameBufferIndex - < (bufferIndex + e.NextEntryOffset))) - { - LastName = e.Filename; - ResumeKey = e.FileIndex; - } - bufferIndex += e.NextEntryOffset; - } - //return bufferIndex - start; - return DataCount; - } - - public override string ToString() - { - string c; - if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2) - { - c = "Trans2FindFirst2Response["; - } - else - { - c = "Trans2FindNext2Response["; - } - return c + base.ToString() + ",sid=" + Sid + ",searchCount=" + NumEntries - + ",isEndOfSearch=" + IsEndOfSearch + ",eaErrorOffset=" + EaErrorOffset + ",lastNameOffset=" - + LastNameOffset + ",lastName=" + LastName + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs deleted file mode 100644 index cb860f7993..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2FindNext2.cs +++ /dev/null @@ -1,109 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class Trans2FindNext2 : SmbComTransaction - { - private int _sid; - - private int _informationLevel; - - private int _resumeKey; - - private int _flags; - - private string _filename; - - internal Trans2FindNext2(int sid, int resumeKey, string filename) - { - this._sid = sid; - this._resumeKey = resumeKey; - this._filename = filename; - Command = SmbComTransaction2; - SubCommand = Trans2FindNext2; - _informationLevel = Smb.Trans2FindFirst2.SmbFileBothDirectoryInfo; - _flags = unchecked(0x00); - MaxParameterCount = 8; - MaxDataCount = Smb.Trans2FindFirst2.ListSize; - MaxSetupCount = 0; - } - - internal override void Reset(int resumeKey, string lastName) - { - base.Reset(); - this._resumeKey = resumeKey; - _filename = lastName; - Flags2 = 0; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_sid, dst, dstIndex); - dstIndex += 2; - WriteInt2(Smb.Trans2FindFirst2.ListCount, dst, dstIndex); - dstIndex += 2; - WriteInt2(_informationLevel, dst, dstIndex); - dstIndex += 2; - WriteInt4(_resumeKey, dst, dstIndex); - dstIndex += 4; - WriteInt2(_flags, dst, dstIndex); - dstIndex += 2; - dstIndex += WriteString(_filename, dst, dstIndex); - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2FindNext2[" + base.ToString() + ",sid=" + _sid + ",searchCount=" - + Smb.Trans2FindFirst2.ListSize + ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel - , 3) + ",resumeKey=0x" + Hexdump.ToHexString(_resumeKey, 4) + ",flags=0x" + Hexdump - .ToHexString(_flags, 2) + ",filename=" + _filename + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs deleted file mode 100644 index c83de79737..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferral.cs +++ /dev/null @@ -1,78 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class Trans2GetDfsReferral : SmbComTransaction - { - private int _maxReferralLevel = 3; - - internal Trans2GetDfsReferral(string filename) - { - Path = filename; - Command = SmbComTransaction2; - SubCommand = Trans2GetDfsReferral; - TotalDataCount = 0; - MaxParameterCount = 0; - MaxDataCount = 4096; - MaxSetupCount = unchecked(unchecked(0x00)); - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_maxReferralLevel, dst, dstIndex); - dstIndex += 2; - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2GetDfsReferral[" + base.ToString() + ",maxReferralLevel=0x" - + _maxReferralLevel + ",filename=" + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs deleted file mode 100644 index 5fa4a795da..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2GetDfsReferralResponse.cs +++ /dev/null @@ -1,179 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class Trans2GetDfsReferralResponse : SmbComTransactionResponse - { - internal class Referral - { - private int _version; - - private int _size; - - private int _serverType; - - private int _flags; - - private int _proximity; - - private int _pathOffset; - - private int _altPathOffset; - - private int _nodeOffset; - - private string _altPath; - - internal int Ttl; - - internal string Path; - - internal string Node; - - internal virtual int ReadWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - _version = ReadInt2(buffer, bufferIndex); - if (_version != 3 && _version != 1) - { - throw new RuntimeException("Version " + _version + " referral not supported. Please report this to jcifs at samba dot org." - ); - } - bufferIndex += 2; - _size = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _serverType = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _flags = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if (_version == 3) - { - _proximity = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Ttl = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _pathOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _altPathOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _nodeOffset = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - Path = _enclosing.ReadString(buffer, start + _pathOffset, len, (_enclosing.Flags2 & SmbConstants.Flags2Unicode) != 0); - if (_nodeOffset > 0) - { - Node = _enclosing.ReadString(buffer, start + _nodeOffset, len, (_enclosing.Flags2 & SmbConstants.Flags2Unicode) != 0); - } - } - else - { - if (_version == 1) - { - Node = _enclosing.ReadString(buffer, bufferIndex, len, (_enclosing - .Flags2 & SmbConstants.Flags2Unicode) != 0); - } - } - return _size; - } - - public override string ToString() - { - return "Referral[" + "version=" + _version + ",size=" + _size - + ",serverType=" + _serverType + ",flags=" + _flags + ",proximity=" + _proximity + ",ttl=" + Ttl + ",pathOffset=" + _pathOffset + ",altPathOffset=" - + _altPathOffset + ",nodeOffset=" + _nodeOffset + ",path=" + Path - + ",altPath=" + _altPath + ",node=" + Node + "]"; - } - - internal Referral(Trans2GetDfsReferralResponse enclosing) - { - this._enclosing = enclosing; - } - - private readonly Trans2GetDfsReferralResponse _enclosing; - } - - internal int PathConsumed; - - internal int NumReferrals; - - internal int flags; - - internal Referral[] Referrals; - - public Trans2GetDfsReferralResponse() - { - SubCommand = Smb.SmbComTransaction.Trans2GetDfsReferral; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - int start = bufferIndex; - PathConsumed = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - if ((Flags2 & SmbConstants.Flags2Unicode) != 0) - { - PathConsumed /= 2; - } - NumReferrals = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - flags = ReadInt2(buffer, bufferIndex); - bufferIndex += 4; - Referrals = new Referral[NumReferrals]; - for (int ri = 0; ri < NumReferrals; ri++) - { - Referrals[ri] = new Referral(this); - bufferIndex += Referrals[ri].ReadWireFormat(buffer, bufferIndex, len); - } - return bufferIndex - start; - } - - public override string ToString() - { - return "Trans2GetDfsReferralResponse[" + base.ToString() + ",pathConsumed=" - + PathConsumed + ",numReferrals=" + NumReferrals + ",flags=" + flags + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs deleted file mode 100644 index 27b350e535..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformation.cs +++ /dev/null @@ -1,80 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class Trans2QueryFsInformation : SmbComTransaction - { - private int _informationLevel; - - internal Trans2QueryFsInformation(int informationLevel) - { - Command = SmbComTransaction2; - SubCommand = Trans2QueryFsInformation; - this._informationLevel = informationLevel; - TotalParameterCount = 2; - TotalDataCount = 0; - MaxParameterCount = 0; - MaxDataCount = 800; - MaxSetupCount = 0; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_informationLevel, dst, dstIndex); - dstIndex += 2; - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2QueryFSInformation[" + base.ToString() + ",informationLevel=0x" - + Hexdump.ToHexString(_informationLevel, 3) + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs deleted file mode 100644 index 2253e7b6fc..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryFSInformationResponse.cs +++ /dev/null @@ -1,192 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class Trans2QueryFsInformationResponse : SmbComTransactionResponse - { - internal const int SMB_INFO_ALLOCATION = 1; - - internal const int SmbQueryFsSizeInfo = unchecked(0x103); - - internal const int SmbFsFullSizeInformation = 1007; - - internal class SmbInfoAllocation : IAllocInfo - { - internal long Alloc; - - internal long Free; - - internal int SectPerAlloc; - - internal int BytesPerSect; - - // information levels - // Also handles SmbQueryFSSizeInfo - public virtual long GetCapacity() - { - return Alloc * SectPerAlloc * BytesPerSect; - } - - public virtual long GetFree() - { - return Free * SectPerAlloc * BytesPerSect; - } - - public override string ToString() - { - return "SmbInfoAllocation[" + "alloc=" + Alloc + ",free=" + Free + ",sectPerAlloc=" + SectPerAlloc + ",bytesPerSect=" + BytesPerSect - + "]"; - } - - internal SmbInfoAllocation(Trans2QueryFsInformationResponse enclosing) - { - this._enclosing = enclosing; - } - - private readonly Trans2QueryFsInformationResponse _enclosing; - } - - private int _informationLevel; - - internal IAllocInfo Info; - - internal Trans2QueryFsInformationResponse(int informationLevel) - { - this._informationLevel = informationLevel; - Command = SmbComTransaction2; - SubCommand = Smb.SmbComTransaction.Trans2QueryFsInformation; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - switch (_informationLevel) - { - case SMB_INFO_ALLOCATION: - { - return ReadSmbInfoAllocationWireFormat(buffer, bufferIndex); - } - - case SmbQueryFsSizeInfo: - { - return ReadSmbQueryFsSizeInfoWireFormat(buffer, bufferIndex); - } - - case SmbFsFullSizeInformation: - { - return ReadFsFullSizeInformationWireFormat(buffer, bufferIndex); - } - - default: - { - return 0; - } - } - } - - internal virtual int ReadSmbInfoAllocationWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - SmbInfoAllocation info = new SmbInfoAllocation - (this); - bufferIndex += 4; - // skip idFileSystem - info.SectPerAlloc = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.Alloc = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.Free = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.BytesPerSect = ReadInt2(buffer, bufferIndex); - bufferIndex += 4; - this.Info = info; - return bufferIndex - start; - } - - internal virtual int ReadSmbQueryFsSizeInfoWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - SmbInfoAllocation info = new SmbInfoAllocation - (this); - info.Alloc = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - info.Free = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - info.SectPerAlloc = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.BytesPerSect = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - this.Info = info; - return bufferIndex - start; - } - - internal virtual int ReadFsFullSizeInformationWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - SmbInfoAllocation info = new SmbInfoAllocation - (this); - // Read total allocation units. - info.Alloc = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - // read caller available allocation units - info.Free = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - // skip actual free units - bufferIndex += 8; - info.SectPerAlloc = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.BytesPerSect = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - this.Info = info; - return bufferIndex - start; - } - - public override string ToString() - { - return "Trans2QueryFSInformationResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs deleted file mode 100644 index b3db64790d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformation.cs +++ /dev/null @@ -1,85 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; - -namespace SharpCifs.Smb -{ - internal class Trans2QueryPathInformation : SmbComTransaction - { - private int _informationLevel; - - internal Trans2QueryPathInformation(string filename, int informationLevel) - { - Path = filename; - this._informationLevel = informationLevel; - Command = SmbComTransaction2; - SubCommand = Trans2QueryPathInformation; - TotalDataCount = 0; - MaxParameterCount = 2; - MaxDataCount = 40; - MaxSetupCount = unchecked(unchecked(0x00)); - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_informationLevel, dst, dstIndex); - dstIndex += 2; - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - dstIndex += WriteString(Path, dst, dstIndex); - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2QueryPathInformation[" + base.ToString() + ",informationLevel=0x" - + Hexdump.ToHexString(_informationLevel, 3) + ",filename=" + Path + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs deleted file mode 100644 index 50650df627..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2QueryPathInformationResponse.cs +++ /dev/null @@ -1,227 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class Trans2QueryPathInformationResponse : SmbComTransactionResponse - { - internal const int SMB_QUERY_FILE_BASIC_INFO = unchecked(0x101); - - internal const int SMB_QUERY_FILE_STANDARD_INFO = unchecked(0x102); - - internal class SmbQueryFileBasicInfo : IInfo - { - internal long CreateTime; - - internal long LastAccessTime; - - internal long LastWriteTime; - - internal long ChangeTime; - - internal int Attributes; - - // information levels - public virtual int GetAttributes() - { - return Attributes; - } - - public virtual long GetCreateTime() - { - return CreateTime; - } - - public virtual long GetLastWriteTime() - { - return LastWriteTime; - } - - public virtual long GetSize() - { - return 0L; - } - - public override string ToString() - { - return "SmbQueryFileBasicInfo[" + "createTime=" + Extensions.CreateDate - (CreateTime) + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime - ) + ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",changeTime=" - + Extensions.CreateDate(ChangeTime) + ",attributes=0x" + Hexdump.ToHexString - (Attributes, 4) + "]"; - } - - internal SmbQueryFileBasicInfo(Trans2QueryPathInformationResponse enclosing) - { - this._enclosing = enclosing; - } - - private readonly Trans2QueryPathInformationResponse _enclosing; - } - - internal class SmbQueryFileStandardInfo : IInfo - { - internal long AllocationSize; - - internal long EndOfFile; - - internal int NumberOfLinks; - - internal bool DeletePending; - - internal bool Directory; - - public virtual int GetAttributes() - { - return 0; - } - - public virtual long GetCreateTime() - { - return 0L; - } - - public virtual long GetLastWriteTime() - { - return 0L; - } - - public virtual long GetSize() - { - return EndOfFile; - } - - public override string ToString() - { - return "SmbQueryInfoStandard[" + "allocationSize=" + AllocationSize - + ",endOfFile=" + EndOfFile + ",numberOfLinks=" + NumberOfLinks + ",deletePending=" - + DeletePending + ",directory=" + Directory + "]"; - } - - internal SmbQueryFileStandardInfo(Trans2QueryPathInformationResponse enclosing) - { - this._enclosing = enclosing; - } - - private readonly Trans2QueryPathInformationResponse _enclosing; - } - - private int _informationLevel; - - internal IInfo Info; - - internal Trans2QueryPathInformationResponse(int informationLevel) - { - this._informationLevel = informationLevel; - SubCommand = Smb.SmbComTransaction.Trans2QueryPathInformation; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - // observed two zero bytes here with at least win98 - return 2; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - switch (_informationLevel) - { - case SMB_QUERY_FILE_BASIC_INFO: - { - return ReadSmbQueryFileBasicInfoWireFormat(buffer, bufferIndex); - } - - case SMB_QUERY_FILE_STANDARD_INFO: - { - return ReadSmbQueryFileStandardInfoWireFormat(buffer, bufferIndex); - } - - default: - { - return 0; - } - } - } - - internal virtual int ReadSmbQueryFileStandardInfoWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - SmbQueryFileStandardInfo info = new SmbQueryFileStandardInfo - (this); - info.AllocationSize = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - info.EndOfFile = ReadInt8(buffer, bufferIndex); - bufferIndex += 8; - info.NumberOfLinks = ReadInt4(buffer, bufferIndex); - bufferIndex += 4; - info.DeletePending = (buffer[bufferIndex++] & unchecked(0xFF)) > 0; - info.Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0; - this.Info = info; - return bufferIndex - start; - } - - internal virtual int ReadSmbQueryFileBasicInfoWireFormat(byte[] buffer, int bufferIndex - ) - { - int start = bufferIndex; - SmbQueryFileBasicInfo info = new SmbQueryFileBasicInfo - (this); - info.CreateTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - info.LastAccessTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - info.LastWriteTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - info.ChangeTime = ReadTime(buffer, bufferIndex); - bufferIndex += 8; - info.Attributes = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - this.Info = info; - return bufferIndex - start; - } - - public override string ToString() - { - return "Trans2QueryPathInformationResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs deleted file mode 100644 index 289cab866b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformation.cs +++ /dev/null @@ -1,105 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class Trans2SetFileInformation : SmbComTransaction - { - internal const int SmbFileBasicInfo = unchecked(0x101); - - private int _fid; - - private int _attributes; - - private long _createTime; - - private long _lastWriteTime; - - internal Trans2SetFileInformation(int fid, int attributes, long createTime, long - lastWriteTime) - { - this._fid = fid; - this._attributes = attributes; - this._createTime = createTime; - this._lastWriteTime = lastWriteTime; - Command = SmbComTransaction2; - SubCommand = Trans2SetFileInformation; - MaxParameterCount = 6; - MaxDataCount = 0; - MaxSetupCount = unchecked(unchecked(0x00)); - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 2; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteInt2(_fid, dst, dstIndex); - dstIndex += 2; - WriteInt2(SmbFileBasicInfo, dst, dstIndex); - dstIndex += 2; - WriteInt2(0, dst, dstIndex); - dstIndex += 2; - return dstIndex - start; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - int start = dstIndex; - WriteTime(_createTime, dst, dstIndex); - dstIndex += 8; - WriteInt8(0L, dst, dstIndex); - dstIndex += 8; - WriteTime(_lastWriteTime, dst, dstIndex); - dstIndex += 8; - WriteInt8(0L, dst, dstIndex); - dstIndex += 8; - WriteInt2(unchecked(0x80) | _attributes, dst, dstIndex); - dstIndex += 2; - WriteInt8(0L, dst, dstIndex); - dstIndex += 6; - return dstIndex - start; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2SetFileInformation[" + base.ToString() + ",fid=" + _fid + - "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs deleted file mode 100644 index b21f356b49..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/Trans2SetFileInformationResponse.cs +++ /dev/null @@ -1,63 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class Trans2SetFileInformationResponse : SmbComTransactionResponse - { - public Trans2SetFileInformationResponse() - { - SubCommand = Smb.SmbComTransaction.Trans2SetFileInformation; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "Trans2SetFileInformationResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs deleted file mode 100644 index 404af0aaad..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipe.cs +++ /dev/null @@ -1,97 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal class TransCallNamedPipe : SmbComTransaction - { - private byte[] _pipeData; - - private int _pipeDataOff; - - private int _pipeDataLen; - - internal TransCallNamedPipe(string pipeName, byte[] data, int off, int len) - { - Name = pipeName; - _pipeData = data; - _pipeDataOff = off; - _pipeDataLen = len; - Command = SmbComTransaction; - SubCommand = TransCallNamedPipe; - Timeout = unchecked((int)(0xFFFFFFFF)); - MaxParameterCount = 0; - MaxDataCount = unchecked(0xFFFF); - MaxSetupCount = unchecked(unchecked(0x00)); - SetupCount = 2; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // this says "Transaction priority" in netmon - dst[dstIndex++] = unchecked(unchecked(0x00)); - // no FID - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 4; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - if ((dst.Length - dstIndex) < _pipeDataLen) - { - if (Log.Level >= 3) - { - Log.WriteLine("TransCallNamedPipe data too long for buffer"); - } - return 0; - } - Array.Copy(_pipeData, _pipeDataOff, dst, dstIndex, _pipeDataLen); - return _pipeDataLen; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransCallNamedPipe[" + base.ToString() + ",pipeName=" + Name + - "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs deleted file mode 100644 index b86cc7fdb3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransCallNamedPipeResponse.cs +++ /dev/null @@ -1,77 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class TransCallNamedPipeResponse : SmbComTransactionResponse - { - private SmbNamedPipe _pipe; - - internal TransCallNamedPipeResponse(SmbNamedPipe pipe) - { - this._pipe = pipe; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - if (_pipe.PipeIn != null) - { - TransactNamedPipeInputStream @in = (TransactNamedPipeInputStream)_pipe.PipeIn; - lock (@in.Lock) - { - @in.Receive(buffer, bufferIndex, len); - Runtime.Notify(@in.Lock); - } - } - return len; - } - - public override string ToString() - { - return "TransCallNamedPipeResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs deleted file mode 100644 index 9b80bbe1e2..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipe.cs +++ /dev/null @@ -1,78 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class TransPeekNamedPipe : SmbComTransaction - { - private int _fid; - - internal TransPeekNamedPipe(string pipeName, int fid) - { - Name = pipeName; - this._fid = fid; - Command = SmbComTransaction; - SubCommand = TransPeekNamedPipe; - Timeout = unchecked((int)(0xFFFFFFFF)); - MaxParameterCount = 6; - MaxDataCount = 1; - MaxSetupCount = unchecked(unchecked(0x00)); - SetupCount = 2; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - // this says "Transaction priority" in netmon - WriteInt2(_fid, dst, dstIndex); - return 4; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransPeekNamedPipe[" + base.ToString() + ",pipeName=" + Name + - "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs deleted file mode 100644 index 6bcf2d07e3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransPeekNamedPipeResponse.cs +++ /dev/null @@ -1,84 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class TransPeekNamedPipeResponse : SmbComTransactionResponse - { - private SmbNamedPipe _pipe; - - private int _head; - - internal const int StatusDisconnected = 1; - - internal const int StatusListening = 2; - - internal const int StatusConnectionOk = 3; - - internal const int StatusServerEndClosed = 4; - - internal int status; - - internal int Available; - - internal TransPeekNamedPipeResponse(SmbNamedPipe pipe) - { - this._pipe = pipe; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - Available = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - _head = ReadInt2(buffer, bufferIndex); - bufferIndex += 2; - status = ReadInt2(buffer, bufferIndex); - return 6; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransPeekNamedPipeResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs deleted file mode 100644 index 1b6ec9cca5..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipe.cs +++ /dev/null @@ -1,97 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Smb -{ - internal class TransTransactNamedPipe : SmbComTransaction - { - private byte[] _pipeData; - - private int _pipeFid; - - private int _pipeDataOff; - - private int _pipeDataLen; - - internal TransTransactNamedPipe(int fid, byte[] data, int off, int len) - { - _pipeFid = fid; - _pipeData = data; - _pipeDataOff = off; - _pipeDataLen = len; - Command = SmbComTransaction; - SubCommand = TransTransactNamedPipe; - MaxParameterCount = 0; - MaxDataCount = unchecked(0xFFFF); - MaxSetupCount = unchecked(unchecked(0x00)); - SetupCount = 2; - Name = "\\PIPE\\"; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - WriteInt2(_pipeFid, dst, dstIndex); - dstIndex += 2; - return 4; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - if ((dst.Length - dstIndex) < _pipeDataLen) - { - if (Log.Level >= 3) - { - Log.WriteLine("TransTransactNamedPipe data too long for buffer"); - } - return 0; - } - Array.Copy(_pipeData, _pipeDataOff, dst, dstIndex, _pipeDataLen); - return _pipeDataLen; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransTransactNamedPipe[" + base.ToString() + ",pipeFid=" + _pipeFid - + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs deleted file mode 100644 index b8d14781c8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransTransactNamedPipeResponse.cs +++ /dev/null @@ -1,77 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class TransTransactNamedPipeResponse : SmbComTransactionResponse - { - private SmbNamedPipe _pipe; - - internal TransTransactNamedPipeResponse(SmbNamedPipe pipe) - { - this._pipe = pipe; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - if (_pipe.PipeIn != null) - { - TransactNamedPipeInputStream @in = (TransactNamedPipeInputStream)_pipe.PipeIn; - lock (@in.Lock) - { - @in.Receive(buffer, bufferIndex, len); - Runtime.Notify(@in.Lock); - } - } - return len; - } - - public override string ToString() - { - return "TransTransactNamedPipeResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs deleted file mode 100644 index a184665aa1..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipe.cs +++ /dev/null @@ -1,76 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class TransWaitNamedPipe : SmbComTransaction - { - internal TransWaitNamedPipe(string pipeName) - { - Name = pipeName; - Command = SmbComTransaction; - SubCommand = TransWaitNamedPipe; - Timeout = unchecked((int)(0xFFFFFFFF)); - MaxParameterCount = 0; - MaxDataCount = 0; - MaxSetupCount = unchecked(unchecked(0x00)); - SetupCount = 2; - } - - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - dst[dstIndex++] = SubCommand; - dst[dstIndex++] = unchecked(unchecked(0x00)); - dst[dstIndex++] = unchecked(unchecked(0x00)); - // no FID - dst[dstIndex++] = unchecked(unchecked(0x00)); - return 4; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransWaitNamedPipe[" + base.ToString() + ",pipeName=" + Name + - "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs deleted file mode 100644 index a62a82ec7a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransWaitNamedPipeResponse.cs +++ /dev/null @@ -1,59 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class TransWaitNamedPipeResponse : SmbComTransactionResponse - { - // not much to this one is there :~) - internal override int WriteSetupWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteParametersWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int WriteDataWireFormat(byte[] dst, int dstIndex) - { - return 0; - } - - internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len - ) - { - return 0; - } - - internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int - len) - { - return 0; - } - - internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len) - { - return 0; - } - - public override string ToString() - { - return "TransWaitNamedPipeResponse[" + base.ToString() + "]"; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs deleted file mode 100644 index 46d4185829..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeInputStream.cs +++ /dev/null @@ -1,180 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Smb -{ - internal class TransactNamedPipeInputStream : SmbFileInputStream - { - private const int InitPipeSize = 4096; - - private byte[] _pipeBuf = new byte[InitPipeSize]; - - private int _begIdx; - - private int _nxtIdx; - - private int _used; - - private bool _dcePipe; - - internal object Lock; - - /// - /// - /// - internal TransactNamedPipeInputStream(SmbNamedPipe pipe) : base(pipe, (pipe.PipeType - & unchecked((int)(0xFFFF00FF))) | SmbFile.OExcl) - { - _dcePipe = (pipe.PipeType & SmbNamedPipe.PipeTypeDceTransact) != SmbNamedPipe - .PipeTypeDceTransact; - Lock = new object(); - } - - /// - public override int Read() - { - int result = -1; - lock (Lock) - { - try - { - while (_used == 0) - { - Runtime.Wait(Lock); - } - } - catch (Exception ie) - { - throw new IOException(ie.Message); - } - result = _pipeBuf[_begIdx] & unchecked(0xFF); - _begIdx = (_begIdx + 1) % _pipeBuf.Length; - } - return result; - } - - /// - public override int Read(byte[] b) - { - return Read(b, 0, b.Length); - } - - /// - public override int Read(byte[] b, int off, int len) - { - int result = -1; - int i; - if (len <= 0) - { - return 0; - } - lock (Lock) - { - try - { - while (_used == 0) - { - Runtime.Wait(Lock); - } - } - catch (Exception ie) - { - throw new IOException(ie.Message); - } - i = _pipeBuf.Length - _begIdx; - result = len > _used ? _used : len; - if (_used > i && result > i) - { - Array.Copy(_pipeBuf, _begIdx, b, off, i); - off += i; - Array.Copy(_pipeBuf, 0, b, off, result - i); - } - else - { - Array.Copy(_pipeBuf, _begIdx, b, off, result); - } - _used -= result; - _begIdx = (_begIdx + result) % _pipeBuf.Length; - } - return result; - } - - /// - public override int Available() - { - if (File.Log.Level >= 3) - { - File.Log.WriteLine("Named Pipe available() does not apply to TRANSACT Named Pipes" - ); - } - return 0; - } - - internal virtual int Receive(byte[] b, int off, int len) - { - int i; - if (len > (_pipeBuf.Length - _used)) - { - byte[] tmp; - int newSize; - newSize = _pipeBuf.Length * 2; - if (len > (newSize - _used)) - { - newSize = len + _used; - } - tmp = _pipeBuf; - _pipeBuf = new byte[newSize]; - i = tmp.Length - _begIdx; - if (_used > i) - { - Array.Copy(tmp, _begIdx, _pipeBuf, 0, i); - Array.Copy(tmp, 0, _pipeBuf, i, _used - i); - } - else - { - Array.Copy(tmp, _begIdx, _pipeBuf, 0, _used); - } - _begIdx = 0; - _nxtIdx = _used; - tmp = null; - } - i = _pipeBuf.Length - _nxtIdx; - if (len > i) - { - Array.Copy(b, off, _pipeBuf, _nxtIdx, i); - off += i; - Array.Copy(b, off, _pipeBuf, 0, len - i); - } - else - { - Array.Copy(b, off, _pipeBuf, _nxtIdx, len); - } - _nxtIdx = (_nxtIdx + len) % _pipeBuf.Length; - _used += len; - return len; - } - - /// - public virtual int Dce_read(byte[] b, int off, int len) - { - return base.Read(b, off, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs deleted file mode 100644 index d3e8d3e1ad..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/TransactNamedPipeOutputStream.cs +++ /dev/null @@ -1,86 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - internal class TransactNamedPipeOutputStream : SmbFileOutputStream - { - private string _path; - - private SmbNamedPipe _pipe; - - private byte[] _tmp = new byte[1]; - - private bool _dcePipe; - - /// - internal TransactNamedPipeOutputStream(SmbNamedPipe pipe) : base(pipe, false, (pipe - .PipeType & unchecked((int)(0xFFFF00FF))) | SmbFile.OExcl) - { - this._pipe = pipe; - _dcePipe = (pipe.PipeType & SmbNamedPipe.PipeTypeDceTransact) == SmbNamedPipe - .PipeTypeDceTransact; - _path = pipe.Unc; - } - - /// - public override void Close() - { - _pipe.Close(); - } - - /// - public override void Write(int b) - { - _tmp[0] = unchecked((byte)b); - Write(_tmp, 0, 1); - } - - /// - public override void Write(byte[] b) - { - Write(b, 0, b.Length); - } - - /// - public override void Write(byte[] b, int off, int len) - { - if (len < 0) - { - len = 0; - } - if ((_pipe.PipeType & SmbNamedPipe.PipeTypeCall) == SmbNamedPipe.PipeTypeCall) - { - _pipe.Send(new TransWaitNamedPipe(_path), new TransWaitNamedPipeResponse()); - _pipe.Send(new TransCallNamedPipe(_path, b, off, len), new TransCallNamedPipeResponse - (_pipe)); - } - else - { - if ((_pipe.PipeType & SmbNamedPipe.PipeTypeTransact) == SmbNamedPipe.PipeTypeTransact) - { - EnsureOpen(); - TransTransactNamedPipe req = new TransTransactNamedPipe(_pipe.Fid, b, off, len); - if (_dcePipe) - { - req.MaxDataCount = 1024; - } - _pipe.Send(req, new TransTransactNamedPipeResponse(_pipe)); - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs b/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs deleted file mode 100644 index daecc54072..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Smb/WinError.cs +++ /dev/null @@ -1,49 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Smb -{ - public static class WinError - { - public static int ErrorSuccess = 0; - - public static int ErrorAccessDenied = 5; - - public static int ErrorReqNotAccep = 71; - - public static int ErrorBadPipe = 230; - - public static int ErrorPipeBusy = 231; - - public static int ErrorNoData = 232; - - public static int ErrorPipeNotConnected = 233; - - public static int ErrorMoreData = 234; - - public static int ErrorNoBrowserServersFound = 6118; - - public static int[] WinerrCodes = { ErrorSuccess, ErrorAccessDenied, - ErrorReqNotAccep, ErrorBadPipe, ErrorPipeBusy, ErrorNoData, ErrorPipeNotConnected - , ErrorMoreData, ErrorNoBrowserServersFound }; - - public static string[] WinerrMessages = { "The operation completed successfully." - , "Access is denied.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept." - , "The pipe state is invalid.", "All pipe instances are busy.", "The pipe is being closed." - , "No process is on the other end of the pipe.", "More data is available.", "The list of servers for this workgroup is not currently available." - }; - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs b/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs deleted file mode 100644 index 816fbe7810..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/UniAddress.cs +++ /dev/null @@ -1,591 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using System.Linq; -using System.Net; -using SharpCifs.Netbios; -using SharpCifs.Util; -using SharpCifs.Util.Sharpen; -using Extensions = SharpCifs.Util.Sharpen.Extensions; - -namespace SharpCifs -{ - /// - ///

Under normal conditions it is not necessary to use - /// this class to use jCIFS properly. - ///

- /// - ///

Under normal conditions it is not necessary to use - /// this class to use jCIFS properly. Name resolusion is - /// handled internally to the jcifs.smb package. - ///

- /// This class is a wrapper for both - /// Jcifs.Netbios.NbtAddress - /// and - /// System.Net.IPAddress - /// . The name resolution mechanisms - /// used will systematically query all available configured resolution - /// services including WINS, broadcasts, DNS, and LMHOSTS. See - /// Setting Name Resolution Properties - /// and the jcifs.resolveOrder property. Changing - /// jCIFS name resolution properties can greatly affect the behavior of - /// the client and may be necessary for proper operation. - ///

- /// This class should be used in favor of InetAddress to resolve - /// hostnames on LANs and WANs that support a mixture of NetBIOS/WINS and - /// DNS resolvable hosts. - /// - public class UniAddress - { - private const int ResolverWins = 0; - - private const int ResolverBcast = 1; - - private const int ResolverDns = 2; - - private const int ResolverLmhosts = 3; - - private static int[] _resolveOrder; - - private static IPAddress _baddr; - - private static LogStream _log = LogStream.GetInstance(); - - static UniAddress() - { - string ro = Config.GetProperty("jcifs.resolveOrder"); - IPAddress nbns = NbtAddress.GetWinsAddress(); - try - { - _baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName - ("255.255.255.255")); - } - catch (UnknownHostException) - { - } - if (string.IsNullOrEmpty(ro)) - { - if (nbns == null) - { - _resolveOrder = new int[3]; - _resolveOrder[0] = ResolverLmhosts; - _resolveOrder[1] = ResolverDns; - _resolveOrder[2] = ResolverBcast; - } - else - { - _resolveOrder = new int[4]; - _resolveOrder[0] = ResolverLmhosts; - _resolveOrder[1] = ResolverWins; - _resolveOrder[2] = ResolverDns; - _resolveOrder[3] = ResolverBcast; - } - } - else - { - int[] tmp = new int[4]; - StringTokenizer st = new StringTokenizer(ro, ","); - int i = 0; - while (st.HasMoreTokens()) - { - string s = st.NextToken().Trim(); - if (Runtime.EqualsIgnoreCase(s, "LMHOSTS")) - { - tmp[i++] = ResolverLmhosts; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "WINS")) - { - if (nbns == null) - { - if (_log.Level > 1) - { - _log.WriteLine("UniAddress resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set" - ); - } - continue; - } - tmp[i++] = ResolverWins; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "BCAST")) - { - tmp[i++] = ResolverBcast; - } - else - { - if (Runtime.EqualsIgnoreCase(s, "DNS")) - { - tmp[i++] = ResolverDns; - } - else - { - if (_log.Level > 1) - { - _log.WriteLine("unknown resolver method: " + s); - } - } - } - } - } - } - _resolveOrder = new int[i]; - Array.Copy(tmp, 0, _resolveOrder, 0, i); - } - } - - internal class Sem - { - internal Sem(int count) - { - this.Count = count; - } - - internal int Count; - } - - internal class QueryThread : Thread - { - internal Sem Sem; - - internal string Host; - - internal string Scope; - - internal int Type; - - internal NbtAddress[] Ans; - - internal IPAddress Svr; - - internal UnknownHostException Uhe; - - internal QueryThread(Sem sem, string host, int type, string scope, IPAddress - svr) : base("JCIFS-QueryThread: " + host) - { - this.Sem = sem; - this.Host = host; - this.Type = type; - this.Scope = scope; - this.Svr = svr; - } - - public override void Run() - { - try - { - //Ans = new [] { NbtAddress.GetByName(Host, Type, Scope, Svr) }; - Ans = NbtAddress.GetAllByName(Host, Type, Scope, Svr); - } - catch (UnknownHostException uhe) - { - this.Uhe = uhe; - } - catch (Exception ex) - { - Uhe = new UnknownHostException(ex.Message); - } - finally - { - lock (Sem) - { - Sem.Count--; - Runtime.Notify(Sem); - } - } - } - } - - /// - internal static NbtAddress[] LookupServerOrWorkgroup(string name, IPAddress svr) - { - Sem sem = new Sem(2); - int type = NbtAddress.IsWins(svr) ? unchecked(0x1b) : unchecked(0x1d); - QueryThread q1X = new QueryThread(sem, name, type, null, svr - ); - QueryThread q20 = new QueryThread(sem, name, unchecked(0x20), null, svr); - q1X.SetDaemon(true); - q20.SetDaemon(true); - try - { - lock (sem) - { - q1X.Start(); - q20.Start(); - while (sem.Count > 0 && q1X.Ans == null && q20.Ans == null) - { - Runtime.Wait(sem); - } - } - } - catch (Exception) - { - throw new UnknownHostException(name); - } - if (q1X.Ans != null) - { - return q1X.Ans; - } - if (q20.Ans != null) - { - return q20.Ans; - } - throw q1X.Uhe; - } - - ///

Determines the address of a host given it's host name. - /// - /// Determines the address of a host given it's host name. The name can be a - /// machine name like "jcifs.samba.org", or an IP address like "192.168.1.15". - /// - /// NetBIOS or DNS hostname to resolve - /// if there is an error resolving the name - /// - public static UniAddress GetByName(string hostname) - { - return GetByName(hostname, false); - } - - internal static bool IsDotQuadIp(string hostname) - { - if (char.IsDigit(hostname[0])) - { - int i; - int len; - int dots; - char[] data; - i = dots = 0; - len = hostname.Length; - data = hostname.ToCharArray(); - while (i < len && char.IsDigit(data[i++])) - { - if (i == len && dots == 3) - { - // probably an IP address - return true; - } - if (i < len && data[i] == '.') - { - dots++; - i++; - } - } - } - return false; - } - - internal static bool IsAllDigits(string hostname) - { - for (int i = 0; i < hostname.Length; i++) - { - if (char.IsDigit(hostname[i]) == false) - { - return false; - } - } - return true; - } - - /// Lookup hostname and return it's UniAddress. - /// - /// Lookup hostname and return it's UniAddress. If the - /// possibleNTDomainOrWorkgroup parameter is true an - /// addtional name query will be performed to locate a master browser. - /// - /// - public static UniAddress GetByName(string hostname, bool possibleNtDomainOrWorkgroup - ) - { - UniAddress[] addrs = GetAllByName(hostname, possibleNtDomainOrWorkgroup - ); - return addrs[0]; - } - - /// - public static UniAddress[] GetAllByName(string hostname, bool possibleNtDomainOrWorkgroup - ) - { - object addr; - int i; - if (string.IsNullOrEmpty(hostname)) - { - throw new UnknownHostException(); - } - if (IsDotQuadIp(hostname)) - { - UniAddress[] addrs = new UniAddress[1]; - addrs[0] = new UniAddress(NbtAddress.GetByName(hostname)); - return addrs; - } - for (i = 0; i < _resolveOrder.Length; i++) - { - try - { - switch (_resolveOrder[i]) - { - case ResolverLmhosts: - { - if ((addr = Lmhosts.GetByName(hostname)) == null) - { - continue; - } - break; - } - - case ResolverWins: - { - if (hostname == NbtAddress.MasterBrowserName || hostname.Length > 15) - { - // invalid netbios name - continue; - } - if (possibleNtDomainOrWorkgroup) - { - addr = LookupServerOrWorkgroup(hostname, NbtAddress.GetWinsAddress()); - } - else - { - addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, NbtAddress.GetWinsAddress - ()); - } - break; - } - - case ResolverBcast: - { - if (hostname.Length > 15) - { - // invalid netbios name - continue; - } - - try - { - if (possibleNtDomainOrWorkgroup) - { - NbtAddress[] iaddrs = LookupServerOrWorkgroup(hostname, _baddr); - - UniAddress[] addrs = new UniAddress[iaddrs.Length]; - for (int ii = 0; ii < iaddrs.Length; ii++) - { - addrs[ii] = new UniAddress(iaddrs[ii]); - } - return addrs; - - } - else - { - addr = NbtAddress.GetByName(hostname, unchecked(0x20), null, _baddr); - } - - } - catch (Exception ex) - { - if (i == _resolveOrder.Length - 1) - { - throw ex; - } - else - { - continue; - } - } - break; - } - - case ResolverDns: - { - if (IsAllDigits(hostname)) - { - throw new UnknownHostException(hostname); - } - - IPAddress[] iaddrs = Extensions.GetAddressesByName(hostname); - - if (iaddrs == null || iaddrs.Length == 0) - { - continue; - } - - return iaddrs.Select(iaddr => new UniAddress(iaddr)).ToArray(); - } - - default: - { - // Success - throw new UnknownHostException(hostname); - } - } - UniAddress[] addrs1 = new UniAddress[1]; - addrs1[0] = new UniAddress(addr); - return addrs1; - } - catch (IOException) - { - } - } - // Success - // Failure - throw new UnknownHostException(hostname); - } - - internal object Addr; - - internal string CalledName; - - /// - /// Create a UniAddress by wrapping an InetAddress or - /// NbtAddress. - /// - /// - /// Create a UniAddress by wrapping an InetAddress or - /// NbtAddress. - /// - public UniAddress(object addr) - { - if (addr == null) - { - throw new ArgumentException(); - } - this.Addr = addr; - } - - /// Return the IP address of this address as a 32 bit integer. - /// Return the IP address of this address as a 32 bit integer. - public override int GetHashCode() - { - return Addr.GetHashCode(); - } - - /// Compare two addresses for equality. - /// - /// Compare two addresses for equality. Two UniAddresss are equal - /// if they are both UniAddress' and refer to the same IP address. - /// - public override bool Equals(object obj) - { - return obj is UniAddress && Addr.Equals(((UniAddress)obj).Addr); - } - - /// Guess first called name to try for session establishment. - /// - /// Guess first called name to try for session establishment. This - /// method is used exclusively by the jcifs.smb package. - /// - public virtual string FirstCalledName() - { - if (Addr is NbtAddress) - { - return ((NbtAddress)Addr).FirstCalledName(); - } - CalledName = ((IPAddress) Addr).GetHostAddress(); - if (IsDotQuadIp(CalledName)) - { - CalledName = NbtAddress.SmbserverName; - } - else - { - int i = CalledName.IndexOf('.'); - if (i > 1 && i < 15) - { - CalledName = Runtime.Substring(CalledName, 0, i).ToUpper(); - } - else - { - if (CalledName.Length > 15) - { - CalledName = NbtAddress.SmbserverName; - } - else - { - CalledName = CalledName.ToUpper(); - } - } - } - return CalledName; - } - - /// Guess next called name to try for session establishment. - /// - /// Guess next called name to try for session establishment. This - /// method is used exclusively by the jcifs.smb package. - /// - public virtual string NextCalledName() - { - if (Addr is NbtAddress) - { - return ((NbtAddress)Addr).NextCalledName(); - } - if (CalledName != NbtAddress.SmbserverName) - { - CalledName = NbtAddress.SmbserverName; - return CalledName; - } - return null; - } - - /// Return the underlying NbtAddress or InetAddress. - /// Return the underlying NbtAddress or InetAddress. - public virtual object GetAddress() - { - return Addr; - } - - /// Return the hostname of this address such as "MYCOMPUTER". - /// Return the hostname of this address such as "MYCOMPUTER". - public virtual string GetHostName() - { - if (Addr is NbtAddress) - { - return ((NbtAddress)Addr).GetHostName(); - } - return ((IPAddress) Addr).GetHostAddress(); - } - - /// Return the IP address as text such as "192.168.1.15". - /// Return the IP address as text such as "192.168.1.15". - public virtual string GetHostAddress() - { - if (Addr is NbtAddress) - { - return ((NbtAddress)Addr).GetHostAddress(); - } - return ((IPAddress)Addr).GetHostAddress(); - } - - public virtual IPAddress GetHostIpAddress() - { - return (IPAddress) Addr; - } - - /// - /// Return the a text representation of this address such as - /// MYCOMPUTER/192.168.1.15. - /// - /// - /// Return the a text representation of this address such as - /// MYCOMPUTER/192.168.1.15. - /// - public override string ToString() - { - return Addr.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs deleted file mode 100644 index 4770f13548..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Base64.cs +++ /dev/null @@ -1,110 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Text; - -namespace SharpCifs.Util -{ - public class Base64 - { - private static readonly string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /// Base-64 encodes the supplied block of data. - /// - /// Base-64 encodes the supplied block of data. Line wrapping is not - /// applied on output. - /// - /// The block of data that is to be Base-64 encoded. - /// A String containing the encoded data. - public static string Encode(byte[] bytes) - { - int length = bytes.Length; - if (length == 0) - { - return string.Empty; - } - StringBuilder buffer = new StringBuilder((int)Math.Ceiling(length / 3d) * 4); - int remainder = length % 3; - length -= remainder; - int block; - int i = 0; - while (i < length) - { - block = ((bytes[i++] & unchecked(0xff)) << 16) | ((bytes[i++] & unchecked( - 0xff)) << 8) | (bytes[i++] & unchecked(0xff)); - buffer.Append(Alphabet[(int)(((uint)block) >> 18)]); - buffer.Append(Alphabet[((int)(((uint)block) >> 12)) & unchecked(0x3f)]); - buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]); - buffer.Append(Alphabet[block & unchecked(0x3f)]); - } - if (remainder == 0) - { - return buffer.ToString(); - } - if (remainder == 1) - { - block = (bytes[i] & unchecked(0xff)) << 4; - buffer.Append(Alphabet[(int)(((uint)block) >> 6)]); - buffer.Append(Alphabet[block & unchecked(0x3f)]); - buffer.Append("=="); - return buffer.ToString(); - } - block = (((bytes[i++] & unchecked(0xff)) << 8) | ((bytes[i]) & unchecked(0xff))) << 2; - buffer.Append(Alphabet[(int)(((uint)block) >> 12)]); - buffer.Append(Alphabet[((int)(((uint)block) >> 6)) & unchecked(0x3f)]); - buffer.Append(Alphabet[block & unchecked(0x3f)]); - buffer.Append("="); - return buffer.ToString(); - } - - /// Decodes the supplied Base-64 encoded string. - /// Decodes the supplied Base-64 encoded string. - /// The Base-64 encoded string that is to be decoded. - /// A byte[] containing the decoded data block. - public static byte[] Decode(string @string) - { - int length = @string.Length; - if (length == 0) - { - return new byte[0]; - } - int pad = (@string[length - 2] == '=') ? 2 : (@string[length - 1] == '=') ? 1 : 0; - int size = length * 3 / 4 - pad; - byte[] buffer = new byte[size]; - int block; - int i = 0; - int index = 0; - while (i < length) - { - block = (Alphabet.IndexOf(@string[i++]) & unchecked(0xff)) << 18 | (Alphabet - .IndexOf(@string[i++]) & unchecked(0xff)) << 12 | (Alphabet.IndexOf(@string - [i++]) & unchecked(0xff)) << 6 | (Alphabet.IndexOf(@string[i++]) & unchecked( - 0xff)); - buffer[index++] = unchecked((byte)((int)(((uint)block) >> 16))); - if (index < size) - { - buffer[index++] = unchecked((byte)(((int)(((uint)block) >> 8)) & unchecked(0xff))); - } - if (index < size) - { - buffer[index++] = unchecked((byte)(block & unchecked(0xff))); - } - } - return buffer; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs deleted file mode 100644 index c23b14cf88..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/DES.cs +++ /dev/null @@ -1,568 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; - -namespace SharpCifs.Util -{ - /// - /// This code is derived from the above source - /// JCIFS API - /// Norbert Hranitzky - ///

and modified again by Michael B. - ///

- /// - /// This code is derived from the above source - /// JCIFS API - /// Norbert Hranitzky - ///

and modified again by Michael B. Allen - /// - public class DES - { - private int[] _encryptKeys = new int[32]; - - private int[] _decryptKeys = new int[32]; - - private int[] _tempInts = new int[2]; - - public DES() - { - } - - public DES(byte[] key) - { - // DesCipher - the DES encryption method - // - // The meat of this code is by Dave Zimmerman , and is: - // - // Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved. - // - // Permission to use, copy, modify, and distribute this software - // and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and - // without fee is hereby granted, provided that this copyright notice is kept - // intact. - // - // WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY - // OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED - // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE - // FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - // DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - // - // THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE - // CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE - // PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT - // NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE - // SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE - // SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE - // PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP - // SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR - // HIGH RISK ACTIVITIES. - // - // - // The rest is: - // - // Copyright (C) 1996 by Jef Poskanzer . All rights reserved. - // - // Copyright (C) 1996 by Wolfgang Platzer - // email: wplatzer@iaik.tu-graz.ac.at - // - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions - // are met: - // 1. Redistributions of source code must retain the above copyright - // notice, this list of conditions and the following disclaimer. - // 2. Redistributions in binary form must reproduce the above copyright - // notice, this list of conditions and the following disclaimer in the - // documentation and/or other materials provided with the distribution. - // - // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - // SUCH DAMAGE. - // - // Constructor, byte-array key. - if (key.Length == 7) - { - byte[] key8 = new byte[8]; - MakeSmbKey(key, key8); - SetKey(key8); - } - else - { - SetKey(key); - } - } - - public static void MakeSmbKey(byte[] key7, byte[] key8) - { - int i; - key8[0] = unchecked((byte)((key7[0] >> 1) & unchecked(0xff))); - key8[1] = unchecked((byte)((((key7[0] & unchecked(0x01)) << 6) | (((key7[1 - ] & unchecked(0xff)) >> 2) & unchecked(0xff))) & unchecked(0xff))); - key8[2] = unchecked((byte)((((key7[1] & unchecked(0x03)) << 5) | (((key7[2 - ] & unchecked(0xff)) >> 3) & unchecked(0xff))) & unchecked(0xff))); - key8[3] = unchecked((byte)((((key7[2] & unchecked(0x07)) << 4) | (((key7[3 - ] & unchecked(0xff)) >> 4) & unchecked(0xff))) & unchecked(0xff))); - key8[4] = unchecked((byte)((((key7[3] & unchecked(0x0F)) << 3) | (((key7[4 - ] & unchecked(0xff)) >> 5) & unchecked(0xff))) & unchecked(0xff))); - key8[5] = unchecked((byte)((((key7[4] & unchecked(0x1F)) << 2) | (((key7[5 - ] & unchecked(0xff)) >> 6) & unchecked(0xff))) & unchecked(0xff))); - key8[6] = unchecked((byte)((((key7[5] & unchecked(0x3F)) << 1) | (((key7[6 - ] & unchecked(0xff)) >> 7) & unchecked(0xff))) & unchecked(0xff))); - key8[7] = unchecked((byte)(key7[6] & unchecked(0x7F))); - for (i = 0; i < 8; i++) - { - key8[i] = unchecked((byte)(key8[i] << 1)); - } - } - - /// Set the key. - public virtual void SetKey(byte[] key) - { - // CHECK PAROTY TBD - Deskey(key, true, _encryptKeys); - Deskey(key, false, _decryptKeys); - } - - // Turn an 8-byte key into internal keys. - private void Deskey(byte[] keyBlock, bool encrypting, int[] knL) - { - int i; - int j; - int l; - int m; - int n; - int[] pc1M = new int[56]; - int[] pcr = new int[56]; - int[] kn = new int[32]; - for (j = 0; j < 56; ++j) - { - l = _pc1[j]; - m = l & 0x7; - pc1M[j] = ((keyBlock[(int)(((uint)l) >> 3)] & _bytebit[m]) != 0) ? 1 : 0; - } - for (i = 0; i < 16; ++i) - { - if (encrypting) - { - m = i << 1; - } - else - { - m = (15 - i) << 1; - } - n = m + 1; - kn[m] = kn[n] = 0; - for (j = 0; j < 28; ++j) - { - l = j + _totrot[i]; - if (l < 28) - { - pcr[j] = pc1M[l]; - } - else - { - pcr[j] = pc1M[l - 28]; - } - } - for (j = 28; j < 56; ++j) - { - l = j + _totrot[i]; - if (l < 56) - { - pcr[j] = pc1M[l]; - } - else - { - pcr[j] = pc1M[l - 28]; - } - } - for (j = 0; j < 24; ++j) - { - if (pcr[_pc2[j]] != 0) - { - kn[m] |= _bigbyte[j]; - } - if (pcr[_pc2[j + 24]] != 0) - { - kn[n] |= _bigbyte[j]; - } - } - } - Cookey(kn, knL); - } - - private void Cookey(int[] raw, int[] knL) - { - int raw0; - int raw1; - int rawi; - int knLi; - int i; - for (i = 0, rawi = 0, knLi = 0; i < 16; ++i) - { - raw0 = raw[rawi++]; - raw1 = raw[rawi++]; - knL[knLi] = (raw0 & unchecked(0x00fc0000)) << 6; - knL[knLi] |= (raw0 & unchecked(0x00000fc0)) << 10; - knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x00fc0000))) >> 10); - knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x00000fc0))) >> 6); - ++knLi; - knL[knLi] = (raw0 & unchecked(0x0003f000)) << 12; - knL[knLi] |= (raw0 & unchecked(0x0000003f)) << 16; - knL[knLi] |= (int)(((uint)(raw1 & unchecked(0x0003f000))) >> 4); - knL[knLi] |= (raw1 & unchecked(0x0000003f)); - ++knLi; - } - } - - /// Encrypt a block of eight bytes. - private void Encrypt(byte[] clearText, int clearOff, byte[] cipherText, int cipherOff - ) - { - SquashBytesToInts(clearText, clearOff, _tempInts, 0, 2); - Des(_tempInts, _tempInts, _encryptKeys); - SpreadIntsToBytes(_tempInts, 0, cipherText, cipherOff, 2); - } - - /// Decrypt a block of eight bytes. - private void Decrypt(byte[] cipherText, int cipherOff, byte[] clearText, int clearOff - ) - { - SquashBytesToInts(cipherText, cipherOff, _tempInts, 0, 2); - Des(_tempInts, _tempInts, _decryptKeys); - SpreadIntsToBytes(_tempInts, 0, clearText, clearOff, 2); - } - - // The DES function. - private void Des(int[] inInts, int[] outInts, int[] keys) - { - int fval; - int work; - int right; - int leftt; - int round; - int keysi = 0; - leftt = inInts[0]; - right = inInts[1]; - work = (((int)(((uint)leftt) >> 4)) ^ right) & unchecked(0x0f0f0f0f); - right ^= work; - leftt ^= (work << 4); - work = (((int)(((uint)leftt) >> 16)) ^ right) & unchecked(0x0000ffff); - right ^= work; - leftt ^= (work << 16); - work = (((int)(((uint)right) >> 2)) ^ leftt) & unchecked(0x33333333); - leftt ^= work; - right ^= (work << 2); - work = (((int)(((uint)right) >> 8)) ^ leftt) & unchecked(0x00ff00ff); - leftt ^= work; - right ^= (work << 8); - right = (right << 1) | (((int)(((uint)right) >> 31)) & 1); - work = (leftt ^ right) & unchecked((int)(0xaaaaaaaa)); - leftt ^= work; - right ^= work; - leftt = (leftt << 1) | (((int)(((uint)leftt) >> 31)) & 1); - for (round = 0; round < 8; ++round) - { - work = (right << 28) | ((int)(((uint)right) >> 4)); - work ^= keys[keysi++]; - fval = _sp7[work & unchecked(0x0000003f)]; - fval |= _sp5[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)]; - fval |= _sp3[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)]; - fval |= _sp1[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)]; - work = right ^ keys[keysi++]; - fval |= _sp8[work & unchecked(0x0000003f)]; - fval |= _sp6[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)]; - fval |= _sp4[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)]; - fval |= _sp2[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)]; - leftt ^= fval; - work = (leftt << 28) | ((int)(((uint)leftt) >> 4)); - work ^= keys[keysi++]; - fval = _sp7[work & unchecked(0x0000003f)]; - fval |= _sp5[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)]; - fval |= _sp3[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)]; - fval |= _sp1[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)]; - work = leftt ^ keys[keysi++]; - fval |= _sp8[work & unchecked(0x0000003f)]; - fval |= _sp6[((int)(((uint)work) >> 8)) & unchecked(0x0000003f)]; - fval |= _sp4[((int)(((uint)work) >> 16)) & unchecked(0x0000003f)]; - fval |= _sp2[((int)(((uint)work) >> 24)) & unchecked(0x0000003f)]; - right ^= fval; - } - right = (right << 31) | ((int)(((uint)right) >> 1)); - work = (leftt ^ right) & unchecked((int)(0xaaaaaaaa)); - leftt ^= work; - right ^= work; - leftt = (leftt << 31) | ((int)(((uint)leftt) >> 1)); - work = (((int)(((uint)leftt) >> 8)) ^ right) & unchecked(0x00ff00ff); - right ^= work; - leftt ^= (work << 8); - work = (((int)(((uint)leftt) >> 2)) ^ right) & unchecked(0x33333333); - right ^= work; - leftt ^= (work << 2); - work = (((int)(((uint)right) >> 16)) ^ leftt) & unchecked(0x0000ffff); - leftt ^= work; - right ^= (work << 16); - work = (((int)(((uint)right) >> 4)) ^ leftt) & unchecked(0x0f0f0f0f); - leftt ^= work; - right ^= (work << 4); - outInts[0] = right; - outInts[1] = leftt; - } - - /// Encrypt a block of bytes. - public virtual void Encrypt(byte[] clearText, byte[] cipherText) - { - Encrypt(clearText, 0, cipherText, 0); - } - - /// Decrypt a block of bytes. - public virtual void Decrypt(byte[] cipherText, byte[] clearText) - { - Decrypt(cipherText, 0, clearText, 0); - } - - ///

encrypts an array where the length must be a multiple of 8 - public virtual byte[] Encrypt(byte[] clearText) - { - int length = clearText.Length; - if (length % 8 != 0) - { - Console.Out.WriteLine("Array must be a multiple of 8"); - return null; - } - byte[] cipherText = new byte[length]; - int count = length / 8; - for (int i = 0; i < count; i++) - { - Encrypt(clearText, i * 8, cipherText, i * 8); - } - return cipherText; - } - - /// decrypts an array where the length must be a multiple of 8 - public virtual byte[] Decrypt(byte[] cipherText) - { - int length = cipherText.Length; - if (length % 8 != 0) - { - Console.Out.WriteLine("Array must be a multiple of 8"); - return null; - } - byte[] clearText = new byte[length]; - int count = length / 8; - for (int i = 0; i < count; i++) - { - Encrypt(cipherText, i * 8, clearText, i * 8); - } - return clearText; - } - - private static byte[] _bytebit = { unchecked(unchecked(0x80)), unchecked(unchecked(0x40)), unchecked(unchecked(0x20)), unchecked(unchecked(0x10)), unchecked(unchecked(0x08)), unchecked(unchecked(0x04)), unchecked(unchecked(0x02)), unchecked(unchecked(0x01)) }; - - private static int[] _bigbyte = { unchecked(0x800000), unchecked( - 0x400000), unchecked(0x200000), unchecked(0x100000), unchecked( - 0x080000), unchecked(0x040000), unchecked(0x020000), unchecked( - 0x010000), unchecked(0x008000), unchecked(0x004000), unchecked( - 0x002000), unchecked(0x001000), unchecked(0x000800), unchecked( - 0x000400), unchecked(0x000200), unchecked(0x000100), unchecked( - 0x000080), unchecked(0x000040), unchecked(0x000020), unchecked( - 0x000010), unchecked(0x000008), unchecked(0x000004), unchecked( - 0x000002), unchecked(0x000001) }; - - private static byte[] _pc1 = { unchecked(56), unchecked(48) - , unchecked(40), unchecked(32), unchecked(24), unchecked(16), unchecked(8), unchecked(0), unchecked(57), unchecked(49), unchecked(41), unchecked(33), unchecked(25), unchecked(17), unchecked(9), unchecked(1), unchecked(58), unchecked( - 50), unchecked(42), unchecked(34), unchecked(26), unchecked( - 18), unchecked(10), unchecked(2), unchecked(59), unchecked( - 51), unchecked(43), unchecked(35), unchecked(62), unchecked( - 54), unchecked(46), unchecked(38), unchecked(30), unchecked( - 22), unchecked(14), unchecked(6), unchecked(61), unchecked( - 53), unchecked(45), unchecked(37), unchecked(29), unchecked( - 21), unchecked(13), unchecked(5), unchecked(60), unchecked( - 52), unchecked(44), unchecked(36), unchecked(28), unchecked( - 20), unchecked(12), unchecked(4), unchecked(27), unchecked( - 19), unchecked(11), unchecked(3) }; - - private static int[] _totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, - 21, 23, 25, 27, 28 }; - - private static byte[] _pc2 = { unchecked(13), unchecked(16) - , unchecked(10), unchecked(23), unchecked(0), unchecked(4), unchecked(2), unchecked(27), unchecked(14), unchecked(5), unchecked(20), unchecked(9), unchecked(22), unchecked(18), unchecked(11), unchecked(3), unchecked(25), unchecked(7), unchecked(15), unchecked(6), unchecked(26), unchecked(19), unchecked(12), unchecked(1), unchecked(40), unchecked(51), unchecked(30), unchecked(36), unchecked(46), unchecked(54), unchecked(29), unchecked(39), unchecked(50), unchecked( - 44), unchecked(32), unchecked(47), unchecked(43), unchecked( - 48), unchecked(38), unchecked(55), unchecked(33), unchecked( - 52), unchecked(45), unchecked(41), unchecked(49), unchecked( - 35), unchecked(28), unchecked(31) }; - - private static int[] _sp1 = { unchecked(0x01010400), unchecked(0x00000000), unchecked(0x00010000), unchecked(0x01010404), unchecked( - 0x01010004), unchecked(0x00010404), unchecked(0x00000004), - unchecked(0x00010000), unchecked(0x00000400), unchecked(0x01010400), unchecked(0x01010404), unchecked(0x00000400), unchecked(0x01000404), unchecked(0x01010004), unchecked(0x01000000), unchecked( - 0x00000004), unchecked(0x00000404), unchecked(0x01000400), - unchecked(0x01000400), unchecked(0x00010400), unchecked(0x00010400), unchecked(0x01010000), unchecked(0x01010000), unchecked(0x01000404), unchecked(0x00010004), unchecked(0x01000004), unchecked( - 0x01000004), unchecked(0x00010004), unchecked(0x00000000), - unchecked(0x00000404), unchecked(0x00010404), unchecked(0x01000000), unchecked(0x00010000), unchecked(0x01010404), unchecked(0x00000004), unchecked(0x01010000), unchecked(0x01010400), unchecked( - 0x01000000), unchecked(0x01000000), unchecked(0x00000400), - unchecked(0x01010004), unchecked(0x00010000), unchecked(0x00010400), unchecked(0x01000004), unchecked(0x00000400), unchecked(0x00000004), unchecked(0x01000404), unchecked(0x00010404), unchecked( - 0x01010404), unchecked(0x00010004), unchecked(0x01010000), - unchecked(0x01000404), unchecked(0x01000004), unchecked(0x00000404), unchecked(0x00010404), unchecked(0x01010400), unchecked(0x00000404), unchecked(0x01000400), unchecked(0x01000400), unchecked( - 0x00000000), unchecked(0x00010004), unchecked(0x00010400), - unchecked(0x00000000), unchecked(0x01010004) }; - - private static int[] _sp2 = { unchecked((int)(0x80108020)), unchecked((int - )(0x80008000)), unchecked(0x00008000), unchecked(0x00108020), unchecked( - 0x00100000), unchecked(0x00000020), unchecked((int)(0x80100020)), - unchecked((int)(0x80008020)), unchecked((int)(0x80000020)), unchecked((int)(0x80108020 - )), unchecked((int)(0x80108000)), unchecked((int)(0x80000000)), unchecked((int)( - 0x80008000)), unchecked(0x00100000), unchecked(0x00000020), unchecked( - (int)(0x80100020)), unchecked(0x00108000), unchecked(0x00100020), - unchecked((int)(0x80008020)), unchecked(0x00000000), unchecked((int)(0x80000000 - )), unchecked(0x00008000), unchecked(0x00108020), unchecked((int)( - 0x80100000)), unchecked(0x00100020), unchecked((int)(0x80000020)), unchecked( - 0x00000000), unchecked(0x00108000), unchecked(0x00008020), - unchecked((int)(0x80108000)), unchecked((int)(0x80100000)), unchecked(0x00008020), unchecked(0x00000000), unchecked(0x00108020), unchecked((int)( - 0x80100020)), unchecked(0x00100000), unchecked((int)(0x80008020)), unchecked( - (int)(0x80100000)), unchecked((int)(0x80108000)), unchecked(0x00008000), - unchecked((int)(0x80100000)), unchecked((int)(0x80008000)), unchecked(0x00000020), unchecked((int)(0x80108020)), unchecked(0x00108020), unchecked(0x00000020), unchecked(0x00008000), unchecked((int)(0x80000000)), unchecked( - 0x00008020), unchecked((int)(0x80108000)), unchecked(0x00100000), - unchecked((int)(0x80000020)), unchecked(0x00100020), unchecked((int)(0x80008020 - )), unchecked((int)(0x80000020)), unchecked(0x00100020), unchecked(0x00108000), unchecked(0x00000000), unchecked((int)(0x80008000)), unchecked( - 0x00008020), unchecked((int)(0x80000000)), unchecked((int)(0x80100020)), - unchecked((int)(0x80108020)), unchecked(0x00108000) }; - - private static int[] _sp3 = { unchecked(0x00000208), unchecked(0x08020200), unchecked(0x00000000), unchecked(0x08020008), unchecked( - 0x08000200), unchecked(0x00000000), unchecked(0x00020208), - unchecked(0x08000200), unchecked(0x00020008), unchecked(0x08000008), unchecked(0x08000008), unchecked(0x00020000), unchecked(0x08020208), unchecked(0x00020008), unchecked(0x08020000), unchecked( - 0x00000208), unchecked(0x08000000), unchecked(0x00000008), - unchecked(0x08020200), unchecked(0x00000200), unchecked(0x00020200), unchecked(0x08020000), unchecked(0x08020008), unchecked(0x00020208), unchecked(0x08000208), unchecked(0x00020200), unchecked( - 0x00020000), unchecked(0x08000208), unchecked(0x00000008), - unchecked(0x08020208), unchecked(0x00000200), unchecked(0x08000000), unchecked(0x08020200), unchecked(0x08000000), unchecked(0x00020008), unchecked(0x00000208), unchecked(0x00020000), unchecked( - 0x08020200), unchecked(0x08000200), unchecked(0x00000000), - unchecked(0x00000200), unchecked(0x00020008), unchecked(0x08020208), unchecked(0x08000200), unchecked(0x08000008), unchecked(0x00000200), unchecked(0x00000000), unchecked(0x08020008), unchecked( - 0x08000208), unchecked(0x00020000), unchecked(0x08000000), - unchecked(0x08020208), unchecked(0x00000008), unchecked(0x00020208), unchecked(0x00020200), unchecked(0x08000008), unchecked(0x08020000), unchecked(0x08000208), unchecked(0x00000208), unchecked( - 0x08020000), unchecked(0x00020208), unchecked(0x00000008), - unchecked(0x08020008), unchecked(0x00020200) }; - - private static int[] _sp4 = { unchecked(0x00802001), unchecked(0x00002081), unchecked(0x00002081), unchecked(0x00000080), unchecked( - 0x00802080), unchecked(0x00800081), unchecked(0x00800001), - unchecked(0x00002001), unchecked(0x00000000), unchecked(0x00802000), unchecked(0x00802000), unchecked(0x00802081), unchecked(0x00000081), unchecked(0x00000000), unchecked(0x00800080), unchecked( - 0x00800001), unchecked(0x00000001), unchecked(0x00002000), - unchecked(0x00800000), unchecked(0x00802001), unchecked(0x00000080), unchecked(0x00800000), unchecked(0x00002001), unchecked(0x00002080), unchecked(0x00800081), unchecked(0x00000001), unchecked( - 0x00002080), unchecked(0x00800080), unchecked(0x00002000), - unchecked(0x00802080), unchecked(0x00802081), unchecked(0x00000081), unchecked(0x00800080), unchecked(0x00800001), unchecked(0x00802000), unchecked(0x00802081), unchecked(0x00000081), unchecked( - 0x00000000), unchecked(0x00000000), unchecked(0x00802000), - unchecked(0x00002080), unchecked(0x00800080), unchecked(0x00800081), unchecked(0x00000001), unchecked(0x00802001), unchecked(0x00002081), unchecked(0x00002081), unchecked(0x00000080), unchecked( - 0x00802081), unchecked(0x00000081), unchecked(0x00000001), - unchecked(0x00002000), unchecked(0x00800001), unchecked(0x00002001), unchecked(0x00802080), unchecked(0x00800081), unchecked(0x00002001), unchecked(0x00002080), unchecked(0x00800000), unchecked( - 0x00802001), unchecked(0x00000080), unchecked(0x00800000), - unchecked(0x00002000), unchecked(0x00802080) }; - - private static int[] _sp5 = { unchecked(0x00000100), unchecked(0x02080100), unchecked(0x02080000), unchecked(0x42000100), unchecked( - 0x00080000), unchecked(0x00000100), unchecked(0x40000000), - unchecked(0x02080000), unchecked(0x40080100), unchecked(0x00080000), unchecked(0x02000100), unchecked(0x40080100), unchecked(0x42000100), unchecked(0x42080000), unchecked(0x00080100), unchecked( - 0x40000000), unchecked(0x02000000), unchecked(0x40080000), - unchecked(0x40080000), unchecked(0x00000000), unchecked(0x40000100), unchecked(0x42080100), unchecked(0x42080100), unchecked(0x02000100), unchecked(0x42080000), unchecked(0x40000100), unchecked( - 0x00000000), unchecked(0x42000000), unchecked(0x02080100), - unchecked(0x02000000), unchecked(0x42000000), unchecked(0x00080100), unchecked(0x00080000), unchecked(0x42000100), unchecked(0x00000100), unchecked(0x02000000), unchecked(0x40000000), unchecked( - 0x02080000), unchecked(0x42000100), unchecked(0x40080100), - unchecked(0x02000100), unchecked(0x40000000), unchecked(0x42080000), unchecked(0x02080100), unchecked(0x40080100), unchecked(0x00000100), unchecked(0x02000000), unchecked(0x42080000), unchecked( - 0x42080100), unchecked(0x00080100), unchecked(0x42000000), - unchecked(0x42080100), unchecked(0x02080000), unchecked(0x00000000), unchecked(0x40080000), unchecked(0x42000000), unchecked(0x00080100), unchecked(0x02000100), unchecked(0x40000100), unchecked( - 0x00080000), unchecked(0x00000000), unchecked(0x40080000), - unchecked(0x02080100), unchecked(0x40000100) }; - - private static int[] _sp6 = { unchecked(0x20000010), unchecked(0x20400000), unchecked(0x00004000), unchecked(0x20404010), unchecked( - 0x20400000), unchecked(0x00000010), unchecked(0x20404010), - unchecked(0x00400000), unchecked(0x20004000), unchecked(0x00404010), unchecked(0x00400000), unchecked(0x20000010), unchecked(0x00400010), unchecked(0x20004000), unchecked(0x20000000), unchecked( - 0x00004010), unchecked(0x00000000), unchecked(0x00400010), - unchecked(0x20004010), unchecked(0x00004000), unchecked(0x00404000), unchecked(0x20004010), unchecked(0x00000010), unchecked(0x20400010), unchecked(0x20400010), unchecked(0x00000000), unchecked( - 0x00404010), unchecked(0x20404000), unchecked(0x00004010), - unchecked(0x00404000), unchecked(0x20404000), unchecked(0x20000000), unchecked(0x20004000), unchecked(0x00000010), unchecked(0x20400010), unchecked(0x00404000), unchecked(0x20404010), unchecked( - 0x00400000), unchecked(0x00004010), unchecked(0x20000010), - unchecked(0x00400000), unchecked(0x20004000), unchecked(0x20000000), unchecked(0x00004010), unchecked(0x20000010), unchecked(0x20404010), unchecked(0x00404000), unchecked(0x20400000), unchecked( - 0x00404010), unchecked(0x20404000), unchecked(0x00000000), - unchecked(0x20400010), unchecked(0x00000010), unchecked(0x00004000), unchecked(0x20400000), unchecked(0x00404010), unchecked(0x00004000), unchecked(0x00400010), unchecked(0x20004010), unchecked( - 0x00000000), unchecked(0x20404000), unchecked(0x20000000), - unchecked(0x00400010), unchecked(0x20004010) }; - - private static int[] _sp7 = { unchecked(0x00200000), unchecked(0x04200002), unchecked(0x04000802), unchecked(0x00000000), unchecked( - 0x00000800), unchecked(0x04000802), unchecked(0x00200802), - unchecked(0x04200800), unchecked(0x04200802), unchecked(0x00200000), unchecked(0x00000000), unchecked(0x04000002), unchecked(0x00000002), unchecked(0x04000000), unchecked(0x04200002), unchecked( - 0x00000802), unchecked(0x04000800), unchecked(0x00200802), - unchecked(0x00200002), unchecked(0x04000800), unchecked(0x04000002), unchecked(0x04200000), unchecked(0x04200800), unchecked(0x00200002), unchecked(0x04200000), unchecked(0x00000800), unchecked( - 0x00000802), unchecked(0x04200802), unchecked(0x00200800), - unchecked(0x00000002), unchecked(0x04000000), unchecked(0x00200800), unchecked(0x04000000), unchecked(0x00200800), unchecked(0x00200000), unchecked(0x04000802), unchecked(0x04000802), unchecked( - 0x04200002), unchecked(0x04200002), unchecked(0x00000002), - unchecked(0x00200002), unchecked(0x04000000), unchecked(0x04000800), unchecked(0x00200000), unchecked(0x04200800), unchecked(0x00000802), unchecked(0x00200802), unchecked(0x04200800), unchecked( - 0x00000802), unchecked(0x04000002), unchecked(0x04200802), - unchecked(0x04200000), unchecked(0x00200800), unchecked(0x00000000), unchecked(0x00000002), unchecked(0x04200802), unchecked(0x00000000), unchecked(0x00200802), unchecked(0x04200000), unchecked( - 0x00000800), unchecked(0x04000002), unchecked(0x04000800), - unchecked(0x00000800), unchecked(0x00200002) }; - - private static int[] _sp8 = { unchecked(0x10001040), unchecked(0x00001000), unchecked(0x00040000), unchecked(0x10041040), unchecked( - 0x10000000), unchecked(0x10001040), unchecked(0x00000040), - unchecked(0x10000000), unchecked(0x00040040), unchecked(0x10040000), unchecked(0x10041040), unchecked(0x00041000), unchecked(0x10041000), unchecked(0x00041040), unchecked(0x00001000), unchecked( - 0x00000040), unchecked(0x10040000), unchecked(0x10000040), - unchecked(0x10001000), unchecked(0x00001040), unchecked(0x00041000), unchecked(0x00040040), unchecked(0x10040040), unchecked(0x10041000), unchecked(0x00001040), unchecked(0x00000000), unchecked( - 0x00000000), unchecked(0x10040040), unchecked(0x10000040), - unchecked(0x10001000), unchecked(0x00041040), unchecked(0x00040000), unchecked(0x00041040), unchecked(0x00040000), unchecked(0x10041000), unchecked(0x00001000), unchecked(0x00000040), unchecked( - 0x10040040), unchecked(0x00001000), unchecked(0x00041040), - unchecked(0x10001000), unchecked(0x00000040), unchecked(0x10000040), unchecked(0x10040000), unchecked(0x10040040), unchecked(0x10000000), unchecked(0x00040000), unchecked(0x10001040), unchecked( - 0x00000000), unchecked(0x10041040), unchecked(0x00040040), - unchecked(0x10000040), unchecked(0x10040000), unchecked(0x10001000), unchecked(0x10001040), unchecked(0x00000000), unchecked(0x10041040), unchecked(0x00041000), unchecked(0x00041000), unchecked( - 0x00001040), unchecked(0x00001040), unchecked(0x00040040), - unchecked(0x10000000), unchecked(0x10041000) }; - - // Tables, permutations, S-boxes, etc. - /// Squash bytes down to ints. - public static void SquashBytesToInts(byte[] inBytes, int inOff, int[] outInts, int - outOff, int intLen) - { - for (int i = 0; i < intLen; ++i) - { - outInts[outOff + i] = ((inBytes[inOff + i * 4] & unchecked(0xff)) << 24) | - ((inBytes[inOff + i * 4 + 1] & unchecked(0xff)) << 16) | ((inBytes[inOff - + i * 4 + 2] & unchecked(0xff)) << 8) | (inBytes[inOff + i * 4 + 3] & unchecked( - 0xff)); - } - } - - /// Spread ints into bytes. - public static void SpreadIntsToBytes(int[] inInts, int inOff, byte[] outBytes, int - outOff, int intLen) - { - for (int i = 0; i < intLen; ++i) - { - outBytes[outOff + i * 4] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >> 24 - ))); - outBytes[outOff + i * 4 + 1] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >> - 16))); - outBytes[outOff + i * 4 + 2] = unchecked((byte)((int)(((uint)inInts[inOff + i]) >> - 8))); - outBytes[outOff + i * 4 + 3] = unchecked((byte)inInts[inOff + i]); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs deleted file mode 100644 index 7e4d57705b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Encdec.cs +++ /dev/null @@ -1,401 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util -{ - public class Encdec - { - public const long MillisecondsBetween1970And1601 = 11644473600000L; - - public const long SecBetweeen1904And1970 = 2082844800L; - - public const int Time1970Sec32Be = 1; - - public const int Time1970Sec32Le = 2; - - public const int Time1904Sec32Be = 3; - - public const int Time1904Sec32Le = 4; - - public const int Time1601Nanos64Le = 5; - - public const int Time1601Nanos64Be = 6; - - public const int Time1970Millis64Be = 7; - - public const int Time1970Millis64Le = 8; - - public static int Enc_uint16be(short s, byte[] dst, int di) - { - dst[di++] = unchecked((byte)((s >> 8) & unchecked(0xFF))); - dst[di] = unchecked((byte)(s & unchecked(0xFF))); - return 2; - } - - public static int Enc_uint32be(int i, byte[] dst, int di) - { - dst[di++] = unchecked((byte)((i >> 24) & unchecked(0xFF))); - dst[di++] = unchecked((byte)((i >> 16) & unchecked(0xFF))); - dst[di++] = unchecked((byte)((i >> 8) & unchecked(0xFF))); - dst[di] = unchecked((byte)(i & unchecked(0xFF))); - return 4; - } - - public static int Enc_uint16le(short s, byte[] dst, int di) - { - dst[di++] = unchecked((byte)(s & unchecked(0xFF))); - dst[di] = unchecked((byte)((s >> 8) & unchecked(0xFF))); - return 2; - } - - public static int Enc_uint32le(int i, byte[] dst, int di) - { - dst[di++] = unchecked((byte)(i & unchecked(0xFF))); - dst[di++] = unchecked((byte)((i >> 8) & unchecked(0xFF))); - dst[di++] = unchecked((byte)((i >> 16) & unchecked(0xFF))); - dst[di] = unchecked((byte)((i >> 24) & unchecked(0xFF))); - return 4; - } - - public static short Dec_uint16be(byte[] src, int si) - { - return (short)(((src[si] & unchecked(0xFF)) << 8) | (src[si + 1] & unchecked( - 0xFF))); - } - - public static int Dec_uint32be(byte[] src, int si) - { - return ((src[si] & unchecked(0xFF)) << 24) | ((src[si + 1] & unchecked(0xFF)) << 16) | ((src[si + 2] & unchecked(0xFF)) << 8) | (src[si + 3] - & unchecked(0xFF)); - } - - public static short Dec_uint16le(byte[] src, int si) - { - return (short)((src[si] & unchecked(0xFF)) | ((src[si + 1] & unchecked(0xFF)) << 8)); - } - - public static int Dec_uint32le(byte[] src, int si) - { - return (src[si] & unchecked(0xFF)) | ((src[si + 1] & unchecked(0xFF - )) << 8) | ((src[si + 2] & unchecked(0xFF)) << 16) | ((src[si + 3] & unchecked( - 0xFF)) << 24); - } - - public static int Enc_uint64be(long l, byte[] dst, int di) - { - Enc_uint32be((int)(l & unchecked(0xFFFFFFFFL)), dst, di + 4); - Enc_uint32be((int)((l >> 32) & unchecked(0xFFFFFFFFL)), dst, di); - return 8; - } - - public static int Enc_uint64le(long l, byte[] dst, int di) - { - Enc_uint32le((int)(l & unchecked(0xFFFFFFFFL)), dst, di); - Enc_uint32le((int)((l >> 32) & unchecked(0xFFFFFFFFL)), dst, di + 4); - return 8; - } - - public static long Dec_uint64be(byte[] src, int si) - { - long l; - l = Dec_uint32be(src, si) & unchecked(0xFFFFFFFFL); - l <<= 32; - l |= Dec_uint32be(src, si + 4) & unchecked(0xFFFFFFFFL); - return l; - } - - public static long Dec_uint64le(byte[] src, int si) - { - long l; - l = Dec_uint32le(src, si + 4) & unchecked(0xFFFFFFFFL); - l <<= 32; - l |= Dec_uint32le(src, si) & unchecked(0xFFFFFFFFL); - return l; - } - - public static int Enc_floatle(float f, byte[] dst, int di) - { - return Enc_uint32le((int)BitConverter.DoubleToInt64Bits(f), dst, di); - } - - public static int Enc_floatbe(float f, byte[] dst, int di) - { - return Enc_uint32be((int)BitConverter.DoubleToInt64Bits(f), dst, di); - } - - public static float Dec_floatle(byte[] src, int si) - { - return (float)BitConverter.Int64BitsToDouble(Dec_uint32le(src, si)); - } - - public static float Dec_floatbe(byte[] src, int si) - { - return (float)BitConverter.Int64BitsToDouble(Dec_uint32be(src, si)); - } - - public static int Enc_doublele(double d, byte[] dst, int di) - { - return Enc_uint64le(BitConverter.DoubleToInt64Bits(d), dst, di); - } - - public static int Enc_doublebe(double d, byte[] dst, int di) - { - return Enc_uint64be(BitConverter.DoubleToInt64Bits(d), dst, di); - } - - public static double Dec_doublele(byte[] src, int si) - { - return BitConverter.Int64BitsToDouble(Dec_uint64le(src, si)); - } - - public static double Dec_doublebe(byte[] src, int si) - { - return BitConverter.Int64BitsToDouble(Dec_uint64be(src, si)); - } - - public static int Enc_time(DateTime date, byte[] dst, int di, int enc) - { - long t; - switch (enc) - { - case Time1970Sec32Be: - { - return Enc_uint32be((int)(date.GetTime() / 1000L), dst, di); - } - - case Time1970Sec32Le: - { - return Enc_uint32le((int)(date.GetTime() / 1000L), dst, di); - } - - case Time1904Sec32Be: - { - return Enc_uint32be((int)((date.GetTime() / 1000L + SecBetweeen1904And1970) & - unchecked((int)(0xFFFFFFFF))), dst, di); - } - - case Time1904Sec32Le: - { - return Enc_uint32le((int)((date.GetTime() / 1000L + SecBetweeen1904And1970) & - unchecked((int)(0xFFFFFFFF))), dst, di); - } - - case Time1601Nanos64Be: - { - t = (date.GetTime() + MillisecondsBetween1970And1601) * 10000L; - return Enc_uint64be(t, dst, di); - } - - case Time1601Nanos64Le: - { - t = (date.GetTime() + MillisecondsBetween1970And1601) * 10000L; - return Enc_uint64le(t, dst, di); - } - - case Time1970Millis64Be: - { - return Enc_uint64be(date.GetTime(), dst, di); - } - - case Time1970Millis64Le: - { - return Enc_uint64le(date.GetTime(), dst, di); - } - - default: - { - throw new ArgumentException("Unsupported time encoding"); - } - } - } - - public static DateTime Dec_time(byte[] src, int si, int enc) - { - long t; - switch (enc) - { - case Time1970Sec32Be: - { - return Sharpen.Extensions.CreateDate(Dec_uint32be(src, si) * 1000L); - } - - case Time1970Sec32Le: - { - return Sharpen.Extensions.CreateDate(Dec_uint32le(src, si) * 1000L); - } - - case Time1904Sec32Be: - { - return Sharpen.Extensions.CreateDate(((Dec_uint32be(src, si) & unchecked(0xFFFFFFFFL)) - SecBetweeen1904And1970) * 1000L); - } - - case Time1904Sec32Le: - { - return Sharpen.Extensions.CreateDate(((Dec_uint32le(src, si) & unchecked(0xFFFFFFFFL)) - SecBetweeen1904And1970) * 1000L); - } - - case Time1601Nanos64Be: - { - t = Dec_uint64be(src, si); - return Sharpen.Extensions.CreateDate(t / 10000L - MillisecondsBetween1970And1601 - ); - } - - case Time1601Nanos64Le: - { - t = Dec_uint64le(src, si); - return Sharpen.Extensions.CreateDate(t / 10000L - MillisecondsBetween1970And1601 - ); - } - - case Time1970Millis64Be: - { - return Sharpen.Extensions.CreateDate(Dec_uint64be(src, si)); - } - - case Time1970Millis64Le: - { - return Sharpen.Extensions.CreateDate(Dec_uint64le(src, si)); - } - - default: - { - throw new ArgumentException("Unsupported time encoding"); - } - } - } - - /// - public static int Enc_utf8(string str, byte[] dst, int di, int dlim) - { - int start = di; - int ch; - int strlen = str.Length; - for (int i = 0; di < dlim && i < strlen; i++) - { - ch = str[i]; - if ((ch >= unchecked(0x0001)) && (ch <= unchecked(0x007F))) - { - dst[di++] = unchecked((byte)ch); - } - else - { - if (ch > unchecked(0x07FF)) - { - if ((dlim - di) < 3) - { - break; - } - dst[di++] = unchecked((byte)(unchecked(0xE0) | ((ch >> 12) & unchecked(0x0F)))); - dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 6) & unchecked(0x3F)))); - dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 0) & unchecked(0x3F)))); - } - else - { - if ((dlim - di) < 2) - { - break; - } - dst[di++] = unchecked((byte)(unchecked(0xC0) | ((ch >> 6) & unchecked(0x1F)))); - dst[di++] = unchecked((byte)(unchecked(0x80) | ((ch >> 0) & unchecked(0x3F)))); - } - } - } - return di - start; - } - - /// - public static string Dec_utf8(byte[] src, int si, int slim) - { - char[] uni = new char[slim - si]; - int ui; - int ch; - for (ui = 0; si < slim && (ch = src[si++] & unchecked(0xFF)) != 0; ui++) - { - if (ch < unchecked(0x80)) - { - uni[ui] = (char)ch; - } - else - { - if ((ch & unchecked(0xE0)) == unchecked(0xC0)) - { - if ((slim - si) < 2) - { - break; - } - uni[ui] = (char)((ch & unchecked(0x1F)) << 6); - ch = src[si++] & unchecked(0xFF); - uni[ui] |= (char)((char)ch & unchecked(0x3F)); - if ((ch & unchecked(0xC0)) != unchecked(0x80) || uni[ui] < unchecked( - 0x80)) - { - throw new IOException("Invalid UTF-8 sequence"); - } - } - else - { - if ((ch & unchecked(0xF0)) == unchecked(0xE0)) - { - if ((slim - si) < 3) - { - break; - } - uni[ui] = (char)((ch & unchecked(0x0F)) << 12); - ch = src[si++] & unchecked(0xFF); - if ((ch & unchecked(0xC0)) != unchecked(0x80)) - { - throw new IOException("Invalid UTF-8 sequence"); - } - uni[ui] |= (char)((char)(ch & unchecked(0x3F)) << 6); - ch = src[si++] & unchecked(0xFF); - uni[ui] |= (char)((char)ch & unchecked(0x3F)); - if ((ch & unchecked(0xC0)) != unchecked(0x80) || uni[ui] < unchecked( - 0x800)) - { - throw new IOException("Invalid UTF-8 sequence"); - } - } - else - { - throw new IOException("Unsupported UTF-8 sequence"); - } - } - } - } - return new string(uni, 0, ui); - } - - /// - public static string Dec_ucs2le(byte[] src, int si, int slim, char[] buf) - { - int bi; - for (bi = 0; (si + 1) < slim; bi++, si += 2) - { - buf[bi] = (char)Dec_uint16le(src, si); - if (buf[bi] == '\0') - { - break; - } - } - return new string(buf, 0, bi); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs deleted file mode 100644 index 9ab31d61b8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/HMACT64.cs +++ /dev/null @@ -1,146 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util -{ - /// This is an implementation of the HMACT64 keyed hashing algorithm. - /// - /// This is an implementation of the HMACT64 keyed hashing algorithm. - /// HMACT64 is defined by Luke Leighton as a modified HMAC-MD5 (RFC 2104) - /// in which the key is truncated at 64 bytes (rather than being hashed - /// via MD5). - /// - public class Hmact64 : MessageDigest - { - private const int BlockLength = 64; - - private const byte Ipad = unchecked(unchecked(0x36)); - - private const byte Opad = unchecked(unchecked(0x5c)); - - private MessageDigest _md5; - - private byte[] _ipad = new byte[BlockLength]; - - private byte[] _opad = new byte[BlockLength]; - - /// Creates an HMACT64 instance which uses the given secret key material. - /// Creates an HMACT64 instance which uses the given secret key material. - /// The key material to use in hashing. - public Hmact64(byte[] key) - { - int length = Math.Min(key.Length, BlockLength); - for (int i = 0; i < length; i++) - { - _ipad[i] = unchecked((byte)(key[i] ^ Ipad)); - _opad[i] = unchecked((byte)(key[i] ^ Opad)); - } - for (int i1 = length; i1 < BlockLength; i1++) - { - _ipad[i1] = Ipad; - _opad[i1] = Opad; - } - try - { - _md5 = GetInstance("MD5"); - } - catch (Exception ex) - { - throw new InvalidOperationException(ex.Message); - } - EngineReset(); - } - - - protected byte[] EngineDigest() - { - byte[] digest = _md5.Digest(); - _md5.Update(_opad); - return _md5.Digest(digest); - } - - protected int EngineDigest(byte[] buf, int offset, int len) - { - byte[] digest = _md5.Digest(); - _md5.Update(_opad); - _md5.Update(digest); - try - { - _md5.Digest(buf, offset, len); - - return len; - } - catch (Exception) - { - throw new InvalidOperationException(); - } - } - - protected int EngineGetDigestLength() - { - return _md5.GetDigestLength(); - } - - protected void EngineReset() - { - _md5.Reset(); - _md5.Update(_ipad); - } - - protected void EngineUpdate(byte b) - { - _md5.Update(b); - } - - protected void EngineUpdate(byte[] input, int offset, int len) - { - _md5.Update(input, offset, len); - } - - public override byte[] Digest() - { - return EngineDigest(); - } - - public override int GetDigestLength() - { - return EngineGetDigestLength(); - } - - public override void Reset() - { - EngineReset(); - } - - public override void Update(byte[] b) - { - EngineUpdate(b, 0, b.Length); - } - - public override void Update(byte b) - { - EngineUpdate(b); - } - - public override void Update(byte[] b, int offset, int len) - { - EngineUpdate(b, offset, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs deleted file mode 100644 index 7e53f76e3e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Hexdump.cs +++ /dev/null @@ -1,191 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; - -namespace SharpCifs.Util -{ - public class Hexdump - { - private static readonly string Nl = @"\r\n"; //Runtime.GetProperty("line.separator"); - - private static readonly int NlLength = Nl.Length; - - private static readonly char[] SpaceChars = { ' ', ' ', ' ', ' ', ' ' - , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' - , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' - , ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; - - public static readonly char[] HexDigits = { '0', '1', '2', '3', '4', - '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - - - private static bool IsIsoControl(char c) - { - return (c >= '\u0000' && c <= '\u001F') || (c >= '\u007F' && c <= '\u009F'); - } - - /// - /// Generate "hexdump" output of the buffer at src like the following: - ///

-		/// 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46  |..).........
-		/// 
- /// - /// Generate "hexdump" output of the buffer at src like the following: - ///

-		/// 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46  |..)......... EGF|
-		/// 00010: 43 45 46 45 45 43 41 43 41 43 41 43 41 43 41 43  |CEFEECACACACACAC|
-		/// 00020: 41 43 41 43 41 43 41 43 41 43 41 41 44 00 00 20  |ACACACACACAAD.. |
-		/// 00030: 00 01 c0 0c 00 20 00 01 00 00 00 00 00 06 20 00  |..... ........ .|
-		/// 00040: ac 22 22 e1                                      |."".            |
-		/// 
- ///
- public static void ToHexdump(TextWriter ps, byte[] src, int srcIndex, int length) - { - if (length == 0) - { - return; - } - int s = length % 16; - int r = (s == 0) ? length / 16 : length / 16 + 1; - char[] c = new char[r * (74 + NlLength)]; - char[] d = new char[16]; - int i; - int si = 0; - int ci = 0; - do - { - ToHexChars(si, c, ci, 5); - ci += 5; - c[ci++] = ':'; - do - { - if (si == length) - { - int n = 16 - s; - Array.Copy(SpaceChars, 0, c, ci, n * 3); - ci += n * 3; - Array.Copy(SpaceChars, 0, d, s, n); - break; - } - c[ci++] = ' '; - i = src[srcIndex + si] & 0xFF; - ToHexChars(i, c, ci, 2); - ci += 2; - if (i < 0 || IsIsoControl((char)i)) - { - d[si % 16] = '.'; - } - else - { - d[si % 16] = (char)i; - } - } - while ((++si % 16) != 0); - c[ci++] = ' '; - c[ci++] = ' '; - c[ci++] = '|'; - Array.Copy(d, 0, c, ci, 16); - ci += 16; - c[ci++] = '|'; - //Sharpen.Runtime.GetCharsForString(NL, 0, NL_LENGTH, c, ci); - c = Nl.ToCharArray(0, NlLength); - ci += NlLength; - } - while (si < length); - ps.WriteLine(c); - } - - /// - /// This is an alternative to the java.lang.Integer.toHexString - /// method. - /// - /// - /// This is an alternative to the java.lang.Integer.toHexString - /// method. It is an efficient relative that also will pad the left side so - /// that the result is size digits. - /// - public static string ToHexString(int val, int size) - { - char[] c = new char[size]; - ToHexChars(val, c, 0, size); - return new string(c); - } - - public static string ToHexString(long val, int size) - { - char[] c = new char[size]; - ToHexChars(val, c, 0, size); - return new string(c); - } - - public static string ToHexString(byte[] src, int srcIndex, int size) - { - char[] c = new char[size]; - size = (size % 2 == 0) ? size / 2 : size / 2 + 1; - for (int i = 0, j = 0; i < size; i++) - { - c[j++] = HexDigits[(src[i] >> 4) & 0x0F]; - if (j == c.Length) - { - break; - } - c[j++] = HexDigits[src[i] & 0x0F]; - } - return new string(c); - } - - /// - /// This is the same as - /// ToHexString(int, int) - /// but provides a more practical form when trying to avoid - /// string - /// concatenation and - /// System.Text.StringBuilder - /// . - /// - public static void ToHexChars(int val, char[] dst, int dstIndex, int size) - { - while (size > 0) - { - int i = dstIndex + size - 1; - if (i < dst.Length) - { - dst[i] = HexDigits[val & 0x000F]; - } - if (val != 0) - { - val = (int)(((uint)val) >> 4); - } - size--; - } - } - - public static void ToHexChars(long val, char[] dst, int dstIndex, int size) - { - while (size > 0) - { - dst[dstIndex + size - 1] = HexDigits[(int)(val & 0x000FL)]; - if (val != 0) - { - val = (long)(((ulong)val) >> 4); - } - size--; - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs deleted file mode 100644 index 9dd130b500..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/LogStream.cs +++ /dev/null @@ -1,78 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.Diagnostics; -using System.IO; -using System.Text; -//using Windows.Storage; -//using Windows.UI.Notifications; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util -{ - /// - /// 0 - nothing - /// 1 - critical [default] - /// 2 - basic info can be logged under load - /// 3 - almost everything - /// N - debugging - /// - public class LogStream: PrintWriter -{ - private static LogStream _inst = null; - - public int Level = 1; - - public void SetLevel(int level) - { - this.Level = level; - } - - public LogStream(TextWriter other) : base(other) - { - - } - - /// - /// This must be called before getInstance is called or - /// it will have no effect. - /// - /// - /// This must be called before getInstance is called or - /// it will have no effect. - /// - public static void SetInstance(TextWriter other) - { - //inst = new Jcifs.Util.LogStream(); - _inst = new LogStream(other); - } - - public static LogStream GetInstance() - { - if (_inst == null) - { - SetInstance(Console.Error); - } - return _inst; - } - - public override Encoding Encoding - { - get { throw new NotImplementedException(); } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs deleted file mode 100644 index 99eb6ade66..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/MD4.cs +++ /dev/null @@ -1,347 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util -{ - /// Implements the MD4 message digest algorithm in Java. - /// - /// Implements the MD4 message digest algorithm in Java. - ///

- /// References: - ///

    - ///
  1. Ronald L. Rivest, - /// " - /// The MD4 Message-Digest Algorithm", - /// IETF RFC-1320 (informational). - ///
- ///

$Revision: 1.2 $ - /// - /// Raif S. Naffah - public class Md4 : MessageDigest - { - ///

The size in bytes of the input block to the tranformation algorithm. - /// The size in bytes of the input block to the tranformation algorithm. - private const int BlockLength = 64; - - /// 4 32-bit words (interim result) - private int[] _context = new int[4]; - - /// Number of bytes processed so far mod. - /// Number of bytes processed so far mod. 2 power of 64. - private long _count; - - /// 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits. - /// 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits. - private byte[] _buffer = new byte[BlockLength]; - - /// 512 bits work buffer = 16 x 32-bit words - private int[] _x = new int[16]; - - public Md4() - { - // This file is currently unlocked (change this line if you lock the file) - // - // $Log: MD4.java,v $ - // Revision 1.2 1998/01/05 03:41:19 iang - // Added references only. - // - // Revision 1.1.1.1 1997/11/03 22:36:56 hopwood - // + Imported to CVS (tagged as 'start'). - // - // Revision 0.1.0.0 1997/07/14 R. Naffah - // + original version - // - // $Endlog$ - // MD4 specific object variables - //........................................................................... - // = 512 / 8; - // Constructors - //........................................................................... - EngineReset(); - } - - /// This constructor is here to implement cloneability of this class. - /// This constructor is here to implement cloneability of this class. - private Md4(Md4 md) : this() - { - _context = (int[])md._context.Clone(); - _buffer = (byte[])md._buffer.Clone(); - _count = md._count; - } - - // Cloneable method implementation - //........................................................................... - /// Returns a copy of this MD object. - /// Returns a copy of this MD object. - public object Clone() - { - return new Md4(this); - } - - // JCE methods - //........................................................................... - /// - /// Resets this object disregarding any temporary data present at the - /// time of the invocation of this call. - /// - /// - /// Resets this object disregarding any temporary data present at the - /// time of the invocation of this call. - /// - protected void EngineReset() - { - // initial values of MD4 i.e. A, B, C, D - // as per rfc-1320; they are low-order byte first - _context[0] = unchecked(0x67452301); - _context[1] = unchecked((int)(0xEFCDAB89)); - _context[2] = unchecked((int)(0x98BADCFE)); - _context[3] = unchecked(0x10325476); - _count = 0L; - for (int i = 0; i < BlockLength; i++) - { - _buffer[i] = 0; - } - } - - /// Continues an MD4 message digest using the input byte. - /// Continues an MD4 message digest using the input byte. - protected void EngineUpdate(byte b) - { - // compute number of bytes still unhashed; ie. present in buffer - int i = (int)(_count % BlockLength); - _count++; - // update number of bytes - _buffer[i] = b; - if (i == BlockLength - 1) - { - Transform(_buffer, 0); - } - } - - /// MD4 block update operation. - /// - /// MD4 block update operation. - ///

- /// Continues an MD4 message digest operation, by filling the buffer, - /// transform(ing) data in 512-bit message block(s), updating the variables - /// context and count, and leaving (buffering) the remaining bytes in buffer - /// for the next update or finish. - /// - /// input block - /// start of meaningful bytes in input - /// count of bytes in input block to consider - protected void EngineUpdate(byte[] input, int offset, int len) - { - // make sure we don't exceed input's allocated size/length - if (offset < 0 || len < 0 || (long)offset + len > input.Length) - { - throw new IndexOutOfRangeException(); - } - // compute number of bytes still unhashed; ie. present in buffer - int bufferNdx = (int)(_count % BlockLength); - _count += len; - // update number of bytes - int partLen = BlockLength - bufferNdx; - int i = 0; - if (len >= partLen) - { - Array.Copy(input, offset, _buffer, bufferNdx, partLen); - Transform(_buffer, 0); - for (i = partLen; i + BlockLength - 1 < len; i += BlockLength) - { - Transform(input, offset + i); - } - bufferNdx = 0; - } - // buffer remaining input - if (i < len) - { - Array.Copy(input, offset + i, _buffer, bufferNdx, len - i); - } - } - - ///

- /// Completes the hash computation by performing final operations such - /// as padding. - /// - /// - /// Completes the hash computation by performing final operations such - /// as padding. At the return of this engineDigest, the MD engine is - /// reset. - /// - /// the array of bytes for the resulting hash value. - protected byte[] EngineDigest() - { - // pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512 - int bufferNdx = (int)(_count % BlockLength); - int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx); - // padding is alwas binary 1 followed by binary 0s - byte[] tail = new byte[padLen + 8]; - tail[0] = unchecked(unchecked(0x80)); - // append length before final transform: - // save number of bits, casting the long to an array of 8 bytes - // save low-order byte first. - for (int i = 0; i < 8; i++) - { - tail[padLen + i] = unchecked((byte)((long)(((ulong)(_count * 8)) >> (8 * i)))); - } - EngineUpdate(tail, 0, tail.Length); - byte[] result = new byte[16]; - // cast this MD4's context (array of 4 ints) into an array of 16 bytes. - for (int i1 = 0; i1 < 4; i1++) - { - for (int j = 0; j < 4; j++) - { - result[i1 * 4 + j] = unchecked((byte)((int)(((uint)_context[i1]) >> (8 * j)))); - } - } - // reset the engine - EngineReset(); - return result; - } - - // own methods - //........................................................................... - /// MD4 basic transformation. - /// - /// MD4 basic transformation. - ///

- /// Transforms context based on 512 bits from input block starting - /// from the offset'th byte. - /// - /// input sub-array. - /// starting position of sub-array. - private void Transform(byte[] block, int offset) - { - // encodes 64 bytes from input block into an array of 16 32-bit - // entities. Use A as a temp var. - for (int i = 0; i < 16; i++) - { - _x[i] = (block[offset++] & unchecked(0xFF)) | (block[offset++] & unchecked( - 0xFF)) << 8 | (block[offset++] & unchecked(0xFF)) << 16 | (block[offset - ++] & unchecked(0xFF)) << 24; - } - int a = _context[0]; - int b = _context[1]; - int c = _context[2]; - int d = _context[3]; - a = Ff(a, b, c, d, _x[0], 3); - d = Ff(d, a, b, c, _x[1], 7); - c = Ff(c, d, a, b, _x[2], 11); - b = Ff(b, c, d, a, _x[3], 19); - a = Ff(a, b, c, d, _x[4], 3); - d = Ff(d, a, b, c, _x[5], 7); - c = Ff(c, d, a, b, _x[6], 11); - b = Ff(b, c, d, a, _x[7], 19); - a = Ff(a, b, c, d, _x[8], 3); - d = Ff(d, a, b, c, _x[9], 7); - c = Ff(c, d, a, b, _x[10], 11); - b = Ff(b, c, d, a, _x[11], 19); - a = Ff(a, b, c, d, _x[12], 3); - d = Ff(d, a, b, c, _x[13], 7); - c = Ff(c, d, a, b, _x[14], 11); - b = Ff(b, c, d, a, _x[15], 19); - a = Gg(a, b, c, d, _x[0], 3); - d = Gg(d, a, b, c, _x[4], 5); - c = Gg(c, d, a, b, _x[8], 9); - b = Gg(b, c, d, a, _x[12], 13); - a = Gg(a, b, c, d, _x[1], 3); - d = Gg(d, a, b, c, _x[5], 5); - c = Gg(c, d, a, b, _x[9], 9); - b = Gg(b, c, d, a, _x[13], 13); - a = Gg(a, b, c, d, _x[2], 3); - d = Gg(d, a, b, c, _x[6], 5); - c = Gg(c, d, a, b, _x[10], 9); - b = Gg(b, c, d, a, _x[14], 13); - a = Gg(a, b, c, d, _x[3], 3); - d = Gg(d, a, b, c, _x[7], 5); - c = Gg(c, d, a, b, _x[11], 9); - b = Gg(b, c, d, a, _x[15], 13); - a = Hh(a, b, c, d, _x[0], 3); - d = Hh(d, a, b, c, _x[8], 9); - c = Hh(c, d, a, b, _x[4], 11); - b = Hh(b, c, d, a, _x[12], 15); - a = Hh(a, b, c, d, _x[2], 3); - d = Hh(d, a, b, c, _x[10], 9); - c = Hh(c, d, a, b, _x[6], 11); - b = Hh(b, c, d, a, _x[14], 15); - a = Hh(a, b, c, d, _x[1], 3); - d = Hh(d, a, b, c, _x[9], 9); - c = Hh(c, d, a, b, _x[5], 11); - b = Hh(b, c, d, a, _x[13], 15); - a = Hh(a, b, c, d, _x[3], 3); - d = Hh(d, a, b, c, _x[11], 9); - c = Hh(c, d, a, b, _x[7], 11); - b = Hh(b, c, d, a, _x[15], 15); - _context[0] += a; - _context[1] += b; - _context[2] += c; - _context[3] += d; - } - - // The basic MD4 atomic functions. - private int Ff(int a, int b, int c, int d, int x, int s) - { - int t = a + ((b & c) | (~b & d)) + x; - return t << s | (int)(((uint)t) >> (32 - s)); - } - - private int Gg(int a, int b, int c, int d, int x, int s) - { - int t = a + ((b & (c | d)) | (c & d)) + x + unchecked(0x5A827999); - return t << s | (int)(((uint)t) >> (32 - s)); - } - - private int Hh(int a, int b, int c, int d, int x, int s) - { - int t = a + (b ^ c ^ d) + x + unchecked(0x6ED9EBA1); - return t << s | (int)(((uint)t) >> (32 - s)); - } - - public override byte[] Digest() - { - return EngineDigest(); - } - - public override int GetDigestLength() - { - return EngineDigest().Length; - } - - public override void Reset() - { - EngineReset(); - } - - public override void Update(byte[] b) - { - EngineUpdate(b, 0, b.Length); - } - - public override void Update(byte b) - { - EngineUpdate(b); - } - - public override void Update(byte[] b, int offset, int len) - { - EngineUpdate(b, offset, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs deleted file mode 100644 index b17e076e72..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/RC4.cs +++ /dev/null @@ -1,68 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Util -{ - public class Rc4 - { - internal byte[] S; - - internal int I; - - internal int J; - - public Rc4() - { - } - - public Rc4(byte[] key) - { - Init(key, 0, key.Length); - } - - public virtual void Init(byte[] key, int ki, int klen) - { - S = new byte[256]; - for (I = 0; I < 256; I++) - { - S[I] = unchecked((byte)I); - } - for (I = J = 0; I < 256; I++) - { - J = (J + key[ki + I % klen] + S[I]) & unchecked(0xff); - byte t = S[I]; - S[I] = S[J]; - S[J] = t; - } - I = J = 0; - } - - public virtual void Update(byte[] src, int soff, int slen, byte[] dst, int doff) - { - int slim; - slim = soff + slen; - while (soff < slim) - { - I = (I + 1) & unchecked(0xff); - J = (J + S[I]) & unchecked(0xff); - byte t = S[I]; - S[I] = S[J]; - S[J] = t; - dst[doff++] = unchecked((byte)(src[soff++] ^ S[(S[I] + S[J]) & unchecked(0xff)])); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs deleted file mode 100644 index 2868a840ad..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace SharpCifs.Util.Sharpen -{ - public abstract class AbstractMap : IDictionary - { - public virtual void Clear () - { - EntrySet ().Clear (); - } - - public virtual bool ContainsKey (object name) - { - return EntrySet ().Any (p => p.Key.Equals ((T)name)); - } - - public abstract ICollection> EntrySet (); - - public virtual TU Get (object key) - { - return EntrySet ().Where (p => p.Key.Equals (key)).Select (p => p.Value).FirstOrDefault (); - } - - protected virtual IEnumerator> InternalGetEnumerator () - { - return EntrySet ().GetEnumerator (); - } - - public virtual bool IsEmpty () - { - return !EntrySet ().Any (); - } - - public virtual TU Put (T key, TU value) - { - throw new NotSupportedException (); - } - - public virtual TU Remove (object key) - { - Iterator iterator = EntrySet () as Iterator; - if (iterator == null) { - throw new NotSupportedException (); - } - while (iterator.HasNext ()) { - TU local = iterator.Next (); - if (local.Equals ((T)key)) { - iterator.Remove (); - return local; - } - } - return default(TU); - } - - void ICollection>.Add (KeyValuePair item) - { - Put (item.Key, item.Value); - } - - bool ICollection>.Contains (KeyValuePair item) - { - throw new NotImplementedException (); - } - - void ICollection>.CopyTo (KeyValuePair[] array, int arrayIndex) - { - EntrySet ().CopyTo (array, arrayIndex); - } - - bool ICollection>.Remove (KeyValuePair item) - { - Remove (item.Key); - return true; - } - - void IDictionary.Add (T key, TU value) - { - Put (key, value); - } - - bool IDictionary.ContainsKey (T key) - { - return ContainsKey (key); - } - - bool IDictionary.Remove (T key) - { - if (ContainsKey (key)) { - Remove (key); - return true; - } - return false; - } - - bool IDictionary.TryGetValue (T key, out TU value) - { - if (ContainsKey (key)) { - value = Get (key); - return true; - } - value = default(TU); - return false; - } - - IEnumerator> IEnumerable>.GetEnumerator () - { - return InternalGetEnumerator (); - } - - IEnumerator IEnumerable.GetEnumerator () - { - return InternalGetEnumerator (); - } - - public virtual int Count { - get { return EntrySet ().Count; } - } - - public TU this[T key] { - get { return Get (key); } - set { Put (key, value); } - } - - public virtual IEnumerable Keys { - get { return EntrySet ().Select (p => p.Key); } - } - - int ICollection>.Count { - get { return Count; } - } - - bool ICollection>.IsReadOnly { - get { return false; } - } - - ICollection IDictionary.Keys { - get { return Keys.ToList (); } - } - - ICollection IDictionary.Values { - get { return Values.ToList (); } - } - - public virtual IEnumerable Values { - get { return EntrySet ().Select (p => p.Value); } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs deleted file mode 100644 index b3a0a85fa8..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SharpCifs.Util.Sharpen -{ - public class Arrays - { - public static List AsList (params T[] array) - { - return array.ToList (); - } - - public static bool Equals (T[] a1, T[] a2) - { - if (a1.Length != a2.Length) { - return false; - } - return !a1.Where((t, i) => !t.Equals(a2[i])).Any(); - } - - public static void Fill (T[] array, T val) - { - Fill (array, 0, array.Length, val); - } - - public static void Fill (T[] array, int start, int end, T val) - { - for (int i = start; i < end; i++) { - array[i] = val; - } - } - - public static void Sort (string[] array) - { - Array.Sort (array, (s1,s2) => string.CompareOrdinal (s1,s2)); - } - - public static void Sort (T[] array) - { - Array.Sort (array); - } - - public static void Sort (T[] array, IComparer c) - { - Array.Sort (array, c); - } - - public static void Sort (T[] array, int start, int count) - { - Array.Sort (array, start, count); - } - - public static void Sort (T[] array, int start, int count, IComparer c) - { - Array.Sort (array, start, count, c); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs deleted file mode 100644 index b3824b0d2c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class BufferedReader : StreamReader - { - public BufferedReader (InputStreamReader r) : base(r.BaseStream) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs deleted file mode 100644 index 64a45915ad..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// BufferedWriter.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class BufferedWriter - { - StreamWriter _writer; - - public BufferedWriter (StreamWriter w) - { - _writer = w; - } - - public void Write (string s) - { - _writer.Write (s); - } - - public void NewLine () - { - _writer.WriteLine (); - } - - public void Close () - { - //Stream.`Close` method deleted - //_writer.Close (); - _writer.Dispose(); - } - } -} - diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs deleted file mode 100644 index 76ca2dc956..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal class CharBuffer : CharSequence - { - internal string Wrapped; - - public override string ToString () - { - return Wrapped; - } - - public static CharBuffer Wrap (string str) - { - CharBuffer buffer = new CharBuffer (); - buffer.Wrapped = str; - return buffer; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs deleted file mode 100644 index fa2acf7bdc..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Text; - -namespace SharpCifs.Util.Sharpen -{ - public class CharSequence - { - public static implicit operator CharSequence (string str) - { - return new StringCharSequence (str); - } - - public static implicit operator CharSequence (StringBuilder str) - { - return new StringCharSequence (str.ToString ()); - } - } - - class StringCharSequence: CharSequence - { - string _str; - - public StringCharSequence (string str) - { - this._str = str; - } - - public override string ToString () - { - return _str; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs deleted file mode 100644 index 8560a2dc24..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -// TODO: @bond Remove -namespace SharpCifs.Util.Sharpen -{ - internal static class Collections - { - static readonly IList Empty = new T [0]; - public static IList EmptySet { - get { return Empty; } - } - - } - - public static class Collections - { - public static bool AddAll (ICollection list, IEnumerable toAdd) - { - foreach (T t in toAdd) - list.Add (t); - return true; - } - - public static TV Remove (IDictionary map, TK toRemove) where TK : class - { - TV local; - if (map.TryGetValue (toRemove, out local)) { - map.Remove (toRemove); - return local; - } - return default(TV); - } - - - public static T[] ToArray (ICollection list) - { - T[] array = new T[list.Count]; - list.CopyTo (array, 0); - return array; - } - - public static T[] ToArray(List list) - { - T[] array = new T[list.Count]; - for(int c = 0; c < list.Count; c++) - { - array[c] = (T)list[c]; - } - - return array; - } - - - public static TU[] ToArray (ICollection list, TU[] res) where T:TU - { - if (res.Length < list.Count) - res = new TU [list.Count]; - - int n = 0; - foreach (T t in list) - res [n++] = t; - - if (res.Length > list.Count) - res [list.Count] = default (T); - return res; - } - - public static IDictionary EmptyMap () - { - return new Dictionary (); - } - - public static IList EmptyList () - { - return Collections.EmptySet; - } - - public static ICollection EmptySet () - { - return Collections.EmptySet; - } - - public static IList NCopies (int n, T elem) - { - List list = new List (n); - while (n-- > 0) { - list.Add (elem); - } - return list; - } - - public static void Reverse (IList list) - { - int end = list.Count - 1; - int index = 0; - while (index < end) { - T tmp = list [index]; - list [index] = list [end]; - list [end] = tmp; - ++index; - --end; - } - } - - public static ICollection Singleton (T item) - { - List list = new List (1); - list.Add (item); - return list; - } - - public static IList SingletonList (T item) - { - List list = new List (1); - list.Add (item); - return list; - } - - public static IList SynchronizedList (IList list) - { - return new SynchronizedList (list); - } - - public static ICollection UnmodifiableCollection (ICollection list) - { - return list; - } - - public static IList UnmodifiableList (IList list) - { - return new ReadOnlyCollection (list); - } - - public static ICollection UnmodifiableSet (ICollection list) - { - return list; - } - - public static IDictionary UnmodifiableMap (IDictionary dict) - { - return dict; - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs deleted file mode 100644 index 7f464ad362..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - internal class ConcurrentHashMap : AbstractMap, IConcurrentMap - { - private Dictionary _table; - - public ConcurrentHashMap () - { - _table = new Dictionary (); - } - - public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel) - { - _table = new Dictionary (initialCapacity); - } - - public override void Clear () - { - lock (_table) { - _table = new Dictionary (); - } - } - - public override bool ContainsKey (object name) - { - return _table.ContainsKey ((T)name); - } - - public override ICollection> EntrySet () - { - return this; - } - - public override TU Get (object key) - { - TU local; - _table.TryGetValue ((T)key, out local); - return local; - } - - protected override IEnumerator> InternalGetEnumerator () - { - return _table.GetEnumerator (); - } - - public override bool IsEmpty () - { - return _table.Count == 0; - } - - public override TU Put (T key, TU value) - { - lock (_table) { - TU old = Get (key); - Dictionary newTable = new Dictionary (_table); - newTable[key] = value; - _table = newTable; - return old; - } - } - - public TU PutIfAbsent (T key, TU value) - { - lock (_table) { - if (!ContainsKey (key)) { - Dictionary newTable = new Dictionary (_table); - newTable[key] = value; - _table = newTable; - return value; - } - return Get (key); - } - } - - public override TU Remove (object key) - { - lock (_table) { - TU old = Get ((T)key); - Dictionary newTable = new Dictionary (_table); - newTable.Remove ((T)key); - _table = newTable; - return old; - } - } - - public bool Remove (object key, object value) - { - lock (_table) { - if (ContainsKey (key) && value.Equals (Get (key))) { - Dictionary newTable = new Dictionary (_table); - newTable.Remove ((T)key); - _table = newTable; - return true; - } - return false; - } - } - - public bool Replace (T key, TU oldValue, TU newValue) - { - lock (_table) { - if (ContainsKey (key) && oldValue.Equals (Get (key))) { - Dictionary newTable = new Dictionary (_table); - newTable[key] = newValue; - _table = newTable; - return true; - } - return false; - } - } - - public override IEnumerable Keys { - get { return _table.Keys; } - } - - public override IEnumerable Values { - get { return _table.Values; } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs deleted file mode 100644 index 9a3b7ec4a3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Globalization; - -namespace SharpCifs.Util.Sharpen -{ - public abstract class DateFormat - { - public const int Default = 2; - - public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle) - { - return GetDateTimeInstance (dateStyle, timeStyle, CultureInfo.CurrentCulture); - } - - public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle, CultureInfo aLocale) - { - return new SimpleDateFormat (aLocale.DateTimeFormat.FullDateTimePattern, aLocale); - } - - TimeZoneInfo _timeZone; - - public abstract DateTime Parse (string value); - - public TimeZoneInfo GetTimeZone () - { - return _timeZone; - } - - public void SetTimeZone (TimeZoneInfo timeZone) - { - this._timeZone = timeZone; - } - - public abstract string Format (DateTime time); - } -} - diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs deleted file mode 100644 index f8efdde2a7..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - internal class EnumeratorWrapper : Iterator - { - object _collection; - IEnumerator _e; - T _lastVal; - bool _more; - bool _copied; - - public EnumeratorWrapper (object collection, IEnumerator e) - { - this._e = e; - this._collection = collection; - _more = e.MoveNext (); - } - - public override bool HasNext () - { - return _more; - } - - public override T Next () - { - if (!_more) - throw new NoSuchElementException (); - _lastVal = _e.Current; - _more = _e.MoveNext (); - return _lastVal; - } - - public override void Remove () - { - ICollection col = _collection as ICollection; - if (col == null) { - throw new NotSupportedException (); - } - if (_more && !_copied) { - // Read the remaining elements, since the current enumerator - // will be invalid after removing the element - List remaining = new List (); - do { - remaining.Add (_e.Current); - } while (_e.MoveNext ()); - _e = remaining.GetEnumerator (); - _e.MoveNext (); - _copied = true; - } - col.Remove (_lastVal); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs deleted file mode 100644 index ec88b28496..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs +++ /dev/null @@ -1,217 +0,0 @@ -// -// Exceptions.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -namespace SharpCifs.Util.Sharpen -{ - public class VirtualMachineError : Error - { - } - - public class StackOverflowError : VirtualMachineError - { - } - - public class BrokenBarrierException : Exception - { - } - - internal class BufferUnderflowException : Exception - { - } - - public class CharacterCodingException : Exception - { - } - - public class DataFormatException : Exception - { - } - - public class EofException : Exception - { - public EofException () - { - } - - public EofException (string msg) : base(msg) - { - } - } - - public class Error : Exception - { - public Error () - { - } - - public Error (Exception ex) : base("Runtime Exception", ex) - { - } - - public Error (string msg) : base(msg) - { - } - - public Error (string msg, Exception ex) : base(msg, ex) - { - } - } - - public class ExecutionException : Exception - { - public ExecutionException (Exception inner): base ("Execution failed", inner) - { - } - } - - public class InstantiationException : Exception - { - } - - public class InterruptedIoException : Exception - { - public InterruptedIoException (string msg) : base(msg) - { - } - } - - public class MissingResourceException : Exception - { - } - - public class NoSuchAlgorithmException : Exception - { - } - - public class NoSuchElementException : Exception - { - } - - internal class NoSuchMethodException : Exception - { - } - - internal class OverlappingFileLockException : Exception - { - } - - public class ParseException : Exception - { - public ParseException () - { - } - - public ParseException (string msg, int errorOffset) : base(string.Format ("Msg: {0}. Error Offset: {1}", msg, errorOffset)) - { - } - } - - public class RuntimeException : Exception - { - public RuntimeException () - { - } - - public RuntimeException (Exception ex) : base("Runtime Exception", ex) - { - } - - public RuntimeException (string msg) : base(msg) - { - } - - public RuntimeException (string msg, Exception ex) : base(msg, ex) - { - } - } - - internal class StringIndexOutOfBoundsException : Exception - { - } - - public class UnknownHostException : Exception - { - public UnknownHostException () - { - } - - public UnknownHostException(string message) : base(message) - { - - } - - public UnknownHostException (Exception ex): base ("Host not found", ex) - { - } - } - - public class UnsupportedEncodingException : Exception - { - } - - internal class UriSyntaxException : Exception - { - public UriSyntaxException (string s, string msg) : base(s + " " + msg) - { - } - } - - internal class ZipException : Exception - { - } - - public class GitException : Exception - { - } - - public class ConnectException: Exception - { - public ConnectException (string msg): base (msg) - { - } - } - - class KeyManagementException: Exception - { - } - - class IllegalCharsetNameException: Exception - { - public IllegalCharsetNameException (string msg): base (msg) - { - } - } - - class UnsupportedCharsetException: Exception - { - public UnsupportedCharsetException (string msg): base (msg) - { - } - } -} - diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs deleted file mode 100644 index 1716adef7a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs +++ /dev/null @@ -1,696 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -//using Windows.Networking; -//using Windows.Networking.Sockets; - -namespace SharpCifs.Util.Sharpen -{ - - - public static class Extensions - { - private static readonly long EpochTicks; - - static Extensions() - { - DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - EpochTicks = time.Ticks; - } - - public static void Add(this IList list, int index, T item) - { - list.Insert(index, item); - } - - public static void AddFirst(this IList list, T item) - { - list.Insert(0, item); - } - - public static void AddLast(this IList list, T item) - { - list.Add(item); - } - - public static void RemoveLast(this IList list) - { - if (list.Count > 0) - list.Remove(list.Count - 1); - } - - public static StringBuilder AppendRange(this StringBuilder sb, string str, int start, int end) - { - return sb.Append(str, start, end - start); - } - - public static StringBuilder Delete(this StringBuilder sb, int start, int end) - { - return sb.Remove(start, end - start); - } - - public static void SetCharAt(this StringBuilder sb, int index, char c) - { - sb[index] = c; - } - - public static int IndexOf(this StringBuilder sb, string str) - { - return sb.ToString().IndexOf(str); - } - - public static int BitCount(int val) - { - uint num = (uint)val; - int count = 0; - for (int i = 0; i < 32; i++) - { - if ((num & 1) != 0) - { - count++; - } - num >>= 1; - } - return count; - } - - public static IndexOutOfRangeException CreateIndexOutOfRangeException(int index) - { - return new IndexOutOfRangeException("Index: " + index); - } - - public static string Decode(this Encoding e, byte[] chars, int start, int len) - { - try - { - byte[] bom = e.GetPreamble(); - if (bom != null && bom.Length > 0) - { - if (len >= bom.Length) - { - int pos = start; - bool hasBom = true; - for (int n = 0; n < bom.Length && hasBom; n++) - { - if (bom[n] != chars[pos++]) - hasBom = false; - } - if (hasBom) - { - len -= pos - start; - start = pos; - } - } - } - return e.GetString(chars, start, len); - } - catch (DecoderFallbackException) - { - throw new CharacterCodingException(); - } - } - - - - public static Encoding GetEncoding(string name) - { - // Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); - try - { - - Encoding e = Encoding.GetEncoding(name.Replace('_', '-')); - if (e is UTF8Encoding) - return new UTF8Encoding(false, true); - - return e; - } - catch (ArgumentException) - { - throw new UnsupportedCharsetException(name); - } - } - - public static ICollection> EntrySet(this IDictionary s) - { - return s; - } - - - public static bool AddItem(this IList list, T item) - { - list.Add(item); - return true; - } - - public static bool AddItem(this ICollection list, T item) - { - list.Add(item); - return true; - } - - public static TU Get(this IDictionary d, T key) - { - TU val; - d.TryGetValue(key, out val); - return val; - } - - - public static TU Put(this IDictionary d, T key, TU value) - { - TU old; - d.TryGetValue(key, out old); - d[key] = value; - return old; - } - - public static void PutAll(this IDictionary d, IDictionary values) - { - foreach (KeyValuePair val in values) - d[val.Key] = val.Value; - } - - - public static CultureInfo GetEnglishCulture() - { - return new CultureInfo("en-US"); - } - - public static T GetFirst(this IList list) - { - return ((list.Count == 0) ? default(T) : list[0]); - } - - public static CultureInfo GetGermanCulture() - { - CultureInfo r = new CultureInfo("de-DE"); - return r; - } - - public static T GetLast(this IList list) - { - return ((list.Count == 0) ? default(T) : list[list.Count - 1]); - } - - public static int GetOffset(this TimeZoneInfo tzone, long date) - { - return (int)tzone.GetUtcOffset(MillisToDateTimeOffset(date, 0).DateTime).TotalMilliseconds; - } - - public static long GetTime(this DateTime dateTime) - { - return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch(); - } - - public static void InitCause(this Exception ex, Exception cause) - { - Console.WriteLine(cause); - } - - public static bool IsEmpty(this ICollection col) - { - return (col.Count == 0); - } - - public static bool IsEmpty(this Stack col) - { - return (col.Count == 0); - } - - public static bool IsLower(this char c) - { - return char.IsLower(c); - } - - public static bool IsUpper(this char c) - { - return char.IsUpper(c); - } - - public static Iterator Iterator(this ICollection col) - { - return new EnumeratorWrapper(col, col.GetEnumerator()); - } - - public static Iterator Iterator(this IEnumerable col) - { - return new EnumeratorWrapper(col, col.GetEnumerator()); - } - - public static T Last(this ICollection col) - { - IList list = col as IList; - if (list != null) - { - return list[list.Count - 1]; - } - return col.Last(); - } - - public static int LowestOneBit(int val) - { - return (1 << NumberOfTrailingZeros(val)); - } - - public static bool Matches(this string str, string regex) - { - Regex regex2 = new Regex(regex); - return regex2.IsMatch(str); - } - - public static DateTime CreateDate(long milliSecondsSinceEpoch) - { - long num = EpochTicks + (milliSecondsSinceEpoch * 10000); - return new DateTime(num); - } - - public static DateTime CreateDateFromUTC(long milliSecondsSinceEpoch) - { - long num = EpochTicks + (milliSecondsSinceEpoch * 10000); - return new DateTime(num, DateTimeKind.Utc); - } - - - public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, long offsetMinutes) - { - TimeSpan offset = TimeSpan.FromMinutes(offsetMinutes); - long num = EpochTicks + (milliSecondsSinceEpoch * 10000); - return new DateTimeOffset(num + offset.Ticks, offset); - } - - public static int NumberOfLeadingZeros(int val) - { - uint num = (uint)val; - int count = 0; - while ((num & 0x80000000) == 0) - { - num = num << 1; - count++; - } - return count; - } - - public static int NumberOfTrailingZeros(int val) - { - uint num = (uint)val; - int count = 0; - while ((num & 1) == 0) - { - num = num >> 1; - count++; - } - return count; - } - - public static int Read(this StreamReader reader, char[] data) - { - return reader.Read(data, 0, data.Length); - } - - public static T Remove(this IList list, T item) - { - int index = list.IndexOf(item); - if (index == -1) - { - return default(T); - } - T local = list[index]; - list.RemoveAt(index); - return local; - } - - public static T Remove(this IList list, int i) - { - T old; - try - { - old = list[i]; - list.RemoveAt(i); - } - catch (IndexOutOfRangeException) - { - throw new NoSuchElementException(); - } - return old; - } - - public static T RemoveFirst(this IList list) - { - return list.Remove(0); - } - - public static string ReplaceAll(this string str, string regex, string replacement) - { - Regex rgx = new Regex(regex); - - if (replacement.IndexOfAny(new[] { '\\', '$' }) != -1) - { - // Back references not yet supported - StringBuilder sb = new StringBuilder(); - for (int n = 0; n < replacement.Length; n++) - { - char c = replacement[n]; - if (c == '$') - throw new NotSupportedException("Back references not supported"); - if (c == '\\') - c = replacement[++n]; - sb.Append(c); - } - replacement = sb.ToString(); - } - - return rgx.Replace(str, replacement); - } - - public static bool RegionMatches(this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len) - { - if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length) - return false; - return string.Compare(str, toOffset, other, ooffset, len) == 0; - } - - public static T Set(this IList list, int index, T item) - { - T old = list[index]; - list[index] = item; - return old; - } - - public static int Signum(long val) - { - if (val < 0) - { - return -1; - } - if (val > 0) - { - return 1; - } - return 0; - } - - public static void RemoveAll(this ICollection col, ICollection items) where TU : T - { - foreach (var u in items) - col.Remove(u); - } - - public static bool ContainsAll(this ICollection col, ICollection items) where TU : T - { - foreach (var u in items) - if (!col.Any(n => (ReferenceEquals(n, u)) || n.Equals(u))) - return false; - return true; - } - - public static bool Contains(this ICollection col, object item) - { - if (!(item is T)) - return false; - return col.Any(n => (ReferenceEquals(n, item)) || n.Equals(item)); - } - - public static void Sort(this IList list) - { - List sorted = new List(list); - sorted.Sort(); - for (int i = 0; i < list.Count; i++) - { - list[i] = sorted[i]; - } - } - - public static void Sort(this IList list, IComparer comparer) - { - List sorted = new List(list); - sorted.Sort(comparer); - for (int i = 0; i < list.Count; i++) - { - list[i] = sorted[i]; - } - } - - public static string[] Split(this string str, string regex) - { - return str.Split(regex, 0); - } - - public static string[] Split(this string str, string regex, int limit) - { - Regex rgx = new Regex(regex); - List list = new List(); - int startIndex = 0; - if (limit != 1) - { - int nm = 1; - foreach (Match match in rgx.Matches(str)) - { - list.Add(str.Substring(startIndex, match.Index - startIndex)); - startIndex = match.Index + match.Length; - if (limit > 0 && ++nm == limit) - break; - } - } - if (startIndex < str.Length) - { - list.Add(str.Substring(startIndex)); - } - if (limit >= 0) - { - int count = list.Count - 1; - while ((count >= 0) && (list[count].Length == 0)) - { - count--; - } - list.RemoveRange(count + 1, (list.Count - count) - 1); - } - return list.ToArray(); - } - - public static IList SubList(this IList list, int start, int len) - { - List sublist = new List(len); - for (int i = start; i < (start + len); i++) - { - sublist.Add(list[i]); - } - return sublist; - } - - public static char[] ToCharArray(this string str) - { - char[] destination = new char[str.Length]; - str.CopyTo(0, destination, 0, str.Length); - return destination; - } - - public static long ToMillisecondsSinceEpoch(this DateTime dateTime) - { - if (dateTime.Kind != DateTimeKind.Utc) - { - throw new ArgumentException("dateTime is expected to be expressed as a UTC DateTime", "dateTime"); - } - return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch(); - } - - public static long ToMillisecondsSinceEpoch(this DateTimeOffset dateTimeOffset) - { - return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) / TimeSpan.TicksPerMillisecond); - } - - public static string ToOctalString(int val) - { - return Convert.ToString(val, 8); - } - - public static string ToHexString(int val) - { - return Convert.ToString(val, 16); - } - - public static string ToString(object val) - { - return val.ToString(); - } - - public static string ToString(int val, int bas) - { - return Convert.ToString(val, bas); - } - - public static IList UpcastTo(this IList s) where T : TU - { - List list = new List(s.Count); - for (int i = 0; i < s.Count; i++) - { - list.Add(s[i]); - } - return list; - } - - public static ICollection UpcastTo(this ICollection s) where T : TU - { - List list = new List(s.Count); - foreach (var v in s) - { - list.Add(v); - } - return list; - } - - public static T ValueOf(T val) - { - return val; - } - - - //use? for NUnit-testing? - //public static string GetTestName(object obj) - //{ - // return GetTestName(); - //} - - //public static string GetTestName() - //{ - // MethodBase met; - // int n = 0; - // do - // { - // met = new StackFrame(n).GetMethod(); - // if (met != null) - // { - // foreach (Attribute at in met.GetCustomAttributes(true)) - // { - // if (at.GetType().FullName == "NUnit.Framework.TestAttribute") - // { - // // Convert back to camel case - // string name = met.Name; - // if (char.IsUpper(name[0])) - // name = char.ToLower(name[0]) + name.Substring(1); - // return name; - // } - // } - // } - // n++; - // } while (met != null); - // return ""; - //} - - public static string GetHostAddress(this IPAddress addr) - { - return addr.ToString(); - } - - - public static IPAddress GetAddressByName(string host) - { - if (host == "0.0.0.0") - { - return IPAddress.Any; - } - - try - { - return IPAddress.Parse(host); - } - catch (Exception ex) - { - return null; - } - } - - public static IPAddress[] GetAddressesByName(string host) - { - //IReadOnlyList data = null; - - //try - //{ - // Task.Run(async () => - // { - // data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0"); - // }).Wait(); - //} - //catch (Exception ex) - //{ - // return null; - //} - - //return data != null - // ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4) - // .GroupBy(i => i.RemoteHostName.DisplayName) - // .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName)) - // .ToArray() - // : null; - - //get v4-address only - var entry = Task.Run(() => System.Net.Dns.GetHostEntryAsync(host)) - .GetAwaiter() - .GetResult(); - return entry.AddressList - .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork) - .ToArray(); - - } - - public static string GetImplementationVersion(this Assembly asm) - { - return asm.GetName().Version.ToString(); - } - - public static string GetHost(this Uri uri) - { - return string.IsNullOrEmpty(uri.Host) ? "" : uri.Host; - } - - public static string GetUserInfo(this Uri uri) - { - return string.IsNullOrEmpty(uri.UserInfo) ? null : uri.UserInfo; - } - - public static string GetQuery(this Uri uri) - { - return string.IsNullOrEmpty(uri.Query) ? null : uri.Query; - } - - public static int GetLocalPort(this Socket socket) - { - return ((IPEndPoint)socket.LocalEndPoint).Port; - } - - public static int GetPort(this Socket socket) - { - return ((IPEndPoint)socket.RemoteEndPoint).Port; - } - - public static IPAddress GetInetAddress(this Socket socket) - { - return ((IPEndPoint)socket.RemoteEndPoint).Address; - } - - - /*public static bool RemoveElement(this ArrayList list, object elem) - { - int i = list.IndexOf(elem); - if (i == -1) - return false; - list.RemoveAt(i); - return true; - }*/ - - public static Semaphore CreateSemaphore(int count) - { - return new Semaphore(count, int.MaxValue); - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs deleted file mode 100644 index 25c5e06e07..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class FileInputStream : InputStream - { - public FileInputStream (FilePath file) : this(file.GetPath ()) - { - } - - public FileInputStream (string file) - { - if (!File.Exists (file)) { - throw new FileNotFoundException ("File not found", file); - } - Wrapped = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs deleted file mode 100644 index bf80294886..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - internal class FileOutputStream : OutputStream - { - public FileOutputStream (FilePath file): this (file.GetPath (), false) - { - } - - public FileOutputStream (string file): this (file, false) - { - } - - public FileOutputStream (FilePath file, bool append) : this(file.GetPath (), append) - { - } - - public FileOutputStream (string file, bool append) - { - try { - if (append) { - Wrapped = File.Open (file, FileMode.Append, FileAccess.Write); - } else { - Wrapped = File.Open (file, FileMode.Create, FileAccess.Write); - } - } catch (DirectoryNotFoundException) { - throw new FileNotFoundException ("File not found: " + file); - } - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs deleted file mode 100644 index 1b2f5eddcd..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs +++ /dev/null @@ -1,313 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - public class FilePath - { - private string _path; - private static long _tempCounter; - - public FilePath () - { - } - - public FilePath (string path) - : this ((string) null, path) - { - - } - - public FilePath (FilePath other, string child) - : this ((string) other, child) - { - - } - - public FilePath (string other, string child) - { - if (other == null) { - _path = child; - } else { - while (!string.IsNullOrEmpty(child) && (child[0] == Path.DirectorySeparatorChar || child[0] == Path.AltDirectorySeparatorChar)) - child = child.Substring (1); - - if (!string.IsNullOrEmpty(other) && other[other.Length - 1] == Path.VolumeSeparatorChar) - other += Path.DirectorySeparatorChar; - - _path = Path.Combine (other, child); - } - } - - public static implicit operator FilePath (string name) - { - return new FilePath (name); - } - - public static implicit operator string (FilePath filePath) - { - return filePath == null ? null : filePath._path; - } - - public override bool Equals (object obj) - { - FilePath other = obj as FilePath; - if (other == null) - return false; - return GetCanonicalPath () == other.GetCanonicalPath (); - } - - public override int GetHashCode () - { - return _path.GetHashCode (); - } - - public bool CreateNewFile () - { - try { - //Stream.`Close` method deleted - //File.Open (_path, FileMode.CreateNew).Close (); - File.Open(_path, FileMode.CreateNew).Dispose(); - return true; - } catch { - return false; - } - } - - public static FilePath CreateTempFile () - { - return new FilePath (Path.GetTempFileName ()); - } - - public static FilePath CreateTempFile (string prefix, string suffix) - { - return CreateTempFile (prefix, suffix, null); - } - - public static FilePath CreateTempFile (string prefix, string suffix, FilePath directory) - { - string file; - if (prefix == null) { - throw new ArgumentNullException ("prefix"); - } - if (prefix.Length < 3) { - throw new ArgumentException ("prefix must have at least 3 characters"); - } - string str = (directory == null) ? Path.GetTempPath () : directory.GetPath (); - do { - file = Path.Combine (str, prefix + Interlocked.Increment (ref _tempCounter) + suffix); - } while (File.Exists (file)); - - new FileOutputStream (file).Close (); - return new FilePath (file); - } - - - public void DeleteOnExit () - { - } - - - public FilePath GetAbsoluteFile () - { - return new FilePath (Path.GetFullPath (_path)); - } - - public string GetAbsolutePath () - { - return Path.GetFullPath (_path); - } - - public FilePath GetCanonicalFile () - { - return new FilePath (GetCanonicalPath ()); - } - - public string GetCanonicalPath () - { - string p = Path.GetFullPath (_path); - p.TrimEnd (Path.DirectorySeparatorChar); - return p; - } - - public string GetName () - { - return Path.GetFileName (_path); - } - - public FilePath GetParentFile () - { - return new FilePath (Path.GetDirectoryName (_path)); - } - - public string GetPath () - { - return _path; - } - - public bool IsAbsolute () - { - return Path.IsPathRooted (_path); - } - - public bool IsDirectory () - { - return false; // FileHelper.Instance.IsDirectory(this); - } - - public bool IsFile () - { - return false; //FileHelper.Instance.IsFile (this); - } - - public long LastModified () - { - return 0; // FileHelper.Instance.LastModified(this); - } - - public long Length () - { - return 0; // FileHelper.Instance.Length(this); - } - - public string[] List () - { - return List (null); - } - - public string[] List (IFilenameFilter filter) - { - try { - if (IsFile ()) - return null; - List list = new List (); - foreach (string filePth in Directory.GetFileSystemEntries (_path)) { - string fileName = Path.GetFileName (filePth); - if ((filter == null) || filter.Accept (this, fileName)) { - list.Add (fileName); - } - } - return list.ToArray (); - } catch { - return null; - } - } - - public FilePath[] ListFiles () - { - try { - if (IsFile ()) - return null; - List list = new List (); - foreach (string filePath in Directory.GetFileSystemEntries (_path)) { - list.Add (new FilePath (filePath)); - } - return list.ToArray (); - } catch { - return null; - } - } - - static void MakeDirWritable (string dir) - { - //FileHelper.Instance.MakeDirWritable (dir); - } - - static void MakeFileWritable (string file) - { - //FileHelper.Instance.MakeFileWritable (file); - } - - public bool Mkdir () - { - try { - if (Directory.Exists (_path)) - return false; - Directory.CreateDirectory (_path); - return true; - } catch (Exception) { - return false; - } - } - - public bool Mkdirs () - { - try { - if (Directory.Exists (_path)) - return false; - Directory.CreateDirectory (_path); - return true; - } catch { - return false; - } - } - - public bool RenameTo (FilePath file) - { - return RenameTo (file._path); - } - - public bool RenameTo (string name) - { - return false; // FileHelper.Instance.RenameTo(this, name); - } - - public bool SetLastModified (long milis) - { - return false; // FileHelper.Instance.SetLastModified(this, milis); - } - - public bool SetReadOnly () - { - return false; // FileHelper.Instance.SetReadOnly(this); - } - - public Uri ToUri () - { - return new Uri (_path); - } - - // Don't change the case of this method, since ngit does reflection on it - public bool CanExecute () - { - return false; // FileHelper.Instance.CanExecute(this); - } - - // Don't change the case of this method, since ngit does reflection on it - public bool SetExecutable (bool exec) - { - return false; // FileHelper.Instance.SetExecutable(this, exec); - } - - public string GetParent () - { - string p = Path.GetDirectoryName (_path); - if (string.IsNullOrEmpty(p) || p == _path) - return null; - return p; - } - - public override string ToString () - { - return _path; - } - - static internal string PathSeparator { - get { return Path.PathSeparator.ToString (); } - } - - static internal char PathSeparatorChar { - get { return Path.PathSeparator; } - } - - static internal char SeparatorChar { - get { return Path.DirectorySeparatorChar; } - } - - static internal string Separator { - get { return Path.DirectorySeparatorChar.ToString (); } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs deleted file mode 100644 index 7a0c1f90e1..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public class FileReader : InputStreamReader - { - //public FileReader (FilePath f) : base(f.GetPath ()) - //{ - //} - //path -> fileStream - public FileReader(InputStream s) : base(s) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs deleted file mode 100644 index 0675c238bc..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FileWriter.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - //resharper said, nobody using this. i believe it. - //internal class FileWriter : StreamWriter - //{ - // public FileWriter (FilePath path) : base(path.GetPath ()) - // { - // } - - // public FileWriter Append (string sequence) - // { - // Write (sequence); - // return this; - // } - //} -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs deleted file mode 100644 index dfc0ba2641..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public class FilterInputStream : InputStream - { - protected InputStream In; - - public FilterInputStream (InputStream s) - { - In = s; - } - - public override int Available () - { - return In.Available (); - } - - public override void Close () - { - In.Close (); - } - - public override void Mark (int readlimit) - { - In.Mark (readlimit); - } - - public override bool MarkSupported () - { - return In.MarkSupported (); - } - - public override int Read () - { - return In.Read (); - } - - public override int Read (byte[] buf) - { - return In.Read (buf); - } - - public override int Read (byte[] b, int off, int len) - { - return In.Read (b, off, len); - } - - public override void Reset () - { - In.Reset (); - } - - public override long Skip (long cnt) - { - return In.Skip (cnt); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs deleted file mode 100644 index 4863105ed6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public class FilterOutputStream : OutputStream - { - protected OutputStream Out; - - public FilterOutputStream (OutputStream os) - { - Out = os; - } - - public override void Close () - { - Out.Close (); - } - - public override void Flush () - { - Out.Flush (); - } - - public override void Write (byte[] b) - { - Out.Write (b); - } - - public override void Write (int b) - { - Out.Write (b); - } - - public override void Write (byte[] b, int offset, int len) - { - Out.Write (b, offset, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs deleted file mode 100644 index c2c53485dc..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace SharpCifs.Util.Sharpen -{ - public class Hashtable : Dictionary - { - public void Put(object key, object value) - { - Add(key, value); - } - - public object Get(object key) - { - var m_key = Keys.SingleOrDefault(k => k.Equals(key)); - - return m_key != null ? this[m_key] : null; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs deleted file mode 100644 index ace314eee4..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// HttpURLConnection.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -namespace SharpCifs.Util.Sharpen -{ - public class UrlConnection - { - protected Uri Url; - } - -} - diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs deleted file mode 100644 index d847cb497a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal interface ICallable - { - T Call (); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs deleted file mode 100644 index dead242443..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - internal interface IConcurrentMap : IDictionary - { - TU PutIfAbsent (T key, TU value); - bool Remove (object key, object value); - bool Replace (T key, TU oldValue, TU newValue); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs deleted file mode 100644 index 5f76c2ed57..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public interface IExecutor - { - void Execute (IRunnable runnable); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs deleted file mode 100644 index fe2eb6a3d6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public interface IFilenameFilter - { - bool Accept (FilePath dir, string name); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs deleted file mode 100644 index 5215e45028..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal interface IFuture - { - bool Cancel (bool mayInterruptIfRunning); - T Get (); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs deleted file mode 100644 index 4a5e92f9b5..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal interface IPrivilegedAction - { - T Run (); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs deleted file mode 100644 index 7f6ae5533d..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public interface IRunnable - { - void Run (); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs deleted file mode 100644 index 2f3f070b50..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class InputStream : IDisposable - { - private long _mark; - protected Stream Wrapped; - protected Stream BaseStream; - - public static implicit operator InputStream (Stream s) - { - return Wrap (s); - } - - public static implicit operator Stream (InputStream s) - { - return s.GetWrappedStream (); - } - - public virtual int Available () - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Available (); - return 0; - } - - public virtual void Close () - { - if (Wrapped != null) { - //Stream.`Close` method deleted - //Wrapped.Close (); - Wrapped.Dispose(); - } - } - - public void Dispose () - { - Close (); - } - - internal Stream GetWrappedStream () - { - // Always create a wrapper stream (not directly Wrapped) since the subclass - // may be overriding methods that need to be called when used through the Stream class - return new WrappedSystemStream (this); - } - - public virtual void Mark (int readlimit) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).InputStream.Mark (readlimit); - else { - if (BaseStream is WrappedSystemStream) - ((WrappedSystemStream)BaseStream).OnMark (readlimit); - if (Wrapped != null) - _mark = Wrapped.Position; - } - } - - public virtual bool MarkSupported () - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.MarkSupported (); - return ((Wrapped != null) && Wrapped.CanSeek); - } - - public virtual int Read () - { - if (Wrapped == null) { - throw new NotImplementedException (); - } - return Wrapped.ReadByte (); - } - - public virtual int Read (byte[] buf) - { - return Read (buf, 0, buf.Length); - } - - public virtual int Read (byte[] b, int off, int len) - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Read (b, off, len); - - if (Wrapped != null) { - int num = Wrapped.Read (b, off, len); - return ((num <= 0) ? -1 : num); - } - int totalRead = 0; - while (totalRead < len) { - int nr = Read (); - if (nr == -1) - return -1; - b[off + totalRead] = (byte)nr; - totalRead++; - } - return totalRead; - } - - public virtual void Reset () - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).InputStream.Reset (); - else { - if (Wrapped == null) - throw new IOException (); - Wrapped.Position = _mark; - } - } - - public virtual long Skip (long cnt) - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Skip (cnt); - - long n = cnt; - while (n > 0) { - if (Read () == -1) - return cnt - n; - n--; - } - return cnt - n; - } - - internal virtual bool CanSeek () - { - if (Wrapped != null) - return Wrapped.CanSeek; - return false; - } - - internal virtual long Position { - get - { - if (Wrapped != null) - return Wrapped.Position; - throw new NotSupportedException (); - } - set { - if (Wrapped != null) - Wrapped.Position = value; - else - throw new NotSupportedException (); - } - } - - public virtual long Length - { - get - { - if (Wrapped != null) - { - return Wrapped.Length; - } - - throw new NotSupportedException(); - } - } - - static internal InputStream Wrap (Stream s) - { - InputStream stream = new InputStream (); - stream.Wrapped = s; - return stream; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs deleted file mode 100644 index f9f1983b83..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.IO; -using System.Text; - -namespace SharpCifs.Util.Sharpen -{ - public class InputStreamReader : StreamReader - { - //Stream(string path) constructor deleted - //protected InputStreamReader (string file) : base(file) - //{ - //} - - public InputStreamReader (InputStream s) : base(s.GetWrappedStream ()) - { - } - - public InputStreamReader (InputStream s, string encoding) : base(s.GetWrappedStream (), Encoding.GetEncoding (encoding)) - { - } - - public InputStreamReader (InputStream s, Encoding e) : base(s.GetWrappedStream (), e) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs deleted file mode 100644 index 634c7b404e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - public interface ITerator - { - bool HasNext (); - object Next (); - void Remove (); - } - - public abstract class Iterator : IEnumerator, ITerator - { - private T _lastValue; - - object ITerator.Next () - { - return Next (); - } - - public abstract bool HasNext (); - public abstract T Next (); - public abstract void Remove (); - - bool IEnumerator.MoveNext () - { - if (HasNext ()) { - _lastValue = Next (); - return true; - } - return false; - } - - void IEnumerator.Reset () - { - throw new NotImplementedException (); - } - - void IDisposable.Dispose () - { - } - - T IEnumerator.Current { - get { return _lastValue; } - } - - object IEnumerator.Current { - get { return _lastValue; } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs deleted file mode 100644 index 9f4970bddf..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace SharpCifs.Util.Sharpen -{ - internal class LinkageError : Exception - { - public LinkageError (string msg) : base(msg) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs deleted file mode 100644 index 50f3fa43b2..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs +++ /dev/null @@ -1,275 +0,0 @@ -//Copyright (c) Microsoft Corporation. All rights reserved. - -using System; -using System.Text; - -namespace SharpCifs.Util.Sharpen -{ // ************************************************************** -// * Raw implementation of the MD5 hash algorithm -// * from RFC 1321. -// * -// * Written By: Reid Borsuk and Jenny Zheng -// * Copyright (c) Microsoft Corporation. All rights reserved. -// ************************************************************** - -// Simple struct for the (a,b,c,d) which is used to compute the mesage digest. - struct AbcdStruct - { - public uint A; - public uint B; - public uint C; - public uint D; - } - - public sealed class Md5Core - { - //Prevent CSC from adding a default public constructor - private Md5Core() { } - - public static byte[] GetHash(string input, Encoding encoding) - { - if (null == input) - throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); - if (null == encoding) - throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding"); - - byte[] target = encoding.GetBytes(input); - - return GetHash(target); - } - - public static byte[] GetHash(string input) - { - return GetHash(input, new UTF8Encoding()); - } - - public static string GetHashString(byte[] input) - { - if (null == input) - throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); - - string retval = BitConverter.ToString(GetHash(input)); - retval = retval.Replace("-", ""); - - return retval; - } - - public static string GetHashString(string input, Encoding encoding) - { - if (null == input) - throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); - if (null == encoding) - throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHashString(string) overload to use UTF8 Encoding"); - - byte[] target = encoding.GetBytes(input); - - return GetHashString(target); - } - - public static string GetHashString(string input) - { - return GetHashString(input, new UTF8Encoding()); - } - - public static byte[] GetHash(byte[] input) - { - if (null == input) - throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); - - //Intitial values defined in RFC 1321 - AbcdStruct abcd = new AbcdStruct(); - abcd.A = 0x67452301; - abcd.B = 0xefcdab89; - abcd.C = 0x98badcfe; - abcd.D = 0x10325476; - - //We pass in the input array by block, the final block of data must be handled specialy for padding & length embeding - int startIndex = 0; - while (startIndex <= input.Length - 64) - { - GetHashBlock(input, ref abcd, startIndex); - startIndex += 64; - } - // The final data block. - return GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64)input.Length * 8); - } - - internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, AbcdStruct abcd, Int64 len) - { - byte[] working = new byte[64]; - byte[] length = BitConverter.GetBytes(len); - - //Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321 - //The CLR ensures that our buffer is 0-assigned, we don't need to explicitly set it. This is why it ends up being quicker to just - //use a temporary array rather then doing in-place assignment (5% for small inputs) - Array.Copy(input, ibStart, working, 0, cbSize); - working[cbSize] = 0x80; - - //We have enough room to store the length in this chunk - if (cbSize < 56) - { - Array.Copy(length, 0, working, 56, 8); - GetHashBlock(working, ref abcd, 0); - } - else //We need an aditional chunk to store the length - { - GetHashBlock(working, ref abcd, 0); - //Create an entirely new chunk due to the 0-assigned trick mentioned above, to avoid an extra function call clearing the array - working = new byte[64]; - Array.Copy(length, 0, working, 56, 8); - GetHashBlock(working, ref abcd, 0); - } - byte[] output = new byte[16]; - Array.Copy(BitConverter.GetBytes(abcd.A), 0, output, 0, 4); - Array.Copy(BitConverter.GetBytes(abcd.B), 0, output, 4, 4); - Array.Copy(BitConverter.GetBytes(abcd.C), 0, output, 8, 4); - Array.Copy(BitConverter.GetBytes(abcd.D), 0, output, 12, 4); - return output; - } - - // Performs a single block transform of MD5 for a given set of ABCD inputs - /* If implementing your own hashing framework, be sure to set the initial ABCD correctly according to RFC 1321: - // A = 0x67452301; - // B = 0xefcdab89; - // C = 0x98badcfe; - // D = 0x10325476; - */ - internal static void GetHashBlock(byte[] input, ref AbcdStruct abcdValue, int ibStart) - { - uint[] temp = Converter(input, ibStart); - uint a = abcdValue.A; - uint b = abcdValue.B; - uint c = abcdValue.C; - uint d = abcdValue.D; - - a = R1(a, b, c, d, temp[0], 7, 0xd76aa478); - d = R1(d, a, b, c, temp[1], 12, 0xe8c7b756); - c = R1(c, d, a, b, temp[2], 17, 0x242070db); - b = R1(b, c, d, a, temp[3], 22, 0xc1bdceee); - a = R1(a, b, c, d, temp[4], 7, 0xf57c0faf); - d = R1(d, a, b, c, temp[5], 12, 0x4787c62a); - c = R1(c, d, a, b, temp[6], 17, 0xa8304613); - b = R1(b, c, d, a, temp[7], 22, 0xfd469501); - a = R1(a, b, c, d, temp[8], 7, 0x698098d8); - d = R1(d, a, b, c, temp[9], 12, 0x8b44f7af); - c = R1(c, d, a, b, temp[10], 17, 0xffff5bb1); - b = R1(b, c, d, a, temp[11], 22, 0x895cd7be); - a = R1(a, b, c, d, temp[12], 7, 0x6b901122); - d = R1(d, a, b, c, temp[13], 12, 0xfd987193); - c = R1(c, d, a, b, temp[14], 17, 0xa679438e); - b = R1(b, c, d, a, temp[15], 22, 0x49b40821); - - a = R2(a, b, c, d, temp[1], 5, 0xf61e2562); - d = R2(d, a, b, c, temp[6], 9, 0xc040b340); - c = R2(c, d, a, b, temp[11], 14, 0x265e5a51); - b = R2(b, c, d, a, temp[0], 20, 0xe9b6c7aa); - a = R2(a, b, c, d, temp[5], 5, 0xd62f105d); - d = R2(d, a, b, c, temp[10], 9, 0x02441453); - c = R2(c, d, a, b, temp[15], 14, 0xd8a1e681); - b = R2(b, c, d, a, temp[4], 20, 0xe7d3fbc8); - a = R2(a, b, c, d, temp[9], 5, 0x21e1cde6); - d = R2(d, a, b, c, temp[14], 9, 0xc33707d6); - c = R2(c, d, a, b, temp[3], 14, 0xf4d50d87); - b = R2(b, c, d, a, temp[8], 20, 0x455a14ed); - a = R2(a, b, c, d, temp[13], 5, 0xa9e3e905); - d = R2(d, a, b, c, temp[2], 9, 0xfcefa3f8); - c = R2(c, d, a, b, temp[7], 14, 0x676f02d9); - b = R2(b, c, d, a, temp[12], 20, 0x8d2a4c8a); - - a = R3(a, b, c, d, temp[5], 4, 0xfffa3942); - d = R3(d, a, b, c, temp[8], 11, 0x8771f681); - c = R3(c, d, a, b, temp[11], 16, 0x6d9d6122); - b = R3(b, c, d, a, temp[14], 23, 0xfde5380c); - a = R3(a, b, c, d, temp[1], 4, 0xa4beea44); - d = R3(d, a, b, c, temp[4], 11, 0x4bdecfa9); - c = R3(c, d, a, b, temp[7], 16, 0xf6bb4b60); - b = R3(b, c, d, a, temp[10], 23, 0xbebfbc70); - a = R3(a, b, c, d, temp[13], 4, 0x289b7ec6); - d = R3(d, a, b, c, temp[0], 11, 0xeaa127fa); - c = R3(c, d, a, b, temp[3], 16, 0xd4ef3085); - b = R3(b, c, d, a, temp[6], 23, 0x04881d05); - a = R3(a, b, c, d, temp[9], 4, 0xd9d4d039); - d = R3(d, a, b, c, temp[12], 11, 0xe6db99e5); - c = R3(c, d, a, b, temp[15], 16, 0x1fa27cf8); - b = R3(b, c, d, a, temp[2], 23, 0xc4ac5665); - - a = R4(a, b, c, d, temp[0], 6, 0xf4292244); - d = R4(d, a, b, c, temp[7], 10, 0x432aff97); - c = R4(c, d, a, b, temp[14], 15, 0xab9423a7); - b = R4(b, c, d, a, temp[5], 21, 0xfc93a039); - a = R4(a, b, c, d, temp[12], 6, 0x655b59c3); - d = R4(d, a, b, c, temp[3], 10, 0x8f0ccc92); - c = R4(c, d, a, b, temp[10], 15, 0xffeff47d); - b = R4(b, c, d, a, temp[1], 21, 0x85845dd1); - a = R4(a, b, c, d, temp[8], 6, 0x6fa87e4f); - d = R4(d, a, b, c, temp[15], 10, 0xfe2ce6e0); - c = R4(c, d, a, b, temp[6], 15, 0xa3014314); - b = R4(b, c, d, a, temp[13], 21, 0x4e0811a1); - a = R4(a, b, c, d, temp[4], 6, 0xf7537e82); - d = R4(d, a, b, c, temp[11], 10, 0xbd3af235); - c = R4(c, d, a, b, temp[2], 15, 0x2ad7d2bb); - b = R4(b, c, d, a, temp[9], 21, 0xeb86d391); - - abcdValue.A = unchecked(a + abcdValue.A); - abcdValue.B = unchecked(b + abcdValue.B); - abcdValue.C = unchecked(c + abcdValue.C); - abcdValue.D = unchecked(d + abcdValue.D); - } - - //Manually unrolling these equations nets us a 20% performance improvement - private static uint R1(uint a, uint b, uint c, uint d, uint x, int s, uint t) - { - // (b + LSR((a + F(b, c, d) + x + t), s)) - //F(x, y, z) ((x & y) | ((x ^ 0xFFFFFFFF) & z)) - return unchecked(b + Lsr((a + ((b & c) | ((b ^ 0xFFFFFFFF) & d)) + x + t), s)); - } - - private static uint R2(uint a, uint b, uint c, uint d, uint x, int s, uint t) - { - // (b + LSR((a + G(b, c, d) + x + t), s)) - //G(x, y, z) ((x & z) | (y & (z ^ 0xFFFFFFFF))) - return unchecked(b + Lsr((a + ((b & d) | (c & (d ^ 0xFFFFFFFF))) + x + t), s)); - } - - private static uint R3(uint a, uint b, uint c, uint d, uint x, int s, uint t) - { - // (b + LSR((a + H(b, c, d) + k + i), s)) - //H(x, y, z) (x ^ y ^ z) - return unchecked(b + Lsr((a + (b ^ c ^ d) + x + t), s)); - } - - private static uint R4(uint a, uint b, uint c, uint d, uint x, int s, uint t) - { - // (b + LSR((a + I(b, c, d) + k + i), s)) - //I(x, y, z) (y ^ (x | (z ^ 0xFFFFFFFF))) - return unchecked(b + Lsr((a + (c ^ (b | (d ^ 0xFFFFFFFF))) + x + t), s)); - } - - // Implementation of left rotate - // s is an int instead of a uint becuase the CLR requires the argument passed to >>/<< is of - // type int. Doing the demoting inside this function would add overhead. - private static uint Lsr(uint i, int s) - { - return ((i << s) | (i >> (32 - s))); - } - - //Convert input array into array of UInts - private static uint[] Converter(byte[] input, int ibStart) - { - if (null == input) - throw new ArgumentNullException("input", "Unable convert null array to array of uInts"); - - uint[] result = new uint[16]; - - for (int i = 0; i < 16; i++) - { - result[i] = input[ibStart + i * 4]; - result[i] += (uint)input[ibStart + i * 4 + 1] << 8; - result[i] += (uint)input[ibStart + i * 4 + 2] << 16; - result[i] += (uint)input[ibStart + i * 4 + 3] << 24; - } - - return result; - } - } -} \ No newline at end of file diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs deleted file mode 100644 index e74a05abf3..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MD5Managed.cs +++ /dev/null @@ -1,91 +0,0 @@ -//Copyright (c) Microsoft Corporation. All rights reserved. - -using System; -using System.Security.Cryptography; - -// ************************************************************** -// * Raw implementation of the MD5 hash algorithm -// * from RFC 1321. -// * -// * Written By: Reid Borsuk and Jenny Zheng -// * Copyright (c) Microsoft Corporation. All rights reserved. -// ************************************************************** - - -#if SILVERLIGHT -#else -//public class MD5Managed : MD5 -#endif -namespace SharpCifs.Util.Sharpen -{ - public class Md5Managed : HashAlgorithm - - { - public static Md5Managed Create() - { - return new Md5Managed(); - } - - private byte[] _data; - private AbcdStruct _abcd; - private Int64 _totalLength; - private int _dataSize; - - public Md5Managed() - { - //field cannot access - //HashSizeValue = 0x80; - Initialize(); - } - - public override void Initialize() - { - _data = new byte[64]; - _dataSize = 0; - _totalLength = 0; - _abcd = new AbcdStruct(); - //Intitial values as defined in RFC 1321 - _abcd.A = 0x67452301; - _abcd.B = 0xefcdab89; - _abcd.C = 0x98badcfe; - _abcd.D = 0x10325476; - } - - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - int startIndex = ibStart; - int totalArrayLength = _dataSize + cbSize; - if (totalArrayLength >= 64) - { - Array.Copy(array, startIndex, _data, _dataSize, 64 - _dataSize); - // Process message of 64 bytes (512 bits) - Md5Core.GetHashBlock(_data, ref _abcd, 0); - startIndex += 64 - _dataSize; - totalArrayLength -= 64; - while (totalArrayLength >= 64) - { - Array.Copy(array, startIndex, _data, 0, 64); - Md5Core.GetHashBlock(array, ref _abcd, startIndex); - totalArrayLength -= 64; - startIndex += 64; - } - _dataSize = totalArrayLength; - Array.Copy(array, startIndex, _data, 0, totalArrayLength); - } - else - { - Array.Copy(array, startIndex, _data, _dataSize, cbSize); - _dataSize = totalArrayLength; - } - _totalLength += cbSize; - } - - protected override byte[] HashFinal() - { - //field cannot access - //HashValue = Md5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8); - //return HashValue; - return Md5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs deleted file mode 100644 index d0bd79aa28..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Text.RegularExpressions; - -namespace SharpCifs.Util.Sharpen -{ - internal class Matcher - { - private int _current; - private MatchCollection _matches; - private Regex _regex; - private string _str; - - internal Matcher (Regex regex, string str) - { - this._regex = regex; - this._str = str; - } - - public int End () - { - if ((_matches == null) || (_current >= _matches.Count)) { - throw new InvalidOperationException (); - } - return (_matches[_current].Index + _matches[_current].Length); - } - - public bool Find () - { - if (_matches == null) { - _matches = _regex.Matches (_str); - _current = 0; - } - return (_current < _matches.Count); - } - - public bool Find (int index) - { - _matches = _regex.Matches (_str, index); - _current = 0; - return (_matches.Count > 0); - } - - public string Group (int n) - { - if ((_matches == null) || (_current >= _matches.Count)) { - throw new InvalidOperationException (); - } - Group grp = _matches[_current].Groups[n]; - return grp.Success ? grp.Value : null; - } - - public bool Matches () - { - _matches = null; - return Find (); - } - - public string ReplaceFirst (string txt) - { - return _regex.Replace (_str, txt, 1); - } - - public Matcher Reset (CharSequence str) - { - return Reset (str.ToString ()); - } - - public Matcher Reset (string str) - { - _matches = null; - this._str = str; - return this; - } - - public int Start () - { - if ((_matches == null) || (_current >= _matches.Count)) { - throw new InvalidOperationException (); - } - return _matches[_current].Index; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs deleted file mode 100644 index 5562f9d366..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.IO; -using System.Reflection; -using System.Security.Cryptography; - -namespace SharpCifs.Util.Sharpen -{ - public abstract class MessageDigest - { - public void Digest (byte[] buffer, int o, int len) - { - byte[] d = Digest (); - d.CopyTo (buffer, o); - } - - public byte[] Digest (byte[] buffer) - { - Update (buffer); - return Digest (); - } - - public abstract byte[] Digest (); - public abstract int GetDigestLength (); - public static MessageDigest GetInstance (string algorithm) - { - switch (algorithm.ToLower ()) { - case "sha-1": - //System.Security.CryptographySHA1Managed not found - //return new MessageDigest (); - return new MessageDigest(); - case "md5": - return new MessageDigest (); - } - throw new NotSupportedException (string.Format ("The requested algorithm \"{0}\" is not supported.", algorithm)); - } - - public abstract void Reset (); - public abstract void Update (byte[] b); - public abstract void Update (byte b); - public abstract void Update (byte[] b, int offset, int len); - } - - - public class MessageDigest : MessageDigest where TAlgorithm : HashAlgorithm //, new() //use static `Create` method - { - private TAlgorithm _hash; - //private CryptoStream _stream; //don't work .NET Core - private MemoryStream _stream; - - - public MessageDigest () - { - Init (); - } - - public override byte[] Digest () - { - //CryptoStream -> MemoryStream, needless method - //_stream.FlushFinalBlock (); - - //HashAlgorithm.`Hash` property deleted - //byte[] hash = _hash.Hash; - byte[] hash = _hash.ComputeHash(_stream.ToArray()); - - Reset (); - return hash; - } - - public void Dispose () - { - if (_stream != null) { - _stream.Dispose (); - } - _stream = null; - } - - public override int GetDigestLength () - { - return (_hash.HashSize / 8); - } - - private void Init () - { - //use static `Create` method - //_hash = Activator.CreateInstance (); - var createMethod = typeof(TAlgorithm).GetRuntimeMethod("Create", new Type[0]); - _hash = (TAlgorithm)createMethod.Invoke(null, new object[] {}); - - //HashAlgorithm cannot cast `ICryptoTransform` on .NET Core, gave up using CryptoStream. - //_stream = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write); - //_stream = new CryptoStream(_tmpStream, (ICryptoTransform)_hash, CryptoStreamMode.Write); - _stream = new MemoryStream(); - } - - public override void Reset () - { - Dispose (); - Init (); - } - - public override void Update (byte[] input) - { - _stream.Write (input, 0, input.Length); - } - - public override void Update (byte input) - { - _stream.WriteByte (input); - } - - public override void Update (byte[] input, int index, int count) - { - if (count < 0) - Console.WriteLine ("Argh!"); - _stream.Write (input, index, count); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs deleted file mode 100644 index 05599cea3b..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class NetworkStream : Stream - { - SocketEx _socket; - - public NetworkStream(SocketEx socket) - { - _socket = socket; - } - - public override bool CanRead - { - get { throw new NotImplementedException(); } - } - - public override bool CanSeek - { - get { throw new NotImplementedException(); } - } - - public override bool CanWrite - { - get { throw new NotImplementedException(); } - } - - public override void Flush() - { - // throw new NotImplementedException(); - } - - public override long Length - { - get { throw new NotImplementedException(); } - } - - public override long Position - { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } - } - - public override int Read(byte[] buffer, int offset, int count) - { - return _socket.Receive(buffer, offset, count); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - _socket.Send(buffer, offset, count); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs deleted file mode 100644 index dc3d6ccc3e..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - internal class ObjectInputStream : InputStream - { - private BinaryReader _reader; - - public ObjectInputStream (InputStream s) - { - _reader = new BinaryReader (s.GetWrappedStream ()); - } - - public int ReadInt () - { - return _reader.ReadInt32 (); - } - - public object ReadObject () - { - throw new NotImplementedException (); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs deleted file mode 100644 index 97f3a2cfd2..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - internal class ObjectOutputStream : OutputStream - { - private BinaryWriter _bw; - - public ObjectOutputStream (OutputStream os) - { - _bw = new BinaryWriter (os.GetWrappedStream ()); - } - - public virtual void WriteInt (int i) - { - _bw.Write (i); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs deleted file mode 100644 index 0e6189f0cb..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class OutputStream : IDisposable - { - protected Stream Wrapped; - - public static implicit operator OutputStream (Stream s) - { - return Wrap (s); - } - - public static implicit operator Stream (OutputStream s) - { - return s.GetWrappedStream (); - } - - public virtual void Close () - { - if (Wrapped != null) { - //Stream.`Close` method deleted - //Wrapped.Close (); - Wrapped.Dispose(); - } - } - - public void Dispose () - { - Close (); - } - - public virtual void Flush () - { - if (Wrapped != null) { - Wrapped.Flush (); - } - } - - internal Stream GetWrappedStream () - { - // Always create a wrapper stream (not directly Wrapped) since the subclass - // may be overriding methods that need to be called when used through the Stream class - return new WrappedSystemStream (this); - } - - static internal OutputStream Wrap (Stream s) - { - OutputStream stream = new OutputStream (); - stream.Wrapped = s; - return stream; - } - - public virtual void Write (int b) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).OutputStream.Write (b); - else { - if (Wrapped == null) - throw new NotImplementedException (); - Wrapped.WriteByte ((byte)b); - } - } - - public virtual void Write (byte[] b) - { - Write (b, 0, b.Length); - } - - public virtual void Write (byte[] b, int offset, int len) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).OutputStream.Write (b, offset, len); - else { - if (Wrapped != null) { - Wrapped.Write (b, offset, len); - } else { - for (int i = 0; i < len; i++) { - Write (b[i + offset]); - } - } - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs deleted file mode 100644 index 6313b7c798..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.IO; -using System.Text; - -namespace SharpCifs.Util.Sharpen -{ - internal class OutputStreamWriter : StreamWriter - { - public OutputStreamWriter (OutputStream stream) : base(stream.GetWrappedStream ()) - { - } - - public OutputStreamWriter (OutputStream stream, string encoding) : base(stream.GetWrappedStream (), Extensions.GetEncoding (encoding)) - { - } - - public OutputStreamWriter (OutputStream stream, Encoding encoding) : base(stream.GetWrappedStream (), encoding) - { - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs deleted file mode 100644 index d5004c988f..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - internal class PipedInputStream : InputStream - { - private byte[] _oneBuffer; - public const int PipeSize = 1024; - - protected byte[] Buffer; - private bool _closed; - private ManualResetEvent _dataEvent; - private int _end; - private int _start; - private object _thisLock; - private bool _allowGrow = false; - - public int In { - get { return _start; } - set { _start = value; } - } - - public int Out { - get { return _end; } - set { _end = value; } - } - - public PipedInputStream () - { - _thisLock = new object (); - _dataEvent = new ManualResetEvent (false); - Buffer = new byte[PipeSize + 1]; - } - - public PipedInputStream (PipedOutputStream os): this () - { - os.Attach (this); - } - - public override void Close () - { - lock (_thisLock) { - _closed = true; - _dataEvent.Set (); - } - } - - public override int Available () - { - lock (_thisLock) { - if (_start <= _end) { - return (_end - _start); - } - return ((Buffer.Length - _start) + _end); - } - } - - public override int Read () - { - if (_oneBuffer == null) - _oneBuffer = new byte[1]; - if (Read (_oneBuffer, 0, 1) == -1) - return -1; - return _oneBuffer[0]; - } - - public override int Read (byte[] b, int offset, int len) - { - int length = 0; - do { - _dataEvent.WaitOne (); - lock (_thisLock) { - if (_closed && Available () == 0) { - return -1; - } - if (_start < _end) { - length = Math.Min (len, _end - _start); - Array.Copy (Buffer, _start, b, offset, length); - _start += length; - } else if (_start > _end) { - length = Math.Min (len, Buffer.Length - _start); - Array.Copy (Buffer, _start, b, offset, length); - len -= length; - _start = (_start + length) % Buffer.Length; - if (len > 0) { - int i = Math.Min (len, _end); - Array.Copy (Buffer, 0, b, offset + length, i); - _start += i; - length += i; - } - } - if (_start == _end && !_closed) { - _dataEvent.Reset (); - } - Monitor.PulseAll (_thisLock); - } - } while (length == 0); - return length; - } - - private int Allocate (int len) - { - int alen; - while ((alen = TryAllocate (len)) == 0) { - // Wait until somebody reads data - try { - Monitor.Wait (_thisLock); - } catch { - _closed = true; - _dataEvent.Set (); - throw; - } - } - return alen; - } - - int TryAllocate (int len) - { - int free; - if (_start <= _end) { - free = (Buffer.Length - _end) + _start; - } else { - free = _start - _end; - } - if (free <= len) { - if (!_allowGrow) - return free > 0 ? free - 1 : 0; - int sizeInc = (len - free) + 1; - byte[] destinationArray = new byte[Buffer.Length + sizeInc]; - if (_start <= _end) { - Array.Copy (Buffer, _start, destinationArray, _start, _end - _start); - } else { - Array.Copy (Buffer, 0, destinationArray, 0, _end); - Array.Copy (Buffer, _start, destinationArray, _start + sizeInc, Buffer.Length - _start); - _start += sizeInc; - } - Buffer = destinationArray; - } - return len; - } - - internal void Write (int b) - { - lock (_thisLock) { - Allocate (1); - Buffer[_end] = (byte)b; - _end = (_end + 1) % Buffer.Length; - _dataEvent.Set (); - } - } - - internal void Write (byte[] b, int offset, int len) - { - do { - lock (_thisLock) { - int alen = Allocate (len); - int length = Math.Min (Buffer.Length - _end, alen); - Array.Copy (b, offset, Buffer, _end, length); - _end = (_end + length) % Buffer.Length; - if (length < alen) { - Array.Copy (b, offset + length, Buffer, 0, alen - length); - _end += alen - length; - } - _dataEvent.Set (); - len -= alen; - offset += alen; - } - } while (len > 0); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs deleted file mode 100644 index 4c46f1ec00..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal class PipedOutputStream : OutputStream - { - PipedInputStream _ips; - - public PipedOutputStream () - { - } - - public PipedOutputStream (PipedInputStream iss) : this() - { - Attach (iss); - } - - public override void Close () - { - _ips.Close (); - base.Close (); - } - - internal void Attach (PipedInputStream iss) - { - _ips = iss; - } - - public override void Write (int b) - { - _ips.Write (b); - } - - public override void Write (byte[] b, int offset, int len) - { - _ips.Write (b, offset, len); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs deleted file mode 100644 index c366aa6659..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs +++ /dev/null @@ -1,231 +0,0 @@ -using System; -using System.IO; -using System.Text; - -namespace SharpCifs.Util.Sharpen -{ - public class PrintWriter : TextWriter - { - TextWriter _writer; - private FileStream _stream; - - public PrintWriter (FilePath path) - { - //Stream(string path) constructor deleted - _stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite); - _writer = new StreamWriter (_stream); - } - - public PrintWriter (TextWriter other) - { - _writer = other; - } - - public override Encoding Encoding { - get { return _writer.Encoding; } - } - - public void Close() // remove `override` - { - //Stream.`Close` method deleted - //_writer.Close (); - _writer.Dispose(); - _stream.Dispose(); - } - - public override void Flush () - { - _writer.Flush (); - } - - public override IFormatProvider FormatProvider { - get { - return _writer.FormatProvider; - } - } - - public override string NewLine { - get { - return _writer.NewLine; - } - set { - _writer.NewLine = value; - } - } - - public override void Write (char[] buffer, int index, int count) - { - _writer.Write (buffer, index, count); - } - - public override void Write (char[] buffer) - { - _writer.Write (buffer); - } - - public void Write (string format, object arg0, object arg1, object arg2) - { - _writer.Write (format, arg0, arg1, arg2); - } - - public override void Write (string format, object arg0, object arg1) - { - _writer.Write (format, arg0, arg1); - } - - public override void Write (string format, object arg0) - { - _writer.Write (format, arg0); - } - - public override void Write (string format, params object[] arg) - { - _writer.Write (format, arg); - } - - public override void WriteLine (char[] buffer, int index, int count) - { - _writer.WriteLine (buffer, index, count); - } - - public override void WriteLine (char[] buffer) - { - _writer.WriteLine (buffer); - } - - public void WriteLine (string format, object arg0, object arg1, object arg2) - { - _writer.WriteLine (format, arg0, arg1, arg2); - } - - public override void WriteLine (string format, object arg0, object arg1) - { - _writer.WriteLine (format, arg0, arg1); - } - - public override void WriteLine (string format, object arg0) - { - _writer.WriteLine (format, arg0); - } - - public override void WriteLine (string format, params object[] arg) - { - _writer.WriteLine (format, arg); - } - - public override void WriteLine (ulong value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (uint value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (string value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (float value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (object value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (long value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (int value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (double value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (decimal value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (char value) - { - _writer.WriteLine (value); - } - - public override void WriteLine (bool value) - { - _writer.WriteLine (value); - } - - public override void WriteLine () - { - _writer.WriteLine (); - } - - public override void Write (bool value) - { - _writer.Write (value); - } - - public override void Write (char value) - { - _writer.Write (value); - } - - public override void Write (decimal value) - { - _writer.Write (value); - } - - public override void Write (double value) - { - _writer.Write (value); - } - - public override void Write (int value) - { - _writer.Write (value); - } - - public override void Write (long value) - { - _writer.Write (value); - } - - public override void Write (object value) - { - _writer.Write (value); - } - - public override void Write (float value) - { - _writer.Write (value); - } - - public override void Write (string value) - { - _writer.Write (value); - } - - public override void Write (uint value) - { - _writer.Write (value); - } - - public override void Write (ulong value) - { - _writer.Write (value); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs deleted file mode 100644 index 3d886ea87a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class Properties - { - protected Hashtable _properties; - - public Properties() - { - _properties = new Hashtable(); - } - - public Properties(Properties defaultProp): this() - { - PutAll(defaultProp._properties); - } - - public void PutAll(Hashtable properties) - { - foreach (var key in properties.Keys) - { - //_properties.Add(key, properties[key]); - _properties.Put(key, properties[key]); - } - } - - public void SetProperty(object key, object value) - { - //_properties.Add(key, value); - _properties.Put(key, value); - } - - public object GetProperty(object key) - { - return _properties.Keys.Contains(key) ? _properties[key] : null; - } - - public object GetProperty(object key, object def) - { - /*if (_properties.ContainsKey(key)) - { - return _properties[key]; - } - return def;*/ - object value = _properties.Get(key); - - return value ?? def; - } - - public void Load(InputStream input) - { - StreamReader sr = new StreamReader(input); - while (!sr.EndOfStream) - { - string line = sr.ReadLine(); - - if (!string.IsNullOrEmpty(line)) - { - string[] tokens = line.Split('='); - //_properties.Add(tokens[0], tokens[1]); - _properties.Put(tokens[0], tokens[1]); - } - } - } - - public void Store(OutputStream output) - { - StreamWriter sw = new StreamWriter(output); - foreach (var key in _properties.Keys) - { - string line = string.Format("{0}={1}", key, _properties[key]); - sw.WriteLine(line); - } - } - - public void Store(TextWriter output) - { - foreach (var key in _properties.Keys) - { - string line = string.Format("{0}={1}", key, _properties[key]); - output.WriteLine(line); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs deleted file mode 100644 index bf3596212f..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - public class RandomAccessFile - { - private FileStream _stream; - - public RandomAccessFile (FilePath file, string mode) : this(file.GetPath (), mode) - { - } - - public RandomAccessFile (string file, string mode) - { - if (mode.IndexOf ('w') != -1) - _stream = new FileStream (file, FileMode.OpenOrCreate, FileAccess.ReadWrite); - else - _stream = new FileStream (file, FileMode.Open, FileAccess.Read); - } - - public void Close () - { - //Stream.`Close` method deleted - //_stream.Close (); - _stream.Dispose(); - } - - public long GetFilePointer () - { - return _stream.Position; - } - - public long Length () - { - return _stream.Length; - } - - public int Read (byte[] buffer) - { - int r = _stream.Read (buffer, 0, buffer.Length); - return r > 0 ? r : -1; - } - - public int Read (byte[] buffer, int start, int size) - { - return _stream.Read (buffer, start, size); - } - - public void ReadFully (byte[] buffer, int start, int size) - { - while (size > 0) { - int num = _stream.Read (buffer, start, size); - if (num == 0) { - throw new EofException (); - } - size -= num; - start += num; - } - } - - public void Seek (long pos) - { - _stream.Position = pos; - } - - public void SetLength (long len) - { - _stream.SetLength (len); - } - - public void Write (int value) - { - _stream.Write (BitConverter.GetBytes (value), 0, 4); - } - - public void Write (byte[] buffer) - { - _stream.Write (buffer, 0, buffer.Length); - } - - public void Write (byte[] buffer, int start, int size) - { - _stream.Write (buffer, start, size); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs deleted file mode 100644 index aa34db9d05..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - internal class ReentrantLock - { - public void Lock () - { - Monitor.Enter (this); - } - - public bool TryLock () - { - return Monitor.TryEnter (this); - } - - public void Unlock () - { - Monitor.Exit (this); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs deleted file mode 100644 index c7fbe9a488..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal abstract class Reference - { - public abstract T Get (); - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs deleted file mode 100644 index 74ff16b1bb..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - public class Runtime - { - private static Runtime _instance; - private List _shutdownHooks = new List (); - - internal void AddShutdownHook (IRunnable r) - { - ShutdownHook item = new ShutdownHook (); - item.Runnable = r; - _shutdownHooks.Add (item); - } - - internal int AvailableProcessors () - { - return Environment.ProcessorCount; - } - - public static long CurrentTimeMillis () - { - return DateTime.UtcNow.ToMillisecondsSinceEpoch (); - } - - static Hashtable _properties; - - public static Hashtable GetProperties () - { - if (_properties == null) { - _properties = new Hashtable (); - _properties ["jgit.fs.debug"] = "false"; - _properties["file.encoding"] = "UTF-8"; - if (Path.DirectorySeparatorChar != '\\') - _properties ["os.name"] = "Unix"; - else - _properties ["os.name"] = "Windows"; - } - return _properties; - } - - public static string GetProperty (string key) - { - if (GetProperties().Keys.Contains(key)) - { - return ((string)GetProperties()[key]); - } - return null; - } - - public static void SetProperty (string key, string value) - { - GetProperties () [key] = value; - } - - public static Runtime GetRuntime () - { - if (_instance == null) { - _instance = new Runtime (); - } - return _instance; - } - - public static int IdentityHashCode (object ob) - { - return RuntimeHelpers.GetHashCode (ob); - } - - internal long MaxMemory () - { - return int.MaxValue; - } - - private class ShutdownHook - { - public IRunnable Runnable; - - ~ShutdownHook () - { - Runnable.Run (); - } - } - - public static void DeleteCharAt (StringBuilder sb, int index) - { - sb.Remove (index, 1); - } - - public static byte[] GetBytesForString (string str) - { - return Encoding.UTF8.GetBytes (str); - } - - public static byte[] GetBytesForString (string str, string encoding) - { - return Encoding.GetEncoding (encoding).GetBytes (str); - } - - public static FieldInfo[] GetDeclaredFields (Type t) - { - throw new NotImplementedException("Type.GetFields not found on .NetStandard"); - //return t.GetFields (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - } - - public static void NotifyAll (object ob) - { - Monitor.PulseAll (ob); - } - - public static void Notify(object obj) - { - Monitor.Pulse(obj); - } - - public static void PrintStackTrace (Exception ex) - { - Console.WriteLine (ex); - } - - public static void PrintStackTrace (Exception ex, TextWriter tw) - { - tw.WriteLine (ex); - } - - public static string Substring (string str, int index) - { - return str.Substring (index); - } - - public static string Substring (string str, int index, int endIndex) - { - return str.Substring (index, endIndex - index); - } - - public static void Wait (object ob) - { - Monitor.Wait (ob); - } - - public static bool Wait (object ob, long milis) - { - return Monitor.Wait (ob, (int)milis); - } - - public static Type GetType (string name) - { - throw new NotImplementedException("AppDomain.CurrentDomain.GetAssemblies not found on .NetStandard"); - //foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) { - // Type t = a.GetType (name); - // if (t != null) - // return t; - //} - //never used - //throw new InvalidOperationException ("Type not found: " + name); - } - - public static void SetCharAt (StringBuilder sb, int index, char c) - { - sb [index] = c; - } - - public static bool EqualsIgnoreCase (string s1, string s2) - { - return s1.Equals (s2, StringComparison.CurrentCultureIgnoreCase); - } - - internal static long NanoTime () - { - return Environment.TickCount * 1000 * 1000; - } - - internal static int CompareOrdinal (string s1, string s2) - { - return string.CompareOrdinal (s1, s2); - } - - public static string GetStringForBytes (byte[] chars) - { - return Encoding.UTF8.GetString (chars, 0, chars.Length); - } - - public static string GetStringForBytes (byte[] chars, string encoding) - { - return GetEncoding (encoding).GetString (chars, 0, chars.Length); - } - - public static string GetStringForBytes (byte[] chars, int start, int len) - { - return Encoding.UTF8.GetString (chars, start, len); - } - - public static string GetStringForBytes (byte[] chars, int start, int len, string encoding) - { - return GetEncoding (encoding).Decode (chars, start, len); - } - - public static Encoding GetEncoding (string name) - { - Encoding e = Encoding.GetEncoding (name.Replace ('_','-')); - if (e is UTF8Encoding) - return new UTF8Encoding (false, true); - return e; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs deleted file mode 100644 index 35334b4f2a..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Globalization; - -namespace SharpCifs.Util.Sharpen -{ - public class SimpleDateFormat : DateFormat - { - string _format; - - CultureInfo Culture { - get; set; - } - - bool Lenient { - get; set; - } - - public SimpleDateFormat (): this ("g") - { - } - - public SimpleDateFormat (string format): this (format, CultureInfo.CurrentCulture) - { - } - - public SimpleDateFormat (string format, CultureInfo c) - { - Culture = c; - this._format = format.Replace ("EEE", "ddd"); - this._format = this._format.Replace ("Z", "zzz"); - SetTimeZone (TimeZoneInfo.Local); - } - - public bool IsLenient () - { - return Lenient; - } - - public void SetLenient (bool lenient) - { - Lenient = lenient; - } - - public override DateTime Parse (string value) - { - if (IsLenient ()) - return DateTime.Parse (value); - return DateTime.ParseExact (value, _format, Culture); - } - - public override string Format (DateTime date) - { - date += GetTimeZone().BaseUtcOffset; - return date.ToString (_format); - } - - public string Format (long date) - { - return Extensions.MillisToDateTimeOffset (date, (int)GetTimeZone ().BaseUtcOffset.TotalMinutes).DateTime.ToString (_format); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs deleted file mode 100644 index 4d06519498..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs +++ /dev/null @@ -1,161 +0,0 @@ -// SocketEx.cs implementation by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - public class SocketEx : Socket - { - private int _soTimeOut = -1; - - public int SoTimeOut - { - get - { - return _soTimeOut; - } - - set - { - if (value > 0) - { - _soTimeOut = value; - } - else - { - _soTimeOut = -1; - } - - } - } - - public SocketEx(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) - : base(addressFamily, socketType, protocolType) - { - - } - - public void Connect(IPEndPoint endPoint, int timeOut) - { - using (var evt = new ManualResetEventSlim(false)) - { - using (var args = new SocketAsyncEventArgs - { - RemoteEndPoint = endPoint - }) - { - args.Completed += delegate - { - evt.Set(); - }; - - ConnectAsync(args); - - if (!evt.Wait(timeOut)) - { - CancelConnectAsync(args); - throw new ConnectException("Can't connect to end point."); - } - if (args.SocketError != SocketError.Success) - { - throw new ConnectException("Can't connect to end point."); - } - } - } - } - - public void Bind2(EndPoint ep) - { - if (ep == null) - Bind(new IPEndPoint(IPAddress.Any, 0)); - else - Bind(ep); - } - - - public int Receive(byte[] buffer, int offset, int count) - { - using (var evt = new ManualResetEventSlim(false)) - { - using (var args = new SocketAsyncEventArgs - { - UserToken = this - }) - { - args.SetBuffer(buffer, offset, count); - - args.Completed += delegate - { - evt.Set(); - }; - - if (ReceiveAsync(args)) - { - if (!evt.Wait(_soTimeOut)) - { - throw new TimeoutException("No data received."); - } - } - - return args.BytesTransferred; - } - } - } - - public void Send(byte[] buffer, int offset, int length, EndPoint destination = null) - { - using (var evt = new ManualResetEventSlim(false)) - { - using (SocketAsyncEventArgs args = new SocketAsyncEventArgs - { - UserToken = this - }) - { - args.SetBuffer(buffer, offset, length); - - args.Completed += delegate - { - evt.Set(); - }; - - args.RemoteEndPoint = destination ?? RemoteEndPoint; - - - SendToAsync(args); - if (!evt.Wait(_soTimeOut)) - { - throw new TimeoutException("No data sent."); - } - } - } - } - - public InputStream GetInputStream() - { - return new NetworkStream(this); - } - - public OutputStream GetOutputStream() - { - return new NetworkStream(this); - } - - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs deleted file mode 100644 index 74c14cff6c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/StringTokenizer.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - public class StringTokenizer - { - private string[] _tokens; - private int _pos; - - public StringTokenizer(string text, string delim) - { - _tokens = text.Split(delim); - } - - public int CountTokens() - { - return _tokens.Length; - } - - public string NextToken() - { - string value = _tokens[_pos]; - - _pos++; - - return value; - } - - public bool HasMoreTokens() - { - return _pos < _tokens.Length; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs deleted file mode 100644 index c105a8bab6..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Collections; -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - internal class SynchronizedList : IList - { - private IList _list; - - public SynchronizedList (IList list) - { - this._list = list; - } - - public int IndexOf (T item) - { - lock (_list) { - return _list.IndexOf (item); - } - } - - public void Insert (int index, T item) - { - lock (_list) { - _list.Insert (index, item); - } - } - - public void RemoveAt (int index) - { - lock (_list) { - _list.RemoveAt (index); - } - } - - void ICollection.Add (T item) - { - lock (_list) { - _list.Add (item); - } - } - - void ICollection.Clear () - { - lock (_list) { - _list.Clear (); - } - } - - bool ICollection.Contains (T item) - { - lock (_list) { - return _list.Contains (item); - } - } - - void ICollection.CopyTo (T[] array, int arrayIndex) - { - lock (_list) { - _list.CopyTo (array, arrayIndex); - } - } - - bool ICollection.Remove (T item) - { - lock (_list) { - return _list.Remove (item); - } - } - - IEnumerator IEnumerable.GetEnumerator () - { - return _list.GetEnumerator (); - } - - IEnumerator IEnumerable.GetEnumerator () - { - return _list.GetEnumerator (); - } - - public T this[int index] { - get { - lock (_list) { - return _list[index]; - } - } - set { - lock (_list) { - _list[index] = value; - } - } - } - - int ICollection.Count { - get { - lock (_list) { - return _list.Count; - } - } - } - - bool ICollection.IsReadOnly { - get { return _list.IsReadOnly; } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs deleted file mode 100644 index 59f3df4699..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace SharpCifs.Util.Sharpen -{ - public class Thread : IRunnable - { - private static ThreadGroup _defaultGroup = new ThreadGroup (); - private bool _interrupted; - private IRunnable _runnable; - private ThreadGroup _tgroup; - private System.Threading.Thread _thread; - - [ThreadStatic] - private static Thread _wrapperThread; - - public Thread () : this(null, null, null) - { - } - - public Thread (string name) : this (null, null, name) - { - } - - public Thread (ThreadGroup grp, string name) : this (null, grp, name) - { - } - - public Thread (IRunnable runnable): this (runnable, null, null) - { - } - - Thread (IRunnable runnable, ThreadGroup grp, string name) - { - _thread = new System.Threading.Thread (InternalRun); - - this._runnable = runnable ?? this; - _tgroup = grp ?? _defaultGroup; - _tgroup.Add (this); - if (name != null) - _thread.Name = name; - } - - private Thread (System.Threading.Thread t) - { - _thread = t; - _tgroup = _defaultGroup; - _tgroup.Add (this); - } - - public static Thread CurrentThread () - { - if (_wrapperThread == null) { - _wrapperThread = new Thread (System.Threading.Thread.CurrentThread); - } - return _wrapperThread; - } - - public string GetName () - { - return _thread.Name; - } - - public ThreadGroup GetThreadGroup () - { - return _tgroup; - } - - private void InternalRun () - { - _wrapperThread = this; - try { - _runnable.Run (); - } catch (Exception exception) { - Console.WriteLine (exception); - } finally { - _tgroup.Remove (this); - } - } - - public static void Yield () - { - } - - public void Interrupt () - { - lock (_thread) { - _interrupted = true; - //thread.Interrupt (); - - //TODO: implement CancellationToken - //_thread.Abort(); - throw new NotImplementedException("implement CancellationToken for thread"); - } - } - - public static bool Interrupted () - { - if (Thread._wrapperThread == null) { - return false; - } - Thread wrapperThread = Thread._wrapperThread; - lock (wrapperThread) { - bool interrupted = Thread._wrapperThread._interrupted; - Thread._wrapperThread._interrupted = false; - return interrupted; - } - } - - public bool IsAlive () - { - return _thread.IsAlive; - } - - public void Join () - { - _thread.Join (); - } - - public void Join (long timeout) - { - _thread.Join ((int)timeout); - } - - public virtual void Run () - { - } - - public void SetDaemon (bool daemon) - { - _thread.IsBackground = daemon; - } - - public void SetName (string name) - { - _thread.Name = name; - } - - public static void Sleep (long milis) - { - System.Threading.Thread.Sleep ((int)milis); - } - - public void Start () - { - _thread.Start (); - } - - public void Abort () - { - //TODO: implement CancellationToken - //_thread.Abort (); - throw new NotImplementedException("implement CancellationToken for thread"); - } - - } - - public class ThreadGroup - { - private List _threads = new List (); - - public ThreadGroup() - { - } - - public ThreadGroup (string name) - { - } - - internal void Add (Thread t) - { - lock (_threads) { - _threads.Add (t); - } - } - - internal void Remove (Thread t) - { - lock (_threads) { - _threads.Remove (t); - } - } - - public int Enumerate (Thread[] array) - { - lock (_threads) { - int count = Math.Min (array.Length, _threads.Count); - _threads.CopyTo (0, array, 0, count); - return count; - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs deleted file mode 100644 index 7276c06a2c..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace SharpCifs.Util.Sharpen -{ - internal class ThreadFactory - { - public Thread NewThread (IRunnable r) - { - Thread t = new Thread (r); - t.SetDaemon (true); - t.Start (); - return t; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs deleted file mode 100644 index ef19b8bff5..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using ST = System.Threading; - -namespace SharpCifs.Util.Sharpen -{ - class ThreadPoolExecutor - { - ThreadFactory _tf; - int _corePoolSize; - int _maxPoolSize; - List _pool = new List (); - int _runningThreads; - int _freeThreads; - bool _shutdown; - Queue _pendingTasks = new Queue (); - - public ThreadPoolExecutor (int corePoolSize, ThreadFactory factory) - { - this._corePoolSize = corePoolSize; - _maxPoolSize = corePoolSize; - _tf = factory; - } - - public void SetMaximumPoolSize (int size) - { - _maxPoolSize = size; - } - - public bool IsShutdown () - { - return _shutdown; - } - - public virtual bool IsTerminated () - { - lock (_pendingTasks) { - return _shutdown && _pendingTasks.Count == 0; - } - } - - public virtual bool IsTerminating () - { - lock (_pendingTasks) { - return _shutdown && !IsTerminated (); - } - } - - public int GetCorePoolSize () - { - return _corePoolSize; - } - - public void PrestartAllCoreThreads () - { - lock (_pendingTasks) { - while (_runningThreads < _corePoolSize) - StartPoolThread (); - } - } - - public void SetThreadFactory (ThreadFactory f) - { - _tf = f; - } - - public void Execute (IRunnable r) - { - InternalExecute (r, true); - } - - internal void InternalExecute (IRunnable r, bool checkShutdown) - { - lock (_pendingTasks) { - if (_shutdown && checkShutdown) - throw new InvalidOperationException (); - if (_runningThreads < _corePoolSize) { - StartPoolThread (); - } - else if (_freeThreads > 0) { - _freeThreads--; - } - else if (_runningThreads < _maxPoolSize) { - StartPoolThread (); - } - _pendingTasks.Enqueue (r); - ST.Monitor.PulseAll (_pendingTasks); - } - } - - void StartPoolThread () - { - _runningThreads++; - _pool.Add (_tf.NewThread (new RunnableAction (RunPoolThread))); - } - - public void RunPoolThread () - { - while (!IsTerminated ()) { - try { - IRunnable r = null; - lock (_pendingTasks) { - _freeThreads++; - while (!IsTerminated () && _pendingTasks.Count == 0) - ST.Monitor.Wait (_pendingTasks); - if (IsTerminated ()) - break; - r = _pendingTasks.Dequeue (); - } - if (r != null) - r.Run (); - } - //supress all errors, anyway - //catch (ST.ThreadAbortException) { - // // Do not catch a thread abort. If we've been aborted just let the thread die. - // // Currently reseting an abort which was issued because the appdomain is being - // // torn down results in the process living forever and consuming 100% cpu time. - // return; - //} - catch { - } - } - } - - public virtual void Shutdown () - { - lock (_pendingTasks) { - _shutdown = true; - ST.Monitor.PulseAll (_pendingTasks); - } - } - - public virtual List ShutdownNow () - { - lock (_pendingTasks) { - _shutdown = true; - foreach (var t in _pool) { - try { - t.Abort (); - } catch {} - } - _pool.Clear (); - _freeThreads = 0; - _runningThreads = 0; - var res = new List (_pendingTasks); - _pendingTasks.Clear (); - return res; - } - } - } - - class RunnableAction: IRunnable - { - Action _action; - - public RunnableAction (Action a) - { - _action = a; - } - - public void Run () - { - _action (); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs deleted file mode 100644 index ef2993fa61..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.IO; - -namespace SharpCifs.Util.Sharpen -{ - internal class WrappedSystemStream : Stream - { - private InputStream _ist; - private OutputStream _ost; - int _position; - int _markedPosition; - - public WrappedSystemStream (InputStream ist) - { - this._ist = ist; - } - - public WrappedSystemStream (OutputStream ost) - { - this._ost = ost; - } - - public InputStream InputStream { - get { return _ist; } - } - - public OutputStream OutputStream { - get { return _ost; } - } - - public void Close() //remove `override` - { - if (_ist != null) { - //Stream.`Close` method deleted - //_ist.Close (); - _ist.Dispose(); - } - if (_ost != null) { - //Stream.`Close` method deleted - //_ost.Close (); - _ost.Dispose(); - } - } - - public override void Flush () - { - _ost.Flush (); - } - - public override int Read (byte[] buffer, int offset, int count) - { - int res = _ist.Read (buffer, offset, count); - if (res != -1) { - _position += res; - return res; - } - return 0; - } - - public override int ReadByte () - { - int res = _ist.Read (); - if (res != -1) - _position++; - return res; - } - - public override long Seek (long offset, SeekOrigin origin) - { - if (origin == SeekOrigin.Begin) - Position = offset; - else if (origin == SeekOrigin.Current) - Position = Position + offset; - else if (origin == SeekOrigin.End) - Position = Length + offset; - return Position; - } - - public override void SetLength (long value) - { - throw new NotSupportedException (); - } - - public override void Write (byte[] buffer, int offset, int count) - { - _ost.Write (buffer, offset, count); - _position += count; - } - - public override void WriteByte (byte value) - { - _ost.Write (value); - _position++; - } - - public override bool CanRead { - get { return (_ist != null); } - } - - public override bool CanSeek { - get { return true; } - } - - public override bool CanWrite { - get { return (_ost != null); } - } - - public override long Length { - get { return _ist.Length; } - } - - internal void OnMark (int nb) - { - _markedPosition = _position; - _ist.Mark (nb); - } - - public override long Position { - get - { - if (_ist != null && _ist.CanSeek ()) - return _ist.Position; - return _position; - } - set - { - if (value == _position) - return; - if (value == _markedPosition) - _ist.Reset (); - else if (_ist != null && _ist.CanSeek ()) { - _ist.Position = value; - } - else - throw new NotSupportedException (); - } - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs deleted file mode 100644 index 6e0c3fc7ba..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Request.cs +++ /dev/null @@ -1,22 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Util.Transport -{ - public interface IRequest - { - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs deleted file mode 100644 index 702fea9187..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Response.cs +++ /dev/null @@ -1,25 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -namespace SharpCifs.Util.Transport -{ - public abstract class Response - { - public long Expiration; - - public bool IsReceived; - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs deleted file mode 100644 index b02936ca61..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/Transport.cs +++ /dev/null @@ -1,454 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Smb; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util.Transport -{ - /// - /// This class simplifies communication for protocols that support - /// multiplexing requests. - /// - /// - /// This class simplifies communication for protocols that support - /// multiplexing requests. It encapsulates a stream and some protocol - /// knowledge (provided by a concrete subclass) so that connecting, - /// disconnecting, sending, and receiving can be syncronized - /// properly. Apparatus is provided to send and receive requests - /// concurrently. - /// - public abstract class Transport : IRunnable - { - internal static int Id; - - //internal static LogStream log = LogStream.GetInstance(); - - public LogStream Log - { - get - { - return LogStream.GetInstance(); - } - } - - /// - public static int Readn(InputStream @in, byte[] b, int off, int len) - { - int i = 0; - int n = -5; - while (i < len) - { - n = @in.Read(b, off + i, len - i); - if (n <= 0) - { - break; - } - i += n; - } - return i; - } - - internal int State; - - internal string Name = "Transport" + Id++; - - internal Thread Thread; - - internal TransportException Te; - - protected internal Hashtable ResponseMap = new Hashtable(); - - /// - protected internal abstract void MakeKey(ServerMessageBlock request); - - /// - protected internal abstract ServerMessageBlock PeekKey(); - - /// - protected internal abstract void DoSend(ServerMessageBlock request); - - /// - protected internal abstract void DoRecv(Response response); - - /// - protected internal abstract void DoSkip(); - - /// - public virtual void Sendrecv(ServerMessageBlock request, Response response, long timeout) - { - lock (this) - { - MakeKey(request); - response.IsReceived = false; - try - { - ResponseMap.Put(request, response); - DoSend(request); - response.Expiration = Runtime.CurrentTimeMillis() + timeout; - while (!response.IsReceived) - { - Runtime.Wait(this, timeout); - timeout = response.Expiration - Runtime.CurrentTimeMillis(); - if (timeout <= 0) - { - throw new TransportException(Name + " timedout waiting for response to " + request - ); - } - } - } - catch (IOException ioe) - { - if (Log.Level > 2) - { - Runtime.PrintStackTrace(ioe, Log); - } - try - { - Disconnect(true); - } - catch (IOException ioe2) - { - Runtime.PrintStackTrace(ioe2, Log); - } - throw; - } - catch (Exception ie) - { - throw new TransportException(ie); - } - finally - { - //Sharpen.Collections.Remove(response_map, request); - ResponseMap.Remove(request); - } - } - } - - private void Loop() - { - while (Thread == Thread.CurrentThread()) - { - try - { - ServerMessageBlock key = PeekKey(); - if (key == null) - { - throw new IOException("end of stream"); - } - - - lock (this) - { - Response response = (Response)ResponseMap.Get(key); - if (response == null) - { - if (Log.Level >= 4) - { - Log.WriteLine("Invalid key, skipping message"); - } - DoSkip(); - } - else - { - DoRecv(response); - response.IsReceived = true; - Runtime.NotifyAll(this); - } - } - } - catch (Exception ex) - { - string msg = ex.Message; - bool timeout = msg != null && msg.Equals("Read timed out"); - bool hard = timeout == false; - if (!timeout && Log.Level >= 3) - { - Runtime.PrintStackTrace(ex, Log); - } - try - { - Disconnect(hard); - } - catch (IOException ioe) - { - Runtime.PrintStackTrace(ioe, Log); - } - } - } - } - - /// - protected internal abstract void DoConnect(); - - /// - protected internal abstract void DoDisconnect(bool hard); - - /// - public virtual void Connect(long timeout) - { - lock (this) - { - try - { - switch (State) - { - case 0: - { - break; - } - - case 3: - { - return; - } - - case 4: - { - // already connected - State = 0; - throw new TransportException("Connection in error", Te); - } - - default: - { - //TransportException te = new TransportException("Invalid state: " + state); - State = 0; - throw new TransportException("Invalid state: " + State); - } - } - State = 1; - Te = null; - Thread = new Thread(this); - Thread.SetDaemon(true); - lock (Thread) - { - Thread.Start(); - Runtime.Wait(Thread, timeout); - switch (State) - { - case 1: - { - State = 0; - Thread = null; - throw new TransportException("Connection timeout"); - } - - case 2: - { - if (Te != null) - { - State = 4; - Thread = null; - throw Te; - } - State = 3; - return; - } - } - } - } - catch (Exception ie) - { - State = 0; - Thread = null; - throw new TransportException(ie); - } - finally - { - if (State != 0 && State != 3 && State != 4) - { - if (Log.Level >= 1) - { - Log.WriteLine("Invalid state: " + State); - } - State = 0; - Thread = null; - } - } - } - } - - /// - public virtual void Disconnect(bool hard) - { - - if (hard) - { - IOException ioe = null; - switch (State) - { - case 0: - { - return; - } - - case 2: - { - hard = true; - goto case 3; - } - - case 3: - { - if (ResponseMap.Count != 0 && !hard) - { - break; - } - try - { - DoDisconnect(hard); - } - catch (IOException ioe0) - { - ioe = ioe0; - } - goto case 4; - } - - case 4: - { - Thread = null; - State = 0; - break; - } - - default: - { - if (Log.Level >= 1) - { - Log.WriteLine("Invalid state: " + State); - } - Thread = null; - State = 0; - break; - } - } - if (ioe != null) - { - throw ioe; - } - - return; - } - - lock (this) - { - IOException ioe = null; - switch (State) - { - case 0: - { - return; - } - - case 2: - { - hard = true; - goto case 3; - } - - case 3: - { - if (ResponseMap.Count != 0 && !hard) - { - break; - } - try - { - DoDisconnect(hard); - } - catch (IOException ioe0) - { - ioe = ioe0; - } - goto case 4; - } - - case 4: - { - Thread = null; - State = 0; - break; - } - - default: - { - if (Log.Level >= 1) - { - Log.WriteLine("Invalid state: " + State); - } - Thread = null; - State = 0; - break; - } - } - if (ioe != null) - { - throw ioe; - } - } - } - - public virtual void Run() - { - Thread runThread = Thread.CurrentThread(); - Exception ex0 = null; - try - { - DoConnect(); - } - catch (Exception ex) - { - ex0 = ex; - // Defer to below where we're locked - return; - } - finally - { - lock (runThread) - { - if (runThread != Thread) - { - if (ex0 != null) - { - if (Log.Level >= 2) - { - Runtime.PrintStackTrace(ex0, Log); - } - } - //return; - } - if (ex0 != null) - { - Te = new TransportException(ex0); - } - State = 2; - // run connected - Runtime.Notify(runThread); - } - } - Loop(); - } - - public override string ToString() - { - return Name; - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs b/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs deleted file mode 100644 index bd04551976..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifs/Util/Transport/TransportException.cs +++ /dev/null @@ -1,63 +0,0 @@ -// This code is derived from jcifs smb client library -// Ported by J. Arturo -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -using System; -using System.IO; -using SharpCifs.Util.Sharpen; - -namespace SharpCifs.Util.Transport -{ - - public class TransportException : IOException - { - private Exception _rootCause; - - public TransportException() - { - } - - public TransportException(string msg) : base(msg) - { - } - - public TransportException(Exception rootCause) - { - this._rootCause = rootCause; - } - - public TransportException(string msg, Exception rootCause) : base(msg) - { - this._rootCause = rootCause; - } - - public virtual Exception GetRootCause() - { - return _rootCause; - } - - public override string ToString() - { - if (_rootCause != null) - { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - Runtime.PrintStackTrace(_rootCause, pw); - return base.ToString() + "\n" + sw; - } - return base.ToString(); - } - } -} diff --git a/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs b/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs deleted file mode 100644 index a48543bc70..0000000000 --- a/Emby.Server.Implementations/IO/SharpCifsFileSystem.cs +++ /dev/null @@ -1,621 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using MediaBrowser.Model.IO; -using SharpCifs.Smb; - -namespace Emby.Server.Implementations.IO -{ - public class SharpCifsFileSystem - { - private readonly MediaBrowser.Model.System.OperatingSystem _operatingSystem; - - public SharpCifsFileSystem(MediaBrowser.Model.System.OperatingSystem operatingSystem) - { - _operatingSystem = operatingSystem; - } - - public bool IsEnabledForPath(string path) - { - if (_operatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows) - { - return false; - } - - return path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase) || IsUncPath(path); - } - - public string NormalizePath(string path) - { - if (path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase)) - { - return path; - } - - if (IsUncPath(path)) - { - return ConvertUncToSmb(path); - } - - return path; - } - - public string GetDirectoryName(string path) - { - var separator = GetDirectorySeparatorChar(path); - var result = Path.GetDirectoryName(path); - - if (separator == '/') - { - result = result.Replace('\\', '/'); - - if (result.StartsWith("smb:/", StringComparison.OrdinalIgnoreCase) && !result.StartsWith("smb://", StringComparison.OrdinalIgnoreCase)) - { - result = result.Replace("smb:/", "smb://"); - } - } - - return result; - } - - public char GetDirectorySeparatorChar(string path) - { - if (path.IndexOf('/') != -1) - { - return '/'; - } - - return '\\'; - } - - public FileSystemMetadata GetFileSystemInfo(string path) - { - var file = CreateSmbFile(path); - return ToMetadata(file); - } - - public FileSystemMetadata GetFileInfo(string path) - { - var file = CreateSmbFile(path); - return ToMetadata(file, false); - } - - public FileSystemMetadata GetDirectoryInfo(string path) - { - var file = CreateSmbFile(path); - return ToMetadata(file, true); - } - - private bool IsUncPath(string path) - { - return path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase); - } - - private string GetReturnPath(SmbFile file) - { - return file.GetCanonicalPath().TrimEnd('/'); - //return file.GetPath(); - } - - private string ConvertUncToSmb(string path) - { - if (IsUncPath(path)) - { - path = path.Replace('\\', '/'); - path = "smb:" + path; - } - return path; - } - - private string AddAuthentication(string path) - { - return path; - } - - private SmbFile CreateSmbFile(string path) - { - path = ConvertUncToSmb(path); - path = AddAuthentication(path); - - return new SmbFile(path); - } - - DateTime baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - private FileSystemMetadata ToMetadata(SmbFile info, bool? isDirectory = null) - { - var result = new FileSystemMetadata(); - - result.Exists = info.Exists(); - result.FullName = GetReturnPath(info); - result.Extension = Path.GetExtension(result.FullName); - result.Name = info.GetName(); - - if (result.Exists) - { - result.IsDirectory = info.IsDirectory(); - - if (info.IsFile()) - { - result.Length = info.Length(); - result.DirectoryName = info.GetParent(); - } - - result.CreationTimeUtc = baseDate.AddMilliseconds(info.CreateTime()); - result.LastWriteTimeUtc = baseDate.AddMilliseconds(info.GetLastModified()); - } - else - { - if (isDirectory.HasValue) - { - result.IsDirectory = isDirectory.Value; - } - } - - return result; - } - - public void SetHidden(string path, bool isHidden) - { - var file = CreateSmbFile(path); - SetHidden(file, isHidden); - } - - public void SetReadOnly(string path, bool isReadOnly) - { - var file = CreateSmbFile(path); - SetReadOnly(file, isReadOnly); - } - - public void SetAttributes(string path, bool isHidden, bool isReadOnly) - { - var file = CreateSmbFile(path); - SetHidden(file, isHidden); - SetReadOnly(file, isReadOnly); - } - - private void SetHidden(SmbFile file, bool isHidden) - { - var isCurrentlyHidden = file.IsHidden(); - - if (isCurrentlyHidden && !isHidden) - { - file.SetAttributes(file.GetAttributes() & ~SmbFile.AttrHidden); - } - else if (!isCurrentlyHidden && isHidden) - { - file.SetAttributes(file.GetAttributes() | SmbFile.AttrHidden); - } - } - - private void SetReadOnly(SmbFile file, bool isReadOnly) - { - var isCurrentlyReadOnly = !file.CanWrite(); - - if (isCurrentlyReadOnly && !isReadOnly) - { - file.SetReadWrite(); - } - else if (!isCurrentlyReadOnly && isReadOnly) - { - file.SetReadOnly(); - } - } - - public void DeleteFile(string path) - { - var file = CreateSmbFile(path); - - AssertFileExists(file, path); - - file.Delete(); - } - - public void DeleteDirectory(string path, bool recursive) - { - var file = CreateSmbFile(path); - - AssertDirectoryExists(file, path); - - file.Delete(); - } - - public void CreateDirectory(string path) - { - } - - public string[] ReadAllLines(string path) - { - var lines = new List(); - - using (var stream = OpenRead(path)) - { - using (var reader = new StreamReader(stream)) - { - while (!reader.EndOfStream) - { - lines.Add(reader.ReadLine()); - } - } - } - - return lines.ToArray(); - } - - public void WriteAllLines(string path, IEnumerable lines) - { - using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - using (var writer = new StreamWriter(stream)) - { - foreach (var line in lines) - { - writer.WriteLine(line); - } - } - } - } - - private void AssertFileExists(SmbFile file, string path) - { - if (!file.Exists()) - { - throw new FileNotFoundException("File not found.", path); - } - } - - private void AssertDirectoryExists(SmbFile file, string path) - { - if (!file.Exists()) - { - throw new FileNotFoundException("File not found.", path); - } - } - - public Stream OpenRead(string path) - { - var file = CreateSmbFile(path); - - AssertFileExists(file, path); - - return file.GetInputStream(); - } - - private Stream OpenWrite(string path) - { - var file = CreateSmbFile(path); - - AssertFileExists(file, path); - - return file.GetInputStream(); - } - - public void CopyFile(string source, string target, bool overwrite) - { - if (string.Equals(source, target, StringComparison.Ordinal)) - { - throw new ArgumentException("Cannot CopyFile when source and target are the same"); - } - - using (var input = OpenRead(source)) - { - using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - input.CopyTo(output); - } - } - } - - public void MoveFile(string source, string target) - { - if (string.Equals(source, target, StringComparison.Ordinal)) - { - throw new ArgumentException("Cannot MoveFile when source and target are the same"); - } - - using (var input = OpenRead(source)) - { - using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - input.CopyTo(output); - } - } - - DeleteFile(source); - } - - public void MoveDirectory(string source, string target) - { - throw new NotImplementedException(); - } - - public bool DirectoryExists(string path) - { - var dir = CreateSmbFile(path); - - return dir.Exists() && dir.IsDirectory(); - } - - public bool FileExists(string path) - { - var file = CreateSmbFile(path); - return file.Exists(); - } - - public string ReadAllText(string path, Encoding encoding) - { - using (var stream = OpenRead(path)) - { - using (var reader = new StreamReader(stream, encoding)) - { - return reader.ReadToEnd(); - } - } - } - - public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share) - { - if (mode == FileOpenMode.OpenOrCreate) - { - var file = CreateSmbFile(path); - if (!file.Exists()) - { - file.CreateNewFile(); - } - - mode = FileOpenMode.Open; - } - - if (mode == FileOpenMode.CreateNew) - { - var file = CreateSmbFile(path); - if (file.Exists()) - { - throw new IOException("File already exists"); - } - - file.CreateNewFile(); - - mode = FileOpenMode.Open; - } - - if (mode == FileOpenMode.Create) - { - var file = CreateSmbFile(path); - if (file.Exists()) - { - if (file.IsHidden()) - { - throw new UnauthorizedAccessException(string.Format("File {0} already exists and is hidden", path)); - } - - file.Delete(); - file.CreateNewFile(); - } - else - { - file.CreateNewFile(); - } - - mode = FileOpenMode.Open; - } - - if (mode == FileOpenMode.Open) - { - if (access == FileAccessMode.Read) - { - return OpenRead(path); - } - if (access == FileAccessMode.Write) - { - return OpenWrite(path); - } - throw new NotImplementedException(); - } - throw new NotImplementedException(); - } - - public void WriteAllBytes(string path, byte[] bytes) - { - using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - stream.Write(bytes, 0, bytes.Length); - } - } - - public void WriteAllText(string path, string text) - { - using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - using (var writer = new StreamWriter(stream)) - { - writer.Write(text); - } - } - } - - public void WriteAllText(string path, string text, Encoding encoding) - { - using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None)) - { - using (var writer = new StreamWriter(stream, encoding)) - { - writer.Write(text); - } - } - } - - public string ReadAllText(string path) - { - using (var stream = OpenRead(path)) - { - using (var reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } - } - } - - public byte[] ReadAllBytes(string path) - { - using (var stream = OpenRead(path)) - { - using (var ms = new MemoryStream()) - { - stream.CopyTo(ms); - ms.Position = 0; - return ms.ToArray(); - } - } - } - - private SmbFile CreateSmbDirectoryForListFiles(string path) - { - // In order to call ListFiles, it has to end with the separator - - return CreateSmbFile(path.TrimEnd('/') + '/'); - } - - public IEnumerable GetDirectories(string path, bool recursive = false) - { - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - var result = new List(); - - foreach (var file in list) - { - if (file.IsDirectory()) - { - result.Add(ToMetadata(file)); - } - } - - return result; - } - - public IEnumerable GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) - { - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - var result = new List(); - - foreach (var file in list) - { - if (file.IsFile()) - { - var filePath = GetReturnPath(file); - var extension = Path.GetExtension(filePath); - - if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase)) - { - result.Add(ToMetadata(file)); - } - } - } - - return result; - } - - public IEnumerable GetFileSystemEntries(string path, bool recursive = false) - { - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - var result = new List(); - - foreach (var file in list) - { - result.Add(ToMetadata(file)); - } - - return result; - } - - public List GetFileSystemEntryPaths(string path, bool recursive = false) - { - var result = new List(); - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - - foreach (var file in list) - { - result.Add(GetReturnPath(file)); - } - return result; - } - - public List GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) - { - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - var result = new List(); - - foreach (var file in list) - { - if (file.IsFile()) - { - var filePath = GetReturnPath(file); - var extension = Path.GetExtension(filePath); - - if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase)) - { - result.Add(filePath); - } - } - } - - return result; - } - - public List GetDirectoryPaths(string path, bool recursive = false) - { - var dir = CreateSmbDirectoryForListFiles(path); - AssertDirectoryExists(dir, path); - - var list = ListFiles(dir, recursive); - var result = new List(); - - foreach (var file in list) - { - if (file.IsDirectory()) - { - result.Add(GetReturnPath(file)); - } - } - - return result; - } - - private IEnumerable ListFiles(SmbFile dir, bool recursive) - { - var list = dir.ListFiles(); - var result = new List(); - - foreach (var file in list) - { - result.Add(file); - - if (recursive && file.IsDirectory()) - { - foreach (var subFile in ListFiles(file, recursive)) - { - result.Add(subFile); - } - } - } - - return result; - } - } -} From a640d437c84f13aa7efd3f0247293e89a4b7fc7e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 3 Jan 2019 23:10:18 +0100 Subject: [PATCH 084/125] Remove news service --- .../ApplicationHost.cs | 3 - .../News/NewsEntryPoint.cs | 279 ------------------ .../News/NewsService.cs | 77 ----- 3 files changed, 359 deletions(-) delete mode 100644 Emby.Server.Implementations/News/NewsEntryPoint.cs delete mode 100644 Emby.Server.Implementations/News/NewsService.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ff6586ac1e..80e9b6b502 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -966,9 +966,6 @@ namespace Emby.Server.Implementations DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager); RegisterSingleInstance(DeviceManager); - var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer); - RegisterSingleInstance(newsService); - MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder); RegisterSingleInstance(MediaSourceManager); diff --git a/Emby.Server.Implementations/News/NewsEntryPoint.cs b/Emby.Server.Implementations/News/NewsEntryPoint.cs deleted file mode 100644 index ce6fe6630b..0000000000 --- a/Emby.Server.Implementations/News/NewsEntryPoint.cs +++ /dev/null @@ -1,279 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Notifications; -using MediaBrowser.Controller.Plugins; -using Microsoft.Extensions.Logging; -using MediaBrowser.Model.News; -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 System.Xml; -using MediaBrowser.Common.Progress; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Threading; - -namespace Emby.Server.Implementations.News -{ - public class NewsEntryPoint : IServerEntryPoint - { - private ITimer _timer; - private readonly IHttpClient _httpClient; - private readonly IApplicationPaths _appPaths; - private readonly IFileSystem _fileSystem; - private readonly ILogger _logger; - private readonly IJsonSerializer _json; - - private readonly INotificationManager _notifications; - private readonly IUserManager _userManager; - - private readonly TimeSpan _frequency = TimeSpan.FromHours(24); - private readonly ITimerFactory _timerFactory; - - public NewsEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IJsonSerializer json, INotificationManager notifications, IUserManager userManager, ITimerFactory timerFactory) - { - _httpClient = httpClient; - _appPaths = appPaths; - _fileSystem = fileSystem; - _logger = logger; - _json = json; - _notifications = notifications; - _userManager = userManager; - _timerFactory = timerFactory; - } - - public void Run() - { - _timer = _timerFactory.Create(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency); - } - - /// - /// Called when [timer fired]. - /// - /// The state. - private async void OnTimerFired(object state) - { - var path = Path.Combine(_appPaths.CachePath, "news.json"); - - try - { - await DownloadNews(path).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error downloading news"); - } - } - - private async Task DownloadNews(string path) - { - DateTime? lastUpdate = null; - - if (_fileSystem.FileExists(path)) - { - lastUpdate = _fileSystem.GetLastWriteTimeUtc(path); - } - - var requestOptions = new HttpRequestOptions - { - Url = "https://github.com/jellyfin/jellyfin", - Progress = new SimpleProgress(), - UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36", - BufferContent = false - }; - - using (var response = await _httpClient.SendAsync(requestOptions, "GET").ConfigureAwait(false)) - { - using (var stream = response.Content) - { - using (var reader = XmlReader.Create(stream)) - { - var news = ParseRssItems(reader).ToList(); - - _json.SerializeToFile(news, path); - - await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false); - } - } - } - } - - private Task CreateNotifications(List items, DateTime? lastUpdate, CancellationToken cancellationToken) - { - if (lastUpdate.HasValue) - { - items = items.Where(i => i.Date.ToUniversalTime() >= lastUpdate.Value) - .ToList(); - } - - var tasks = items.Select(i => _notifications.SendNotification(new NotificationRequest - { - Date = i.Date, - Name = i.Title, - Description = i.Description, - Url = i.Link, - UserIds = _userManager.Users.Select(u => u.Id).ToArray() - - }, cancellationToken)); - - return Task.WhenAll(tasks); - } - - private IEnumerable ParseRssItems(XmlReader reader) - { - reader.MoveToContent(); - reader.Read(); - - while (!reader.EOF && reader.ReadState == ReadState.Interactive) - { - if (reader.NodeType == XmlNodeType.Element) - { - switch (reader.Name) - { - case "channel": - { - if (!reader.IsEmptyElement) - { - using (var subReader = reader.ReadSubtree()) - { - return ParseFromChannelNode(subReader); - } - } - else - { - reader.Read(); - } - break; - } - default: - { - reader.Skip(); - break; - } - } - } - else - { - reader.Read(); - } - } - - return new List(); - } - - private IEnumerable ParseFromChannelNode(XmlReader reader) - { - var list = new List(); - - reader.MoveToContent(); - reader.Read(); - - while (!reader.EOF && reader.ReadState == ReadState.Interactive) - { - if (reader.NodeType == XmlNodeType.Element) - { - switch (reader.Name) - { - case "item": - { - if (!reader.IsEmptyElement) - { - using (var subReader = reader.ReadSubtree()) - { - list.Add(ParseItem(subReader)); - } - } - else - { - reader.Read(); - } - break; - } - default: - { - reader.Skip(); - break; - } - } - } - else - { - reader.Read(); - } - } - - return list; - } - - private NewsItem ParseItem(XmlReader reader) - { - var item = new NewsItem(); - - reader.MoveToContent(); - reader.Read(); - - while (!reader.EOF && reader.ReadState == ReadState.Interactive) - { - if (reader.NodeType == XmlNodeType.Element) - { - switch (reader.Name) - { - case "title": - { - item.Title = reader.ReadElementContentAsString(); - break; - } - case "link": - { - item.Link = reader.ReadElementContentAsString(); - break; - } - case "description": - { - item.DescriptionHtml = reader.ReadElementContentAsString(); - item.Description = item.DescriptionHtml.StripHtml(); - break; - } - case "pubDate": - { - var date = reader.ReadElementContentAsString(); - DateTime parsedDate; - - if (DateTime.TryParse(date, out parsedDate)) - { - item.Date = parsedDate; - } - break; - } - default: - { - reader.Skip(); - break; - } - } - } - else - { - reader.Read(); - } - } - - return item; - } - - public void Dispose() - { - if (_timer != null) - { - _timer.Dispose(); - _timer = null; - } - } - } -} diff --git a/Emby.Server.Implementations/News/NewsService.cs b/Emby.Server.Implementations/News/NewsService.cs deleted file mode 100644 index 80e7996342..0000000000 --- a/Emby.Server.Implementations/News/NewsService.cs +++ /dev/null @@ -1,77 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.News; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace Emby.Server.Implementations.News -{ - public class NewsService : INewsService - { - private readonly IApplicationPaths _appPaths; - private readonly IJsonSerializer _json; - - public NewsService(IApplicationPaths appPaths, IJsonSerializer json) - { - _appPaths = appPaths; - _json = json; - } - - public QueryResult GetProductNews(NewsQuery query) - { - try - { - return GetProductNewsInternal(query); - } - catch (FileNotFoundException) - { - // No biggie - return new QueryResult - { - Items = new NewsItem[] { } - }; - } - catch (IOException) - { - // No biggie - return new QueryResult - { - Items = new NewsItem[] { } - }; - } - } - - private QueryResult GetProductNewsInternal(NewsQuery query) - { - var path = Path.Combine(_appPaths.CachePath, "news.json"); - - var items = GetNewsItems(path).OrderByDescending(i => i.Date); - - var itemsArray = items.ToArray(); - var count = itemsArray.Length; - - if (query.StartIndex.HasValue) - { - itemsArray = itemsArray.Skip(query.StartIndex.Value).ToArray(); - } - - if (query.Limit.HasValue) - { - itemsArray = itemsArray.Take(query.Limit.Value).ToArray(); - } - - return new QueryResult - { - Items = itemsArray, - TotalRecordCount = count - }; - } - - private IEnumerable GetNewsItems(string path) - { - return _json.DeserializeFromFile>(path); - } - } -} From 340a2c651276d911285a6ff09944c5eba2384a51 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 27 Dec 2018 22:43:48 +0100 Subject: [PATCH 085/125] Post GPL cleanup --- .../Library/UserManager.cs | 1 - MediaBrowser.Api/BaseApiService.cs | 3 +- MediaBrowser.Api/UserService.cs | 5 +- .../Authentication/IAuthenticationProvider.cs | 6 +- .../Chapters/IChapterManager.cs | 7 -- .../Collections/CollectionCreationOptions.cs | 4 +- .../Connect/IConnectManager.cs | 45 ------- MediaBrowser.Controller/Dto/IDtoService.cs | 1 - .../Entities/AggregateFolder.cs | 2 +- .../Entities/Audio/Audio.cs | 9 +- .../Entities/Audio/MusicAlbum.cs | 4 +- .../Entities/Audio/MusicArtist.cs | 3 +- MediaBrowser.Controller/Entities/BaseItem.cs | 40 +++--- .../Entities/CollectionFolder.cs | 14 +-- MediaBrowser.Controller/Entities/Game.cs | 12 +- .../Entities/InternalItemsQuery.cs | 66 +++++----- .../Entities/InternalPeopleQuery.cs | 4 +- .../Entities/Movies/BoxSet.cs | 19 +-- .../Entities/Movies/Movie.cs | 9 +- .../Entities/MusicVideo.cs | 2 +- MediaBrowser.Controller/Entities/Photo.cs | 5 +- .../Entities/TV/Episode.cs | 12 +- MediaBrowser.Controller/Entities/TV/Season.cs | 7 +- MediaBrowser.Controller/Entities/TV/Series.cs | 8 +- MediaBrowser.Controller/Entities/Trailer.cs | 9 +- MediaBrowser.Controller/Entities/UserView.cs | 19 +-- MediaBrowser.Controller/Entities/Video.cs | 28 ++--- .../Library/IUserDataManager.cs | 1 - .../Library/ItemResolveArgs.cs | 8 +- .../LiveTv/LiveTvProgram.cs | 51 ++------ MediaBrowser.Controller/LiveTv/TimerInfo.cs | 4 +- .../MediaEncoding/EncodingHelper.cs | 33 ++--- .../MediaEncoding/EncodingJobInfo.cs | 10 +- .../MediaEncoding/EncodingJobOptions.cs | 1 - .../MediaEncoding/MediaInfoRequest.cs | 2 +- .../Net/AuthorizationInfo.cs | 8 +- .../Net/WebSocketConnectEventArgs.cs | 2 - .../Playlists/IPlaylistManager.cs | 1 - MediaBrowser.Controller/Playlists/Playlist.cs | 29 ++--- .../Providers/AlbumInfo.cs | 4 +- .../Providers/ImageRefreshOptions.cs | 4 +- .../Providers/ItemLookupInfo.cs | 2 - .../Providers/MetadataRefreshOptions.cs | 4 +- .../Providers/MetadataResult.cs | 2 +- MediaBrowser.Controller/Providers/SongInfo.cs | 7 +- .../Session/AuthenticationRequest.cs | 2 - .../Session/ISessionManager.cs | 1 - .../Session/SessionInfo.cs | 8 +- .../Subtitles/SubtitleSearchRequest.cs | 6 +- .../Images/LocalImageProvider.cs | 6 +- .../Channels/ChannelFeatures.cs | 9 +- .../Configuration/LibraryOptions.cs | 21 ++-- .../Configuration/MetadataOptions.cs | 21 ++-- .../Configuration/MetadataPluginSummary.cs | 8 +- .../Configuration/ServerConfiguration.cs | 49 ++++---- .../Configuration/UserConfiguration.cs | 8 +- .../ConnectAuthenticationExchangeResult.cs | 17 --- .../Connect/ConnectAuthenticationResult.cs | 17 --- .../Connect/ConnectAuthorization.cs | 4 +- .../Connect/ConnectAuthorizationRequest.cs | 19 --- MediaBrowser.Model/Devices/DeviceInfo.cs | 16 --- MediaBrowser.Model/Devices/DeviceQuery.cs | 5 - MediaBrowser.Model/Devices/DevicesOptions.cs | 5 +- MediaBrowser.Model/Dlna/ContainerProfile.cs | 8 +- .../Dlna/ContentFeatureBuilder.cs | 3 +- .../Dlna/ResolutionNormalizer.cs | 37 +++--- MediaBrowser.Model/Dlna/StreamInfo.cs | 8 +- MediaBrowser.Model/Dlna/SubtitleProfile.cs | 4 +- MediaBrowser.Model/Dto/BaseItemDto.cs | 35 ------ MediaBrowser.Model/Dto/ChapterInfoDto.cs | 38 ------ MediaBrowser.Model/Dto/GameSystemSummary.cs | 5 +- MediaBrowser.Model/Dto/MediaSourceInfo.cs | 9 +- MediaBrowser.Model/Dto/MetadataEditorInfo.cs | 12 +- MediaBrowser.Model/Dto/UserDto.cs | 1 - .../Entities/LibraryUpdateInfo.cs | 12 +- .../Entities/VirtualFolderInfo.cs | 2 +- .../Globalization/CultureDto.cs | 2 +- MediaBrowser.Model/Library/UserViewQuery.cs | 2 +- .../LiveTv/LiveTvChannelQuery.cs | 2 +- MediaBrowser.Model/LiveTv/LiveTvInfo.cs | 6 +- MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 18 +-- .../LiveTv/LiveTvServiceInfo.cs | 2 +- MediaBrowser.Model/LiveTv/ProgramQuery.cs | 117 ------------------ .../LiveTv/RecommendedProgramQuery.cs | 73 ----------- MediaBrowser.Model/MediaInfo/MediaInfo.cs | 16 ++- .../MediaInfo/PlaybackInfoRequest.cs | 1 - .../Notifications/NotificationOption.cs | 20 +-- .../Notifications/NotificationRequest.cs | 3 - .../Notifications/NotificationServiceInfo.cs | 8 -- .../Notifications/NotificationTypeInfo.cs | 16 +-- .../Playlists/PlaylistCreationRequest.cs | 5 +- .../Providers/SubtitleOptions.cs | 4 +- MediaBrowser.Model/Querying/QueryFilters.cs | 12 +- MediaBrowser.Model/Search/SearchQuery.cs | 6 +- .../Session/ClientCapabilities.cs | 6 +- MediaBrowser.Model/Session/SessionInfoDto.cs | 117 ------------------ MediaBrowser.Model/Sync/SyncJob.cs | 4 +- MediaBrowser.Model/Users/UserPolicy.cs | 16 +-- .../Chapters/ChapterManager.cs | 11 +- 99 files changed, 327 insertions(+), 1053 deletions(-) delete mode 100644 MediaBrowser.Controller/Connect/IConnectManager.cs delete mode 100644 MediaBrowser.Model/Connect/ConnectAuthenticationExchangeResult.cs delete mode 100644 MediaBrowser.Model/Connect/ConnectAuthenticationResult.cs delete mode 100644 MediaBrowser.Model/Connect/ConnectAuthorizationRequest.cs delete mode 100644 MediaBrowser.Model/Dto/ChapterInfoDto.cs delete mode 100644 MediaBrowser.Model/LiveTv/ProgramQuery.cs delete mode 100644 MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs delete mode 100644 MediaBrowser.Model/Notifications/NotificationServiceInfo.cs delete mode 100644 MediaBrowser.Model/Session/SessionInfoDto.cs diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index ae3577b7d0..ed1fe87917 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -2,7 +2,6 @@ using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Connect; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index 07b8185c5c..ed31cbd1d8 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -55,12 +55,11 @@ namespace MediaBrowser.Api return Request.Headers[name]; } - private static readonly string[] EmptyStringArray = Array.Empty(); public static string[] SplitValue(string value, char delim) { if (string.IsNullOrWhiteSpace(value)) { - return EmptyStringArray; + return Array.Empty(); } return value.Split(new[] { delim }, StringSplitOptions.RemoveEmptyEntries); diff --git a/MediaBrowser.Api/UserService.cs b/MediaBrowser.Api/UserService.cs index 29f3070a59..913a55b2b3 100644 --- a/MediaBrowser.Api/UserService.cs +++ b/MediaBrowser.Api/UserService.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Authentication; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -10,11 +11,9 @@ using MediaBrowser.Model.Connect; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Users; using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MediaBrowser.Model.Services; -using MediaBrowser.Controller.Authentication; namespace MediaBrowser.Api { diff --git a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs index becb3ea627..82308296f1 100644 --- a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs +++ b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Users; diff --git a/MediaBrowser.Controller/Chapters/IChapterManager.cs b/MediaBrowser.Controller/Chapters/IChapterManager.cs index 2a20eb365d..161e87094a 100644 --- a/MediaBrowser.Controller/Chapters/IChapterManager.cs +++ b/MediaBrowser.Controller/Chapters/IChapterManager.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Threading.Tasks; using MediaBrowser.Model.Entities; namespace MediaBrowser.Controller.Chapters @@ -9,12 +8,6 @@ namespace MediaBrowser.Controller.Chapters /// public interface IChapterManager { - /// - /// Gets the chapters. - /// - /// The item identifier. - /// List{ChapterInfo}. - /// /// Saves the chapters. /// diff --git a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs index 727b487a79..5363e035c3 100644 --- a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs +++ b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs @@ -20,8 +20,8 @@ namespace MediaBrowser.Controller.Collections public CollectionCreationOptions() { ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - ItemIdList = new string[] {}; - UserIds = new Guid[] {}; + ItemIdList = Array.Empty(); + UserIds = Array.Empty(); } } } diff --git a/MediaBrowser.Controller/Connect/IConnectManager.cs b/MediaBrowser.Controller/Connect/IConnectManager.cs deleted file mode 100644 index 8ac61bf2b1..0000000000 --- a/MediaBrowser.Controller/Connect/IConnectManager.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Model.Connect; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace MediaBrowser.Controller.Connect -{ - public interface IConnectManager - { - /// - /// Gets the wan API address. - /// - /// The wan API address. - string WanApiAddress { get; } - - /// - /// Links the user. - /// - /// The user identifier. - /// The connect username. - /// Task. - Task LinkUser(string userId, string connectUsername); - - /// - /// Removes the link. - /// - /// The user identifier. - /// Task. - Task RemoveConnect(string userId); - - User GetUserFromExchangeToken(string token); - - /// - /// Authenticates the specified username. - /// - Task Authenticate(string username, string password, string passwordMd5); - - /// - /// Determines whether [is authorization token valid] [the specified token]. - /// - /// The token. - /// true if [is authorization token valid] [the specified token]; otherwise, false. - bool IsAuthorizationTokenValid(string token); - } -} diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs index 219b367891..37e83e45a2 100644 --- a/MediaBrowser.Controller/Dto/IDtoService.cs +++ b/MediaBrowser.Controller/Dto/IDtoService.cs @@ -2,7 +2,6 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Querying; using System.Collections.Generic; -using MediaBrowser.Controller.Sync; namespace MediaBrowser.Controller.Dto { diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 4f4b3483cf..a4601c270d 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -20,7 +20,7 @@ namespace MediaBrowser.Controller.Entities { public AggregateFolder() { - PhysicalLocationsList = new string[] { }; + PhysicalLocationsList = Array.Empty(); } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index d07e31d8a4..1aeae6052f 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -2,13 +2,8 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.MediaInfo; using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Serialization; @@ -36,8 +31,8 @@ namespace MediaBrowser.Controller.Entities.Audio public Audio() { - Artists = new string[] {}; - AlbumArtists = new string[] {}; + Artists = Array.Empty(); + AlbumArtists = Array.Empty(); } public override double GetDefaultPrimaryImageAspectRatio() diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index 48b5c64b21..870e6e07e1 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -23,8 +23,8 @@ namespace MediaBrowser.Controller.Entities.Audio public MusicAlbum() { - Artists = new string[] {}; - AlbumArtists = new string[] {}; + Artists = Array.Empty(); + AlbumArtists = Array.Empty(); } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 2774dc9443..56ed10ced6 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -129,13 +129,12 @@ namespace MediaBrowser.Controller.Entities.Audio return base.IsSaveLocalMetadataEnabled(); } - private readonly Task _cachedTask = Task.FromResult(true); protected override Task ValidateChildrenInternal(IProgress progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService) { if (IsAccessedByName) { // Should never get in here anyway - return _cachedTask; + return Task.CompletedTask; } return base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index e80fe33875..a268e6d765 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -35,24 +35,24 @@ namespace MediaBrowser.Controller.Entities /// public abstract class BaseItem : IHasProviderIds, IHasLookupInfo { - protected static MetadataFields[] EmptyMetadataFieldsArray = new MetadataFields[] { }; - protected static MediaUrl[] EmptyMediaUrlArray = new MediaUrl[] { }; - protected static ItemImageInfo[] EmptyItemImageInfoArray = new ItemImageInfo[] { }; - public static readonly LinkedChild[] EmptyLinkedChildArray = new LinkedChild[] { }; + protected static MetadataFields[] EmptyMetadataFieldsArray = Array.Empty(); + protected static MediaUrl[] EmptyMediaUrlArray = Array.Empty(); + protected static ItemImageInfo[] EmptyItemImageInfoArray = Array.Empty(); + public static readonly LinkedChild[] EmptyLinkedChildArray = Array.Empty(); protected BaseItem() { - ThemeSongIds = new Guid[] {}; - ThemeVideoIds = new Guid[] {}; - Tags = new string[] {}; - Genres = new string[] {}; - Studios = new string[] {}; + ThemeSongIds = Array.Empty(); + ThemeVideoIds = Array.Empty(); + Tags = Array.Empty(); + Genres = Array.Empty(); + Studios = Array.Empty(); ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); LockedFields = EmptyMetadataFieldsArray; ImageInfos = EmptyItemImageInfoArray; - ProductionLocations = new string[] {}; - RemoteTrailers = new MediaUrl[] { }; - ExtraIds = new Guid[] {}; + ProductionLocations = Array.Empty(); + RemoteTrailers = Array.Empty(); + ExtraIds = Array.Empty(); } public static readonly char[] SlugReplaceChars = { '?', '/', '&' }; @@ -62,7 +62,6 @@ namespace MediaBrowser.Controller.Entities /// The supported image extensions /// public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" }; - public static readonly List SupportedImageExtensionsList = SupportedImageExtensions.ToList(); /// /// The trailer folder name @@ -2895,6 +2894,10 @@ namespace MediaBrowser.Controller.Entities return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName); } + /// + /// Gets or sets the remote trailers. + /// + /// The remote trailers. public MediaUrl[] RemoteTrailers { get; set; } public IEnumerable GetExtras() @@ -2913,21 +2916,24 @@ namespace MediaBrowser.Controller.Entities } public virtual bool IsHD { - get{ + get + { return Height >= 720; - } + } } public bool IsShortcut{ get; set;} public string ShortcutPath{ get; set;} public int Width { get; set; } public int Height { get; set; } public Guid[] ExtraIds { get; set; } - public virtual long GetRunTimeTicksForPlayState() { + public virtual long GetRunTimeTicksForPlayState() + { return RunTimeTicks ?? 0; } // what does this do? public static ExtraType[] DisplayExtraTypes = new[] {Model.Entities.ExtraType.ThemeSong, Model.Entities.ExtraType.ThemeVideo }; - public virtual bool SupportsExternalTransfer { + public virtual bool SupportsExternalTransfer + { get { return false; } diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 7292b166a0..75d6b93818 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -31,18 +31,10 @@ namespace MediaBrowser.Controller.Entities public CollectionFolder() { - PhysicalLocationsList = new string[] { }; - PhysicalFolderIds = new Guid[] { }; + PhysicalLocationsList = Array.Empty(); + PhysicalFolderIds = Array.Empty(); } - //public override double? GetDefaultPrimaryImageAspectRatio() - //{ - // double value = 16; - // value /= 9; - - // return value; - //} - [IgnoreDataMember] public override bool SupportsPlayedStatus { @@ -339,7 +331,7 @@ namespace MediaBrowser.Controller.Entities /// Task. protected override Task ValidateChildrenInternal(IProgress progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService) { - return Task.FromResult(true); + return Task.CompletedTask; } /// diff --git a/MediaBrowser.Controller/Entities/Game.cs b/MediaBrowser.Controller/Entities/Game.cs index 3d006a699c..4efc5648ea 100644 --- a/MediaBrowser.Controller/Entities/Game.cs +++ b/MediaBrowser.Controller/Entities/Game.cs @@ -12,10 +12,10 @@ namespace MediaBrowser.Controller.Entities { public Game() { - MultiPartGameFiles = new string[] {}; + MultiPartGameFiles = Array.Empty(); RemoteTrailers = EmptyMediaUrlArray; - LocalTrailerIds = new Guid[] {}; - RemoteTrailerIds = new Guid[] {}; + LocalTrailerIds = Array.Empty(); + RemoteTrailerIds = Array.Empty(); } public Guid[] LocalTrailerIds { get; set; } @@ -38,12 +38,6 @@ namespace MediaBrowser.Controller.Entities get { return false; } } - /// - /// Gets or sets the remote trailers. - /// - /// The remote trailers. - public MediaUrl[] RemoteTrailers { get; set; } - /// /// Gets the type of the media. /// diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index ff57c24714..bb99c0a84e 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using MediaBrowser.Model.Configuration; using System.Linq; using MediaBrowser.Controller.Dto; -using MediaBrowser.Model.Querying; namespace MediaBrowser.Controller.Entities { @@ -48,7 +47,6 @@ namespace MediaBrowser.Controller.Entities public string PresentationUniqueKey { get; set; } public string Path { get; set; } - public string PathNotStartsWith { get; set; } public string Name { get; set; } public string Person { get; set; } @@ -160,8 +158,6 @@ namespace MediaBrowser.Controller.Entities public bool EnableGroupByMetadataKey { get; set; } public bool? HasChapterImages { get; set; } - // why tuple vs value tuple? - //public Tuple[] OrderBy { get; set; } public ValueTuple[] OrderBy { get; set; } public DateTime? MinDateCreated { get; set; } @@ -180,44 +176,44 @@ namespace MediaBrowser.Controller.Entities public InternalItemsQuery() { - AlbumArtistIds = new Guid[] {}; - AlbumIds = new Guid[] {}; - AncestorIds = new Guid[] {}; - ArtistIds = new Guid[] {}; - BlockUnratedItems = new UnratedItem[] { }; - BoxSetLibraryFolders = new Guid[] {}; - ChannelIds = new Guid[] {}; - ContributingArtistIds = new Guid[] {}; + AlbumArtistIds = Array.Empty(); + AlbumIds = Array.Empty(); + AncestorIds = Array.Empty(); + ArtistIds = Array.Empty(); + BlockUnratedItems = Array.Empty(); + BoxSetLibraryFolders = Array.Empty(); + ChannelIds = Array.Empty(); + ContributingArtistIds = Array.Empty(); DtoOptions = new DtoOptions(); EnableTotalRecordCount = true; - ExcludeArtistIds = new Guid[] {}; - ExcludeInheritedTags = new string[] {}; - ExcludeItemIds = new Guid[] {}; - ExcludeItemTypes = new string[] {}; + ExcludeArtistIds = Array.Empty(); + ExcludeInheritedTags = Array.Empty(); + ExcludeItemIds = Array.Empty(); + ExcludeItemTypes = Array.Empty(); ExcludeProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - ExcludeTags = new string[] {}; - GenreIds = new Guid[] {}; - Genres = new string[] {}; + ExcludeTags = Array.Empty(); + GenreIds = Array.Empty(); + Genres = Array.Empty(); GroupByPresentationUniqueKey = true; HasAnyProviderId = new Dictionary(StringComparer.OrdinalIgnoreCase); - ImageTypes = new ImageType[] { }; - IncludeItemTypes = new string[] {}; - ItemIds = new Guid[] {}; - MediaTypes = new string[] {}; + ImageTypes = Array.Empty(); + IncludeItemTypes = Array.Empty(); + ItemIds = Array.Empty(); + MediaTypes = Array.Empty(); MinSimilarityScore = 20; - OfficialRatings = new string[] {}; + OfficialRatings = Array.Empty(); OrderBy = Array.Empty>(); - PersonIds = new Guid[] {}; - PersonTypes = new string[] {}; - PresetViews = new string[] {}; - SeriesStatuses = new SeriesStatus[] { }; - SourceTypes = new SourceType[] { }; - StudioIds = new Guid[] {}; - Tags = new string[] {}; - TopParentIds = new Guid[] {}; - TrailerTypes = new TrailerType[] { }; - VideoTypes = new VideoType[] { }; - Years = new int[] { }; + PersonIds = Array.Empty(); + PersonTypes = Array.Empty(); + PresetViews = Array.Empty(); + SeriesStatuses = Array.Empty(); + SourceTypes = Array.Empty(); + StudioIds = Array.Empty(); + Tags = Array.Empty(); + TopParentIds = Array.Empty(); + TrailerTypes = Array.Empty(); + VideoTypes = Array.Empty(); + Years = Array.Empty(); } public InternalItemsQuery(User user) diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs index 7e00834e30..ce3e9e070e 100644 --- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs @@ -14,8 +14,8 @@ namespace MediaBrowser.Controller.Entities public InternalPeopleQuery() { - PersonTypes = new string[] { }; - ExcludePersonTypes = new string[] { }; + PersonTypes = Array.Empty(); + ExcludePersonTypes = Array.Empty(); } } } diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 5918bf9811..e888a55825 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -19,8 +19,8 @@ namespace MediaBrowser.Controller.Entities.Movies public BoxSet() { RemoteTrailers = EmptyMediaUrlArray; - LocalTrailerIds = new Guid[] { }; - RemoteTrailerIds = new Guid[] { }; + LocalTrailerIds = Array.Empty(); + RemoteTrailerIds = Array.Empty(); DisplayOrder = ItemSortBy.PremiereDate; } @@ -52,12 +52,6 @@ namespace MediaBrowser.Controller.Entities.Movies public Guid[] LocalTrailerIds { get; set; } public Guid[] RemoteTrailerIds { get; set; } - /// - /// Gets or sets the remote trailers. - /// - /// The remote trailers. - public MediaUrl[] RemoteTrailers { get; set; } - /// /// Gets or sets the display order. /// @@ -70,12 +64,7 @@ namespace MediaBrowser.Controller.Entities.Movies } public override double GetDefaultPrimaryImageAspectRatio() - { - double value = 2; - value /= 3; - - return value; - } + => 2 / 3; public override UnratedItem GetBlockUnratedType() { @@ -254,7 +243,7 @@ namespace MediaBrowser.Controller.Entities.Movies return FlattenItems(boxset.GetLinkedChildren(), expandedFolders); } - return new BaseItem[] { }; + return Array.Empty(); } return new[] { item }; diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 878b1b860f..4f743991bc 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -6,8 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - -using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Serialization; @@ -32,8 +30,6 @@ namespace MediaBrowser.Controller.Entities.Movies public Guid[] LocalTrailerIds { get; set; } public Guid[] RemoteTrailerIds { get; set; } - public MediaUrl[] RemoteTrailers { get; set; } - /// /// Gets or sets the name of the TMDB collection. /// @@ -55,10 +51,7 @@ namespace MediaBrowser.Controller.Entities.Movies return 0; } - double value = 2; - value /= 3; - - return value; + return 2 / 3; } protected override async Task RefreshedOwnedItems(MetadataRefreshOptions options, List fileSystemChildren, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index 78f9d06718..4015a11780 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Controller.Entities public MusicVideo() { - Artists = new string[] {}; + Artists = Array.Empty(); } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs index 01c10831dc..662aa42495 100644 --- a/MediaBrowser.Controller/Entities/Photo.cs +++ b/MediaBrowser.Controller/Entities/Photo.cs @@ -58,6 +58,7 @@ namespace MediaBrowser.Controller.Entities public override double GetDefaultPrimaryImageAspectRatio() { + // REVIEW: @bond if (Width.HasValue && Height.HasValue) { double width = Width.Value; @@ -85,8 +86,8 @@ namespace MediaBrowser.Controller.Entities return base.GetDefaultPrimaryImageAspectRatio(); } - public int? Width { get; set; } - public int? Height { get; set; } + public new int? Width { get; set; } + public new int? Height { get; set; } public string CameraMake { get; set; } public string CameraModel { get; set; } public string Software { get; set; } diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 3a3a902a35..00e055c51a 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using System; @@ -19,13 +19,12 @@ namespace MediaBrowser.Controller.Entities.TV public Episode() { RemoteTrailers = EmptyMediaUrlArray; - LocalTrailerIds = new Guid[] {}; - RemoteTrailerIds = new Guid[] {}; + LocalTrailerIds = Array.Empty(); + RemoteTrailerIds = Array.Empty(); } public Guid[] LocalTrailerIds { get; set; } public Guid[] RemoteTrailerIds { get; set; } - public MediaUrl[] RemoteTrailers { get; set; } /// /// Gets the season in which it aired. @@ -112,10 +111,7 @@ namespace MediaBrowser.Controller.Entities.TV return 0; } - double value = 16; - value /= 9; - - return value; + return 16 / 9; } public override List GetUserDataKeys() diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index b5f77df55a..cb3a7f3458 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -102,10 +102,11 @@ namespace MediaBrowser.Controller.Entities.TV get { var seriesId = SeriesId; - if (seriesId.Equals(Guid.Empty)) { + if (seriesId == Guid.Empty) + { seriesId = FindSeriesId(); } - return !seriesId.Equals(Guid.Empty) ? (LibraryManager.GetItemById(seriesId) as Series) : null; + return seriesId == Guid.Empty ? null : (LibraryManager.GetItemById(seriesId) as Series); } } @@ -227,7 +228,7 @@ namespace MediaBrowser.Controller.Entities.TV public Guid FindSeriesId() { var series = FindParent(); - return series == null ? Guid.Empty: series.Id; + return series == null ? Guid.Empty : series.Id; } /// diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 88fde17608..d4a62626ed 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -23,9 +23,9 @@ namespace MediaBrowser.Controller.Entities.TV public Series() { RemoteTrailers = EmptyMediaUrlArray; - LocalTrailerIds = new Guid[] {}; - RemoteTrailerIds = new Guid[] {}; - AirDays = new DayOfWeek[] { }; + LocalTrailerIds = Array.Empty(); + RemoteTrailerIds = Array.Empty(); + AirDays = Array.Empty(); } public DayOfWeek[] AirDays { get; set; } @@ -73,8 +73,6 @@ namespace MediaBrowser.Controller.Entities.TV public Guid[] LocalTrailerIds { get; set; } public Guid[] RemoteTrailerIds { get; set; } - public MediaUrl[] RemoteTrailers { get; set; } - /// /// airdate, dvd or absolute /// diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs index 4f2a5631bf..2ef268ed18 100644 --- a/MediaBrowser.Controller/Entities/Trailer.cs +++ b/MediaBrowser.Controller/Entities/Trailer.cs @@ -15,18 +15,13 @@ namespace MediaBrowser.Controller.Entities { public Trailer() { - TrailerTypes = new TrailerType[] { }; + TrailerTypes = Array.Empty(); } public TrailerType[] TrailerTypes { get; set; } public override double GetDefaultPrimaryImageAspectRatio() - { - double value = 2; - value /= 3; - - return value; - } + => 2 / 3; public override UnratedItem GetBlockUnratedType() { diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 984cad481e..b7c9884ff1 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -1,21 +1,18 @@ using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.TV; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; using System.Linq; using MediaBrowser.Model.Serialization; using System.Threading.Tasks; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Collections; namespace MediaBrowser.Controller.Entities { public class UserView : Folder, IHasCollectionType { public string ViewType { get; set; } - public Guid DisplayParentId { get; set; } + public new Guid DisplayParentId { get; set; } public Guid? UserId { get; set; } @@ -68,14 +65,6 @@ namespace MediaBrowser.Controller.Entities } } - //public override double? GetDefaultPrimaryImageAspectRatio() - //{ - // double value = 16; - // value /= 9; - - // return value; - //} - public override int GetChildCount(User user) { return GetChildren(user, true).Count; @@ -161,8 +150,8 @@ namespace MediaBrowser.Controller.Entities public static bool IsEligibleForGrouping(Folder folder) { - var collectionFolder = folder as ICollectionFolder; - return collectionFolder != null && IsEligibleForGrouping(collectionFolder.CollectionType); + return folder is ICollectionFolder collectionFolder + && IsEligibleForGrouping(collectionFolder.CollectionType); } private static string[] ViewTypesEligibleForGrouping = new string[] @@ -195,7 +184,7 @@ namespace MediaBrowser.Controller.Entities protected override Task ValidateChildrenInternal(IProgress progress, System.Threading.CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, Providers.MetadataRefreshOptions refreshOptions, Providers.IDirectoryService directoryService) { - return Task.FromResult(true); + return Task.CompletedTask; } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 65f5b8382d..2db200ee27 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -10,7 +10,6 @@ using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; @@ -132,8 +131,6 @@ namespace MediaBrowser.Controller.Entities public bool HasSubtitles { get; set; } public bool IsPlaceHolder { get; set; } - public bool IsShortcut { get; set; } - public string ShortcutPath { get; set; } /// /// Gets or sets the default index of the video stream. @@ -173,7 +170,7 @@ namespace MediaBrowser.Controller.Entities } else { - return new string[] {}; + return Array.Empty(); } return mediaEncoder.GetPlayableStreamFileNames(Path, videoType); } @@ -186,9 +183,9 @@ namespace MediaBrowser.Controller.Entities public Video() { - AdditionalParts = new string[] {}; - LocalAlternateVersions = new string[] {}; - SubtitleFiles = new string[] {}; + AdditionalParts = Array.Empty(); + LocalAlternateVersions = Array.Empty(); + SubtitleFiles = Array.Empty(); LinkedAlternateVersions = EmptyLinkedChildArray; } @@ -215,10 +212,10 @@ namespace MediaBrowser.Controller.Entities { if (!string.IsNullOrEmpty(PrimaryVersionId)) { - var item = LibraryManager.GetItemById(PrimaryVersionId) as Video; - if (item != null) + var item = LibraryManager.GetItemById(PrimaryVersionId); + if (item is Video video) { - return item.MediaSourceCount; + return video.MediaSourceCount; } } return LinkedAlternateVersions.Length + LocalAlternateVersions.Length + 1; @@ -366,7 +363,7 @@ namespace MediaBrowser.Controller.Entities /// Gets the additional parts. /// /// IEnumerable{Video}. - public IEnumerable