Merge pull request #30 from jellyfin/master

Updating master
This commit is contained in:
BaronGreenback 2020-06-24 14:16:02 +01:00 committed by GitHub
commit 2486e48097
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
59 changed files with 995 additions and 399 deletions

View file

@ -0,0 +1,131 @@
jobs:
- job: BuildPackage
displayName: 'Build Packages'
strategy:
matrix:
CentOS.amd64:
BuildConfiguration: centos.amd64
Fedora.amd64:
BuildConfiguration: fedora.amd64
Debian.amd64:
BuildConfiguration: debian.amd64
Debian.arm64:
BuildConfiguration: debian.arm64
Debian.armhf:
BuildConfiguration: debian.armhf
Ubuntu.amd64:
BuildConfiguration: ubuntu.amd64
Ubuntu.arm64:
BuildConfiguration: ubuntu.arm64
Ubuntu.armhf:
BuildConfiguration: ubuntu.armhf
Linux.amd64:
BuildConfiguration: linux.amd64
Windows.amd64:
BuildConfiguration: windows.amd64
MacOS:
BuildConfiguration: macos
Portable:
BuildConfiguration: portable
pool:
vmImage: 'ubuntu-latest'
steps:
- script: 'docker build -f deployment/Dockerfile.$(BuildConfiguration) -t jellyfin-server-$(BuildConfiguration) deployment'
displayName: 'Build Dockerfile'
condition: or(startsWith(variables['Build.SourceBranch'], 'refs/tags'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))
- script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="yes" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
displayName: 'Run Dockerfile (unstable)'
condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
- script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="no" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
displayName: 'Run Dockerfile (stable)'
condition: startsWith(variables['Build.SourceBranch'], 'refs/tags')
- task: PublishPipelineArtifact@1
displayName: 'Publish Release'
condition: or(startsWith(variables['Build.SourceBranch'], 'refs/tags'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))
inputs:
targetPath: '$(Build.SourcesDirectory)/deployment/dist'
artifactName: 'jellyfin-server-$(BuildConfiguration)'
- task: CopyFilesOverSSH@0
displayName: 'Upload artifacts to repository server'
condition: or(startsWith(variables['Build.SourceBranch'], 'refs/tags'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))
inputs:
sshEndpoint: repository
sourceFolder: '$(Build.SourcesDirectory)/deployment/dist'
contents: '**'
targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)'
- job: BuildDocker
displayName: 'Build Docker'
strategy:
matrix:
amd64:
BuildConfiguration: amd64
arm64:
BuildConfiguration: arm64
armhf:
BuildConfiguration: armhf
pool:
vmImage: 'ubuntu-latest'
steps:
- task: Docker@2
displayName: 'Push Unstable Image'
condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
inputs:
repository: 'jellyfin/jellyfin-server'
command: buildAndPush
buildContext: '.'
Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
containerRegistry: Docker Hub
tags: |
unstable-$(Build.BuildNumber)-$(BuildConfiguration)
unstable-$(BuildConfiguration)
- task: Docker@2
displayName: 'Push Stable Image'
condition: startsWith(variables['Build.SourceBranch'], 'refs/tags')
inputs:
repository: 'jellyfin/jellyfin-server'
command: buildAndPush
buildContext: '.'
Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
containerRegistry: Docker Hub
tags: |
stable-$(Build.BuildNumber)-$(BuildConfiguration)
stable-$(BuildConfiguration)
- job: CollectArtifacts
displayName: 'Collect Artifacts'
dependsOn:
- BuildPackage
- BuildDocker
condition: and(succeeded('BuildPackage'), succeeded('BuildDocker'))
pool:
vmImage: 'ubuntu-latest'
steps:
- task: SSH@0
displayName: 'Update Unstable Repository'
condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
inputs:
sshEndpoint: repository
runOptions: 'inline'
inline: 'sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable'
- task: SSH@0
displayName: 'Update Stable Repository'
condition: startsWith(variables['Build.SourceBranch'], 'refs/tags')
inputs:
sshEndpoint: repository
runOptions: 'inline'
inline: 'sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber)'

View file

@ -43,3 +43,5 @@ jobs:
NugetPackageName: Jellyfin.Common
AssemblyFileName: MediaBrowser.Common.dll
LinuxImage: 'ubuntu-latest'
- template: azure-pipelines-package.yml

3
.gitignore vendored
View file

@ -39,7 +39,6 @@ ProgramData*/
CorePlugins*/
ProgramData-Server*/
ProgramData-UI*/
MediaBrowser.WebDashboard/jellyfin-web/**
#################
## Visual Studio
@ -276,4 +275,4 @@ BenchmarkDotNet.Artifacts
# Ignore web artifacts from native builds
web/
web-src.*
MediaBrowser.WebDashboard/jellyfin-web/
MediaBrowser.WebDashboard/jellyfin-web

12
.vscode/launch.json vendored
View file

@ -1,9 +1,6 @@
{
// 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": [
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
@ -24,5 +21,8 @@
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
],
"env": {
"DOTNET_CLI_TELEMETRY_OPTOUT": "1"
}
}

7
.vscode/tasks.json vendored
View file

@ -21,5 +21,10 @@
],
"problemMatcher": "$msCompile"
}
]
],
"options": {
"env": {
"DOTNET_CLI_TELEMETRY_OPTOUT": "1"
}
}
}

View file

@ -35,8 +35,6 @@ namespace Emby.Dlna.Main
private readonly IServerConfigurationManager _config;
private readonly ILogger<DlnaEntryPoint> _logger;
private readonly IServerApplicationHost _appHost;
private PlayToManager _manager;
private readonly ISessionManager _sessionManager;
private readonly IHttpClient _httpClient;
private readonly ILibraryManager _libraryManager;
@ -47,14 +45,13 @@ namespace Emby.Dlna.Main
private readonly ILocalizationManager _localization;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IDeviceDiscovery _deviceDiscovery;
private SsdpDevicePublisher _Publisher;
private readonly ISocketFactory _socketFactory;
private readonly INetworkManager _networkManager;
private readonly object _syncLock = new object();
private PlayToManager _manager;
private SsdpDevicePublisher _publisher;
private ISsdpCommunicationsServer _communicationsServer;
internal IContentDirectory ContentDirectory { get; private set; }
@ -181,7 +178,7 @@ namespace Emby.Dlna.Main
var enableMultiSocketBinding = OperatingSystem.Id == OperatingSystemId.Windows ||
OperatingSystem.Id == OperatingSystemId.Linux;
_communicationsServer = new SsdpCommunicationsServer(_config, _socketFactory, _networkManager, _logger, enableMultiSocketBinding)
_communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
{
IsShared = true
};
@ -232,20 +229,22 @@ namespace Emby.Dlna.Main
return;
}
if (_Publisher != null)
if (_publisher != null)
{
return;
}
try
{
_Publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost);
_Publisher.LogFunction = LogMessage;
_Publisher.SupportPnpRootDevice = false;
_publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost)
{
LogFunction = LogMessage,
SupportPnpRootDevice = false
};
await RegisterServerEndpoints().ConfigureAwait(false);
_Publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
_publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
}
catch (Exception ex)
{
@ -267,6 +266,12 @@ namespace Emby.Dlna.Main
continue;
}
// Limit to LAN addresses only
if (!_networkManager.IsAddressInSubnets(address, true, true))
{
continue;
}
var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
_logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
@ -288,13 +293,13 @@ namespace Emby.Dlna.Main
};
SetProperies(device, fullService);
_Publisher.AddDevice(device);
_publisher.AddDevice(device);
var embeddedDevices = new[]
{
"urn:schemas-upnp-org:service:ContentDirectory:1",
"urn:schemas-upnp-org:service:ConnectionManager:1",
//"urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
// "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
};
foreach (var subDevice in embeddedDevices)
@ -326,7 +331,7 @@ namespace Emby.Dlna.Main
private void SetProperies(SsdpDevice device, string fullDeviceType)
{
var service = fullDeviceType.Replace("urn:", string.Empty).Replace(":1", string.Empty);
var service = fullDeviceType.Replace("urn:", string.Empty, StringComparison.OrdinalIgnoreCase).Replace(":1", string.Empty, StringComparison.OrdinalIgnoreCase);
var serviceParts = service.Split(':');
@ -337,7 +342,6 @@ namespace Emby.Dlna.Main
device.DeviceType = serviceParts[2];
}
private readonly object _syncLock = new object();
private void StartPlayToManager()
{
lock (_syncLock)
@ -416,11 +420,11 @@ namespace Emby.Dlna.Main
public void DisposeDevicePublisher()
{
if (_Publisher != null)
if (_publisher != null)
{
_logger.LogInformation("Disposing SsdpDevicePublisher");
_Publisher.Dispose();
_Publisher = null;
_publisher.Dispose();
_publisher = null;
}
}
}

View file

@ -1234,7 +1234,7 @@ namespace Emby.Server.Implementations
if (addresses.Count == 0)
{
addresses.AddRange(_networkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
addresses.AddRange(_networkManager.GetLocalIpAddresses());
}
var resultList = new List<IPAddress>();

View file

@ -17,7 +17,6 @@ namespace Emby.Server.Implementations
{
{ HostWebClientKey, bool.TrueString },
{ HttpListenerHost.DefaultRedirectKey, "web/index.html" },
{ InstallationManager.PluginManifestUrlKey, "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" },
{ FfmpegProbeSizeKey, "1G" },
{ FfmpegAnalyzeDurationKey, "200M" },
{ PlaylistsAllowDuplicatesKey, bool.TrueString }

View file

@ -585,7 +585,7 @@ namespace Emby.Server.Implementations.HttpServer
if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue)
{
var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest, _logger)
var hasHeaders = new RangeRequestWriter(rangeHeader, totalContentLength.Value, stream, contentType, isHeadRequest)
{
OnComplete = options.OnComplete
};
@ -622,8 +622,11 @@ namespace Emby.Server.Implementations.HttpServer
/// <summary>
/// Adds the caching responseHeaders.
/// </summary>
private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration,
bool noCache, DateTime? lastModifiedDate)
private void AddCachingHeaders(
IDictionary<string, string> responseHeaders,
TimeSpan? cacheDuration,
bool noCache,
DateTime? lastModifiedDate)
{
if (noCache)
{

View file

@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@ -8,52 +9,17 @@ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
public class RangeRequestWriter : IAsyncStreamWriter, IHttpResult
{
/// <summary>
/// Gets or sets the source stream.
/// </summary>
/// <value>The source stream.</value>
private Stream SourceStream { get; set; }
private string RangeHeader { get; set; }
private bool IsHeadRequest { get; set; }
private long RangeStart { get; set; }
private long RangeEnd { get; set; }
private long RangeLength { get; set; }
private long TotalContentLength { get; set; }
public Action OnComplete { get; set; }
private readonly ILogger _logger;
private const int BufferSize = 81920;
/// <summary>
/// The _options.
/// </summary>
private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
/// <summary>
/// The us culture.
/// </summary>
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// Additional HTTP Headers.
/// </summary>
/// <value>The headers.</value>
public IDictionary<string, string> Headers => _options;
private List<KeyValuePair<long, long?>> _requestedRanges;
/// <summary>
/// Initializes a new instance of the <see cref="RangeRequestWriter" /> class.
@ -63,8 +29,7 @@ namespace Emby.Server.Implementations.HttpServer
/// <param name="source">The source.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
/// <param name="logger">The logger instance.</param>
public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger)
public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest)
{
if (string.IsNullOrEmpty(contentType))
{
@ -74,7 +39,6 @@ namespace Emby.Server.Implementations.HttpServer
RangeHeader = rangeHeader;
SourceStream = source;
IsHeadRequest = isHeadRequest;
this._logger = logger;
ContentType = contentType;
Headers[HeaderNames.ContentType] = contentType;
@ -84,6 +48,81 @@ namespace Emby.Server.Implementations.HttpServer
SetRangeValues(contentLength);
}
/// <summary>
/// Gets or sets the source stream.
/// </summary>
/// <value>The source stream.</value>
private Stream SourceStream { get; set; }
private string RangeHeader { get; set; }
private bool IsHeadRequest { get; set; }
private long RangeStart { get; set; }
private long RangeEnd { get; set; }
private long RangeLength { get; set; }
private long TotalContentLength { get; set; }
public Action OnComplete { get; set; }
/// <summary>
/// Additional HTTP Headers
/// </summary>
/// <value>The headers.</value>
public IDictionary<string, string> Headers => _options;
/// <summary>
/// Gets the requested ranges.
/// </summary>
/// <value>The requested ranges.</value>
protected List<KeyValuePair<long, long?>> RequestedRanges
{
get
{
if (_requestedRanges == null)
{
_requestedRanges = new List<KeyValuePair<long, long?>>();
// Example: bytes=0-,32-63
var ranges = RangeHeader.Split('=')[1].Split(',');
foreach (var range in ranges)
{
var vals = range.Split('-');
long start = 0;
long? end = null;
if (!string.IsNullOrEmpty(vals[0]))
{
start = long.Parse(vals[0], CultureInfo.InvariantCulture);
}
if (!string.IsNullOrEmpty(vals[1]))
{
end = long.Parse(vals[1], CultureInfo.InvariantCulture);
}
_requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
}
}
return _requestedRanges;
}
}
public string ContentType { get; set; }
public IRequest RequestContext { get; set; }
public object Response { get; set; }
public int Status { get; set; }
public HttpStatusCode StatusCode
{
get => (HttpStatusCode)Status;
set => Status = (int)value;
}
/// <summary>
/// Sets the range values.
/// </summary>
@ -115,50 +154,6 @@ namespace Emby.Server.Implementations.HttpServer
}
}
/// <summary>
/// The _requested ranges.
/// </summary>
private List<KeyValuePair<long, long?>> _requestedRanges;
/// <summary>
/// Gets the requested ranges.
/// </summary>
/// <value>The requested ranges.</value>
protected List<KeyValuePair<long, long?>> RequestedRanges
{
get
{
if (_requestedRanges == null)
{
_requestedRanges = new List<KeyValuePair<long, long?>>();
// Example: bytes=0-,32-63
var ranges = RangeHeader.Split('=')[1].Split(',');
foreach (var range in ranges)
{
var vals = range.Split('-');
long start = 0;
long? end = null;
if (!string.IsNullOrEmpty(vals[0]))
{
start = long.Parse(vals[0], UsCulture);
}
if (!string.IsNullOrEmpty(vals[1]))
{
end = long.Parse(vals[1], UsCulture);
}
_requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
}
}
return _requestedRanges;
}
}
public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
{
try
@ -174,59 +169,44 @@ namespace Emby.Server.Implementations.HttpServer
// If the requested range is "0-", we can optimize by just doing a stream copy
if (RangeEnd >= TotalContentLength - 1)
{
await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false);
await source.CopyToAsync(responseStream, BufferSize, cancellationToken).ConfigureAwait(false);
}
else
{
await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false);
await CopyToInternalAsync(source, responseStream, RangeLength, cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
if (OnComplete != null)
{
OnComplete();
}
OnComplete?.Invoke();
}
}
private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength)
private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
{
var array = new byte[BufferSize];
int bytesRead;
while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
var array = ArrayPool<byte>.Shared.Rent(BufferSize);
try
{
if (bytesRead == 0)
int bytesRead;
while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
break;
}
var bytesToCopy = Math.Min(bytesRead, copyLength);
var bytesToCopy = Math.Min(bytesRead, copyLength);
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy), cancellationToken).ConfigureAwait(false);
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy)).ConfigureAwait(false);
copyLength -= bytesToCopy;
copyLength -= bytesToCopy;
if (copyLength <= 0)
{
break;
if (copyLength <= 0)
{
break;
}
}
}
}
public string ContentType { get; set; }
public IRequest RequestContext { get; set; }
public object Response { get; set; }
public int Status { get; set; }
public HttpStatusCode StatusCode
{
get => (HttpStatusCode)Status;
set => Status = (int)value;
finally
{
ArrayPool<byte>.Shared.Return(array);
}
}
}
}

View file

@ -51,6 +51,22 @@ namespace Emby.Server.Implementations.HttpServer.Security
return user;
}
public AuthorizationInfo Authenticate(HttpRequest request)
{
var auth = _authorizationContext.GetAuthorizationInfo(request);
if (auth?.User == null)
{
return null;
}
if (auth.User.HasPermission(PermissionKind.IsDisabled))
{
throw new SecurityException("User account has been disabled.");
}
return auth;
}
private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
{
// This code is executed before the service

View file

@ -8,6 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer.Security
@ -38,6 +39,14 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(requestContext);
}
public AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext)
{
var auth = GetAuthorizationDictionary(requestContext);
var (authInfo, _) =
GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query);
return authInfo;
}
/// <summary>
/// Gets the authorization.
/// </summary>
@ -46,7 +55,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
private AuthorizationInfo GetAuthorization(IRequest httpReq)
{
var auth = GetAuthorizationDictionary(httpReq);
var (authInfo, originalAuthInfo) =
GetAuthorizationInfoFromDictionary(auth, httpReq.Headers, httpReq.QueryString);
if (originalAuthInfo != null)
{
httpReq.Items["OriginalAuthenticationInfo"] = originalAuthInfo;
}
httpReq.Items["AuthorizationInfo"] = authInfo;
return authInfo;
}
private (AuthorizationInfo authInfo, AuthenticationInfo originalAuthenticationInfo) GetAuthorizationInfoFromDictionary(
in Dictionary<string, string> auth,
in IHeaderDictionary headers,
in IQueryCollection queryString)
{
string deviceId = null;
string device = null;
string client = null;
@ -64,20 +89,20 @@ namespace Emby.Server.Implementations.HttpServer.Security
if (string.IsNullOrEmpty(token))
{
token = httpReq.Headers["X-Emby-Token"];
token = headers["X-Emby-Token"];
}
if (string.IsNullOrEmpty(token))
{
token = httpReq.Headers["X-MediaBrowser-Token"];
token = headers["X-MediaBrowser-Token"];
}
if (string.IsNullOrEmpty(token))
{
token = httpReq.QueryString["api_key"];
token = queryString["api_key"];
}
var info = new AuthorizationInfo
var authInfo = new AuthorizationInfo
{
Client = client,
Device = device,
@ -86,6 +111,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
Token = token
};
AuthenticationInfo originalAuthenticationInfo = null;
if (!string.IsNullOrWhiteSpace(token))
{
var result = _authRepo.Get(new AuthenticationInfoQuery
@ -93,81 +119,77 @@ namespace Emby.Server.Implementations.HttpServer.Security
AccessToken = token
});
var tokenInfo = result.Items.Count > 0 ? result.Items[0] : null;
originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null;
if (tokenInfo != null)
if (originalAuthenticationInfo != null)
{
var updateToken = false;
// TODO: Remove these checks for IsNullOrWhiteSpace
if (string.IsNullOrWhiteSpace(info.Client))
if (string.IsNullOrWhiteSpace(authInfo.Client))
{
info.Client = tokenInfo.AppName;
authInfo.Client = originalAuthenticationInfo.AppName;
}
if (string.IsNullOrWhiteSpace(info.DeviceId))
if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
{
info.DeviceId = tokenInfo.DeviceId;
authInfo.DeviceId = originalAuthenticationInfo.DeviceId;
}
// Temporary. TODO - allow clients to specify that the token has been shared with a casting device
var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
if (string.IsNullOrWhiteSpace(info.Device))
if (string.IsNullOrWhiteSpace(authInfo.Device))
{
info.Device = tokenInfo.DeviceName;
authInfo.Device = originalAuthenticationInfo.DeviceName;
}
else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
{
if (allowTokenInfoUpdate)
{
updateToken = true;
tokenInfo.DeviceName = info.Device;
originalAuthenticationInfo.DeviceName = authInfo.Device;
}
}
if (string.IsNullOrWhiteSpace(info.Version))
if (string.IsNullOrWhiteSpace(authInfo.Version))
{
info.Version = tokenInfo.AppVersion;
authInfo.Version = originalAuthenticationInfo.AppVersion;
}
else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
{
if (allowTokenInfoUpdate)
{
updateToken = true;
tokenInfo.AppVersion = info.Version;
originalAuthenticationInfo.AppVersion = authInfo.Version;
}
}
if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3)
if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3)
{
tokenInfo.DateLastActivity = DateTime.UtcNow;
originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow;
updateToken = true;
}
if (!tokenInfo.UserId.Equals(Guid.Empty))
if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty))
{
info.User = _userManager.GetUserById(tokenInfo.UserId);
authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId);
if (info.User != null && !string.Equals(info.User.Username, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase))
if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase))
{
tokenInfo.UserName = info.User.Username;
originalAuthenticationInfo.UserName = authInfo.User.Username;
updateToken = true;
}
}
if (updateToken)
{
_authRepo.Update(tokenInfo);
_authRepo.Update(originalAuthenticationInfo);
}
}
httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
}
httpReq.Items["AuthorizationInfo"] = info;
return info;
return (authInfo, originalAuthenticationInfo);
}
/// <summary>
@ -187,6 +209,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(auth);
}
/// <summary>
/// Gets the auth.
/// </summary>
/// <param name="httpReq">The HTTP req.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
private Dictionary<string, string> GetAuthorizationDictionary(HttpRequest httpReq)
{
var auth = httpReq.Headers["X-Emby-Authorization"];
if (string.IsNullOrEmpty(auth))
{
auth = httpReq.Headers[HeaderNames.Authorization];
}
return GetAuthorization(auth);
}
/// <summary>
/// Gets the authorization.
/// </summary>

View file

@ -36,11 +36,6 @@ namespace Emby.Server.Implementations
/// </summary>
string RestartArgs { get; }
/// <summary>
/// Gets the value of the --plugin-manifest-url command line option.
/// </summary>
string PluginManifestUrl { get; }
/// <summary>
/// Gets the value of the --published-server-url command line option.
/// </summary>

View file

@ -2897,7 +2897,8 @@ namespace Emby.Server.Implementations.Library
}
catch (HttpException ex)
{
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{
continue;
}

View file

@ -1,5 +1,5 @@
{
"LabelRunningTimeValue": "Duración: {0}",
"LabelRunningTimeValue": "Tiempo en ejecución: {0}",
"ValueSpecialEpisodeName": "Especial - {0}",
"Sync": "Sincronizar",
"Songs": "Canciones",

View file

@ -0,0 +1,62 @@
{
"NotificationOptionUserLockedOut": "प्रयोगकर्ता प्रतिबन्धित",
"NotificationOptionTaskFailed": "निर्धारित कार्य विफलता",
"NotificationOptionServerRestartRequired": "सर्भर रिस्टार्ट आवाश्यक छ",
"NotificationOptionPluginUpdateInstalled": "प्लगइन अद्यावधिक स्थापना भयो",
"NotificationOptionPluginUninstalled": "प्लगइन विस्थापित",
"NotificationOptionPluginInstalled": "प्लगइन स्थापना भयो",
"NotificationOptionPluginError": "प्लगइन असफलता",
"NotificationOptionNewLibraryContent": "नयाँ सामग्री थपियो",
"NotificationOptionInstallationFailed": "स्थापना असफलता",
"NotificationOptionCameraImageUploaded": "क्यामेरा फोटो अपलोड गरियो",
"NotificationOptionAudioPlaybackStopped": "ध्वनि प्रक्षेपण रोकियो",
"NotificationOptionAudioPlayback": "ध्वनि प्रक्षेपण शुरू भयो",
"NotificationOptionApplicationUpdateInstalled": "अनुप्रयोग अद्यावधिक स्थापना भयो",
"NotificationOptionApplicationUpdateAvailable": "अनुप्रयोग अपडेट उपलब्ध छ",
"NewVersionIsAvailable": "जेलीफिन सर्भर को नयाँ संस्करण डाउनलोड को लागी उपलब्ध छ।",
"NameSeasonUnknown": "अज्ञात श्रृंखला",
"NameSeasonNumber": "श्रृंखला {0}",
"NameInstallFailed": "{0} स्थापना असफल भयो",
"MusicVideos": "सांगीतिक भिडियोहरू",
"Music": "संगीत",
"Movies": "चलचित्रहरू",
"MixedContent": "मिश्रित सामग्री",
"MessageServerConfigurationUpdated": "सर्भर कन्फिगरेसन अद्यावधिक गरिएको छ",
"MessageNamedServerConfigurationUpdatedWithValue": "सर्भर कन्फिगरेसन विभाग {0} अद्यावधिक गरिएको छ",
"MessageApplicationUpdatedTo": "जेलीफिन सर्भर {0} मा अद्यावधिक गरिएको छ",
"MessageApplicationUpdated": "जेलीफिन सर्भर अपडेट गरिएको छ",
"Latest": "नविनतम",
"LabelRunningTimeValue": "कुल समय: {0}",
"LabelIpAddressValue": "आईपी ठेगाना: {0}",
"ItemRemovedWithName": "{0}लाई पुस्तकालयबाट हटाईयो",
"ItemAddedWithName": "{0} लाईब्रेरीमा थपियो",
"Inherit": "इनहेरिट",
"HomeVideos": "घरेलु भिडियोहरू",
"HeaderRecordingGroups": "रेकर्ड समूहहरू",
"HeaderNextUp": "आगामी",
"HeaderLiveTV": "प्रत्यक्ष टिभी",
"HeaderFavoriteSongs": "मनपर्ने गीतहरू",
"HeaderFavoriteShows": "मनपर्ने कार्यक्रमहरू",
"HeaderFavoriteEpisodes": "मनपर्ने एपिसोडहरू",
"HeaderFavoriteArtists": "मनपर्ने कलाकारहरू",
"HeaderFavoriteAlbums": "मनपर्ने एल्बमहरू",
"HeaderContinueWatching": "हेर्न जारी राख्नुहोस्",
"HeaderCameraUploads": "क्यामेरा अपलोडहरू",
"HeaderAlbumArtists": "एल्बमका कलाकारहरू",
"Genres": "विधाहरू",
"Folders": "फोल्डरहरू",
"Favorites": "मनपर्ने",
"FailedLoginAttemptWithUserName": "{0}को लग इन प्रयास असफल",
"DeviceOnlineWithName": "{0}को साथ जडित",
"DeviceOfflineWithName": "{0}बाट विच्छेदन भयो",
"Collections": "संग्रह",
"ChapterNameValue": "अध्याय {0}",
"Channels": "च्यानलहरू",
"AppDeviceValues": "अनुप्रयोग: {0}, उपकरण: {1}",
"AuthenticationSucceededWithUserName": "{0} सफलतापूर्वक प्रमाणीकरण गरियो",
"CameraImageUploadedFrom": "{0}बाट नयाँ क्यामेरा छवि अपलोड गरिएको छ",
"Books": "पुस्तकहरु",
"Artists": "कलाकारहरू",
"Application": "अनुप्रयोगहरू",
"Albums": "एल्बमहरू"
}

View file

@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
@ -13,6 +12,9 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Networking
{
/// <summary>
/// Class to take care of network interface management.
/// </summary>
public class NetworkManager : INetworkManager
{
private readonly ILogger<NetworkManager> _logger;
@ -21,8 +23,14 @@ namespace Emby.Server.Implementations.Networking
private readonly object _localIpAddressSyncLock = new object();
private readonly object _subnetLookupLock = new object();
private Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
private readonly Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
private List<PhysicalAddress> _macAddresses;
/// <summary>
/// Initializes a new instance of the <see cref="NetworkManager"/> class.
/// </summary>
/// <param name="logger">Logger to use for messages.</param>
public NetworkManager(ILogger<NetworkManager> logger)
{
_logger = logger;
@ -31,8 +39,10 @@ namespace Emby.Server.Implementations.Networking
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
}
/// <inheritdoc/>
public event EventHandler NetworkChanged;
/// <inheritdoc/>
public Func<string[]> LocalSubnetsFn { get; set; }
private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
@ -58,13 +68,14 @@ namespace Emby.Server.Implementations.Networking
NetworkChanged?.Invoke(this, EventArgs.Empty);
}
public IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface = true)
/// <inheritdoc/>
public IPAddress[] GetLocalIpAddresses()
{
lock (_localIpAddressSyncLock)
{
if (_localIpAddresses == null)
{
var addresses = GetLocalIpAddressesInternal(ignoreVirtualInterface).ToArray();
var addresses = GetLocalIpAddressesInternal().ToArray();
_localIpAddresses = addresses;
}
@ -73,42 +84,47 @@ namespace Emby.Server.Implementations.Networking
}
}
private List<IPAddress> GetLocalIpAddressesInternal(bool ignoreVirtualInterface)
private List<IPAddress> GetLocalIpAddressesInternal()
{
var list = GetIPsDefault(ignoreVirtualInterface).ToList();
var list = GetIPsDefault().ToList();
if (list.Count == 0)
{
list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList();
}
var listClone = list.ToList();
var listClone = new List<IPAddress>();
return list
var subnets = LocalSubnetsFn();
foreach (var i in list)
{
if (i.IsIPv6LinkLocal || i.ToString().StartsWith("169.254.", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (Array.IndexOf(subnets, $"[{i}]") == -1)
{
listClone.Add(i);
}
}
return listClone
.OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
.ThenBy(i => listClone.IndexOf(i))
.Where(FilterIpAddress)
// .ThenBy(i => listClone.IndexOf(i))
.GroupBy(i => i.ToString())
.Select(x => x.First())
.ToList();
}
private static bool FilterIpAddress(IPAddress address)
{
if (address.IsIPv6LinkLocal
|| address.ToString().StartsWith("169.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
/// <inheritdoc/>
public bool IsInPrivateAddressSpace(string endpoint)
{
return IsInPrivateAddressSpace(endpoint, true);
}
// Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address
private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
{
if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
@ -116,12 +132,12 @@ namespace Emby.Server.Implementations.Networking
return true;
}
// ipv6
// IPV6
if (endpoint.Split('.').Length > 4)
{
// Handle ipv4 mapped to ipv6
var originalEndpoint = endpoint;
endpoint = endpoint.Replace("::ffff:", string.Empty);
endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase);
if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
{
@ -130,23 +146,21 @@ namespace Emby.Server.Implementations.Networking
}
// Private address space:
// http://en.wikipedia.org/wiki/Private_network
if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
{
return Is172AddressPrivate(endpoint);
}
if (endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (checkSubnets && endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase))
byte[] octet = IPAddress.Parse(endpoint).GetAddressBytes();
if ((octet[0] == 10) ||
(octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918
(octet[0] == 192 && octet[1] == 168) || // RFC1918
(octet[0] == 127) || // RFC1122
(octet[0] == 169 && octet[1] == 254)) // RFC3927
{
return true;
return false;
}
if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
@ -157,6 +171,7 @@ namespace Emby.Server.Implementations.Networking
return false;
}
/// <inheritdoc/>
public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
{
if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
@ -179,6 +194,7 @@ namespace Emby.Server.Implementations.Networking
return false;
}
// Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart
private List<string> GetSubnets(string endpointFirstPart)
{
lock (_subnetLookupLock)
@ -224,46 +240,75 @@ namespace Emby.Server.Implementations.Networking
}
}
private static bool Is172AddressPrivate(string endpoint)
{
for (var i = 16; i <= 31; i++)
{
if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <inheritdoc/>
public bool IsInLocalNetwork(string endpoint)
{
return IsInLocalNetworkInternal(endpoint, true);
}
/// <inheritdoc/>
public bool IsAddressInSubnets(string addressString, string[] subnets)
{
return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets);
}
/// <inheritdoc/>
public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC)
{
byte[] octet = address.GetAddressBytes();
if ((octet[0] == 127) || // RFC1122
(octet[0] == 169 && octet[1] == 254)) // RFC3927
{
// don't use on loopback or 169 interfaces
return false;
}
string addressString = address.ToString();
string excludeAddress = "[" + addressString + "]";
var subnets = LocalSubnetsFn();
// Exclude any addresses if they appear in the LAN list in [ ]
if (Array.IndexOf(subnets, excludeAddress) != -1)
{
return false;
}
return IsAddressInSubnets(address, addressString, subnets);
}
/// <summary>
/// Checks if the give address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
/// </summary>
/// <param name="address">IPAddress version of the address.</param>
/// <param name="addressString">The address to check.</param>
/// <param name="subnets">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
/// <returns><c>false</c>if the address isn't in the subnets, <c>true</c> otherwise.</returns>
private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
{
foreach (var subnet in subnets)
{
var normalizedSubnet = subnet.Trim();
// Is the subnet a host address and does it match the address being passes?
if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
{
return true;
}
// Parse CIDR subnets and see if address falls within it.
if (normalizedSubnet.Contains('/', StringComparison.Ordinal))
{
var ipNetwork = IPNetwork.Parse(normalizedSubnet);
if (ipNetwork.Contains(address))
try
{
return true;
var ipNetwork = IPNetwork.Parse(normalizedSubnet);
if (ipNetwork.Contains(address))
{
return true;
}
}
catch
{
// Ignoring - invalid subnet passed encountered.
}
}
}
@ -288,7 +333,7 @@ namespace Emby.Server.Implementations.Networking
var localSubnets = localSubnetsFn();
foreach (var subnet in localSubnets)
{
// only validate if there's at least one valid entry
// Only validate if there's at least one valid entry.
if (!string.IsNullOrWhiteSpace(subnet))
{
return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
@ -345,7 +390,7 @@ namespace Emby.Server.Implementations.Networking
}
catch (InvalidOperationException)
{
// Can happen with reverse proxy or IIS url rewriting
// Can happen with reverse proxy or IIS url rewriting?
}
catch (Exception ex)
{
@ -362,7 +407,7 @@ namespace Emby.Server.Implementations.Networking
return Dns.GetHostAddressesAsync(hostName);
}
private IEnumerable<IPAddress> GetIPsDefault(bool ignoreVirtualInterface)
private IEnumerable<IPAddress> GetIPsDefault()
{
IEnumerable<NetworkInterface> interfaces;
@ -382,15 +427,7 @@ namespace Emby.Server.Implementations.Networking
{
var ipProperties = network.GetIPProperties();
// Try to exclude virtual adapters
// http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
var addr = ipProperties.GatewayAddresses.FirstOrDefault();
if (addr == null
|| (ignoreVirtualInterface
&& (addr.Address.Equals(IPAddress.Any) || addr.Address.Equals(IPAddress.IPv6Any))))
{
return Enumerable.Empty<IPAddress>();
}
// Exclude any addresses if they appear in the LAN list in [ ]
return ipProperties.UnicastAddresses
.Select(i => i.Address)
@ -423,33 +460,29 @@ namespace Emby.Server.Implementations.Networking
return port;
}
/// <inheritdoc/>
public int GetRandomUnusedUdpPort()
{
var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
using (var udpClient = new UdpClient(localEndPoint))
{
var port = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
return port;
return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
}
}
private List<PhysicalAddress> _macAddresses;
/// <inheritdoc/>
public List<PhysicalAddress> GetMacAddresses()
{
if (_macAddresses == null)
{
_macAddresses = GetMacAddressesInternal().ToList();
}
return _macAddresses;
return _macAddresses ??= GetMacAddressesInternal().ToList();
}
private static IEnumerable<PhysicalAddress> GetMacAddressesInternal()
=> NetworkInterface.GetAllNetworkInterfaces()
.Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(x => x.GetPhysicalAddress())
.Where(x => x != null && x != PhysicalAddress.None);
.Where(x => !x.Equals(PhysicalAddress.None));
/// <inheritdoc/>
public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask)
{
IPAddress network1 = GetNetworkAddress(address1, subnetMask);
@ -476,6 +509,7 @@ namespace Emby.Server.Implementations.Networking
return new IPAddress(broadcastAddress);
}
/// <inheritdoc/>
public IPAddress GetLocalIpSubnetMask(IPAddress address)
{
NetworkInterface[] interfaces;
@ -496,14 +530,11 @@ namespace Emby.Server.Implementations.Networking
foreach (NetworkInterface ni in interfaces)
{
if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
if (ip.Address.Equals(address) && ip.IPv4Mask != null)
{
if (ip.Address.Equals(address) && ip.IPv4Mask != null)
{
return ip.IPv4Mask;
}
return ip.IPv4Mask;
}
}
}

View file

@ -1,7 +1,6 @@
#pragma warning disable CS1591
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
@ -17,11 +16,10 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Updates
@ -31,11 +29,6 @@ namespace Emby.Server.Implementations.Updates
/// </summary>
public class InstallationManager : IInstallationManager
{
/// <summary>
/// The key for a setting that specifies a URL for the plugin repository JSON manifest.
/// </summary>
public const string PluginManifestUrlKey = "InstallationManager:PluginManifestUrl";
/// <summary>
/// The logger.
/// </summary>
@ -53,7 +46,6 @@ namespace Emby.Server.Implementations.Updates
private readonly IApplicationHost _applicationHost;
private readonly IZipClient _zipClient;
private readonly IConfiguration _appConfig;
private readonly object _currentInstallationsLock = new object();
@ -75,8 +67,7 @@ namespace Emby.Server.Implementations.Updates
IJsonSerializer jsonSerializer,
IServerConfigurationManager config,
IFileSystem fileSystem,
IZipClient zipClient,
IConfiguration appConfig)
IZipClient zipClient)
{
if (logger == null)
{
@ -94,7 +85,6 @@ namespace Emby.Server.Implementations.Updates
_config = config;
_fileSystem = fileSystem;
_zipClient = zipClient;
_appConfig = appConfig;
}
/// <inheritdoc />
@ -122,16 +112,14 @@ namespace Emby.Server.Implementations.Updates
public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
/// <inheritdoc />
public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
public async Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default)
{
var manifestUrl = _appConfig.GetValue<string>(PluginManifestUrlKey);
try
{
using (var response = await _httpClient.SendAsync(
new HttpRequestOptions
{
Url = manifestUrl,
Url = manifest,
CancellationToken = cancellationToken,
CacheMode = CacheMode.Unconditional,
CacheLength = TimeSpan.FromMinutes(3)
@ -145,23 +133,33 @@ namespace Emby.Server.Implementations.Updates
}
catch (SerializationException ex)
{
const string LogTemplate =
"Failed to deserialize the plugin manifest retrieved from {PluginManifestUrl}. If you " +
"have specified a custom plugin repository manifest URL with --plugin-manifest-url or " +
PluginManifestUrlKey + ", please ensure that it is correct.";
_logger.LogError(ex, LogTemplate, manifestUrl);
throw;
_logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
return Array.Empty<PackageInfo>();
}
}
}
catch (UriFormatException ex)
{
const string LogTemplate =
"The URL configured for the plugin repository manifest URL is not valid: {PluginManifestUrl}. " +
"Please check the URL configured by --plugin-manifest-url or " + PluginManifestUrlKey;
_logger.LogError(ex, LogTemplate, manifestUrl);
throw;
_logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
return Array.Empty<PackageInfo>();
}
catch (HttpException ex)
{
_logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
return Array.Empty<PackageInfo>();
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
{
var result = new List<PackageInfo>();
foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
{
result.AddRange(await GetPackages(repository.Url, cancellationToken).ConfigureAwait(true));
}
return result;
}
/// <inheritdoc />
@ -402,6 +400,12 @@ namespace Emby.Server.Implementations.Updates
/// <param name="plugin">The plugin.</param>
public void UninstallPlugin(IPlugin plugin)
{
if (!plugin.CanUninstall)
{
_logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
return;
}
plugin.OnUninstalling();
// Remove it the quick way for now

View file

@ -39,21 +39,18 @@ namespace Jellyfin.Api.Auth
/// <inheritdoc />
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authenticatedAttribute = new AuthenticatedAttribute();
try
{
var user = _authService.Authenticate(Request, authenticatedAttribute);
if (user == null)
var authorizationInfo = _authService.Authenticate(Request);
if (authorizationInfo == null)
{
return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
}
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(
ClaimTypes.Role,
value: user.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User)
new Claim(ClaimTypes.Name, authorizationInfo.User.Username),
new Claim(ClaimTypes.Role, authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User)
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);

View file

@ -16,7 +16,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.4.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.0" />
</ItemGroup>
<ItemGroup>

View file

@ -43,8 +43,8 @@
<PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.5" />
<PackageReference Include="prometheus-net" Version="3.5.0" />
<PackageReference Include="prometheus-net.AspNetCore" Version="3.5.0" />
<PackageReference Include="prometheus-net" Version="3.6.0" />
<PackageReference Include="prometheus-net.AspNetCore" Version="3.6.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />

View file

@ -20,6 +20,7 @@ namespace Jellyfin.Server.Migrations
typeof(Routines.CreateUserLoggingConfigFile),
typeof(Routines.MigrateActivityLogDb),
typeof(Routines.RemoveDuplicateExtras),
typeof(Routines.AddDefaultPluginRepository),
typeof(Routines.MigrateUserDb)
};

View file

@ -0,0 +1,42 @@
using System;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Updates;
namespace Jellyfin.Server.Migrations.Routines
{
/// <summary>
/// Migration to initialize system configuration with the default plugin repository.
/// </summary>
public class AddDefaultPluginRepository : IMigrationRoutine
{
private readonly IServerConfigurationManager _serverConfigurationManager;
private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo
{
Name = "Jellyfin Stable",
Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json"
};
/// <summary>
/// Initializes a new instance of the <see cref="AddDefaultPluginRepository"/> class.
/// </summary>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
public AddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
{
_serverConfigurationManager = serverConfigurationManager;
}
/// <inheritdoc/>
public Guid Id => Guid.Parse("EB58EBEE-9514-4B9B-8225-12E1A40020DF");
/// <inheritdoc/>
public string Name => "AddDefaultPluginRepository";
/// <inheritdoc/>
public void Perform()
{
_serverConfigurationManager.Configuration.PluginRepositories.Add(_defaultRepositoryInfo);
_serverConfigurationManager.SaveConfiguration();
}
}
}

View file

@ -79,10 +79,6 @@ namespace Jellyfin.Server
[Option("restartargs", Required = false, HelpText = "Arguments for restart script.")]
public string? RestartArgs { get; set; }
/// <inheritdoc />
[Option("plugin-manifest-url", Required = false, HelpText = "A custom URL for the plugin repository JSON manifest")]
public string? PluginManifestUrl { get; set; }
/// <inheritdoc />
[Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")]
public Uri? PublishedServerUrl { get; set; }
@ -95,11 +91,6 @@ namespace Jellyfin.Server
{
var config = new Dictionary<string, string>();
if (PluginManifestUrl != null)
{
config.Add(InstallationManager.PluginManifestUrlKey, PluginManifestUrl);
}
if (NoWebClient)
{
config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString);

View file

@ -13,6 +13,18 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api
{
[Route("/Repositories", "GET", Summary = "Gets all package repositories")]
[Authenticated]
public class GetRepositories : IReturnVoid
{
}
[Route("/Repositories", "POST", Summary = "Sets the enabled and existing package repositories")]
[Authenticated]
public class SetRepositories : List<RepositoryInfo>, IReturnVoid
{
}
/// <summary>
/// Class GetPackage.
/// </summary>
@ -94,6 +106,7 @@ namespace MediaBrowser.Api
public class PackageService : BaseApiService
{
private readonly IInstallationManager _installationManager;
private readonly IServerConfigurationManager _serverConfigurationManager;
public PackageService(
ILogger<PackageService> logger,
@ -103,6 +116,19 @@ namespace MediaBrowser.Api
: base(logger, serverConfigurationManager, httpResultFactory)
{
_installationManager = installationManager;
_serverConfigurationManager = serverConfigurationManager;
}
public object Get(GetRepositories request)
{
var result = _serverConfigurationManager.Configuration.PluginRepositories;
return ToOptimizedResult(result);
}
public void Post(SetRepositories request)
{
_serverConfigurationManager.Configuration.PluginRepositories = request;
_serverConfigurationManager.SaveConfiguration();
}
/// <summary>

View file

@ -11,14 +11,21 @@ namespace MediaBrowser.Common.Net
{
event EventHandler NetworkChanged;
/// <summary>
/// Gets or sets a function to return the list of user defined LAN addresses.
/// </summary>
Func<string[]> LocalSubnetsFn { get; set; }
/// <summary>
/// Gets a random port number that is currently available.
/// Gets a random port TCP number that is currently available.
/// </summary>
/// <returns>System.Int32.</returns>
int GetRandomUnusedTcpPort();
/// <summary>
/// Gets a random port UDP number that is currently available.
/// </summary>
/// <returns>System.Int32.</returns>
int GetRandomUnusedUdpPort();
/// <summary>
@ -34,6 +41,13 @@ namespace MediaBrowser.Common.Net
/// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInPrivateAddressSpace(string endpoint);
/// <summary>
/// Determines whether [is in private address space 10.x.x.x] [the specified endpoint] and exists in the subnets returned by GetSubnets().
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <returns><c>true</c> if [is in private address space 10.x.x.x] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint);
/// <summary>
/// Determines whether [is in local network] [the specified endpoint].
/// </summary>
@ -41,12 +55,43 @@ namespace MediaBrowser.Common.Net
/// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInLocalNetwork(string endpoint);
IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface);
/// <summary>
/// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses.
/// </summary>
/// <returns>The list of ipaddresses.</returns>
IPAddress[] GetLocalIpAddresses();
/// <summary>
/// Checks if the given address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
/// </summary>
/// <param name="addressString">The address to check.</param>
/// <param name="subnets">If true, check against addresses in the LAN settings surrounded by brackets ([]).</param>
/// <returns><c>true</c>if the address is in at least one of the given subnets, <c>false</c> otherwise.</returns>
bool IsAddressInSubnets(string addressString, string[] subnets);
/// <summary>
/// Returns true if address is in the LAN list in the config file.
/// </summary>
/// <param name="address">The address to check.</param>
/// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
/// <param name="excludeRFC">If true, returns false if address is in the 127.x.x.x or 169.128.x.x range.</param>
/// <returns><c>false</c>if the address isn't in the LAN list, <c>true</c> if the address has been defined as a LAN address.</returns>
bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC);
/// <summary>
/// Checks if address is in the LAN list in the config file.
/// </summary>
/// <param name="address1">Source address to check.</param>
/// <param name="address2">Destination address to check against.</param>
/// <param name="subnetMask">Destination subnet to check against.</param>
/// <returns><c>true/false</c>depending on whether address1 is in the same subnet as IPAddress2 with subnetMask.</returns>
bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask);
/// <summary>
/// Returns the subnet mask of an interface with the given address.
/// </summary>
/// <param name="address">The address to check.</param>
/// <returns>Returns the subnet mask of an interface with the given address, or null if an interface match cannot be found.</returns>
IPAddress GetLocalIpSubnetMask(IPAddress address);
}
}

View file

@ -2,6 +2,7 @@
using System;
using System.IO;
using System.Reflection;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
@ -49,6 +50,12 @@ namespace MediaBrowser.Common.Plugins
/// <value>The data folder path.</value>
public string DataFolderPath { get; private set; }
/// <summary>
/// Gets a value indicating whether the plugin can be uninstalled.
/// </summary>
public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath)
.Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture);
/// <summary>
/// Gets the plugin info.
/// </summary>
@ -60,7 +67,8 @@ namespace MediaBrowser.Common.Plugins
Name = Name,
Version = Version.ToString(),
Description = Description,
Id = Id.ToString()
Id = Id.ToString(),
CanUninstall = CanUninstall
};
return info;

View file

@ -40,6 +40,11 @@ namespace MediaBrowser.Common.Plugins
/// <value>The assembly file path.</value>
string AssemblyFilePath { get; }
/// <summary>
/// Gets a value indicating whether the plugin can be uninstalled.
/// </summary>
bool CanUninstall { get; }
/// <summary>
/// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed.
/// </summary>

View file

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Common.Updates
@ -40,6 +39,14 @@ namespace MediaBrowser.Common.Updates
/// </summary>
IEnumerable<InstallationInfo> CompletedInstallations { get; }
/// <summary>
/// Parses a plugin manifest at the supplied URL.
/// </summary>
/// <param name="manifest">The URL to query.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IReadOnlyList{PackageInfo}}.</returns>
Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default);
/// <summary>
/// Gets all available packages.
/// </summary>

View file

@ -560,8 +560,6 @@ namespace MediaBrowser.Controller.Entities
/// <summary>
/// The logger.
/// </summary>
public static ILoggerFactory LoggerFactory { get; set; }
public static ILogger<BaseItem> Logger { get; set; }
public static ILibraryManager LibraryManager { get; set; }

View file

@ -68,7 +68,7 @@ namespace MediaBrowser.Controller.Entities
parent = LibraryManager.GetItemById(ParentId) as Folder ?? parent;
}
return new UserViewBuilder(UserViewManager, LibraryManager, LoggerFactory.CreateLogger<UserViewBuilder>(), UserDataManager, TVSeriesManager, ConfigurationManager)
return new UserViewBuilder(UserViewManager, LibraryManager, Logger, UserDataManager, TVSeriesManager, ConfigurationManager)
.GetUserItems(parent, this, CollectionType, query);
}

View file

@ -7,6 +7,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.Extensions.Logging;
@ -22,7 +23,7 @@ namespace MediaBrowser.Controller.Entities
{
private readonly IUserViewManager _userViewManager;
private readonly ILibraryManager _libraryManager;
private readonly ILogger<UserViewBuilder> _logger;
private readonly ILogger<BaseItem> _logger;
private readonly IUserDataManager _userDataManager;
private readonly ITVSeriesManager _tvSeriesManager;
private readonly IServerConfigurationManager _config;
@ -30,7 +31,7 @@ namespace MediaBrowser.Controller.Entities
public UserViewBuilder(
IUserViewManager userViewManager,
ILibraryManager libraryManager,
ILogger<UserViewBuilder> logger,
ILogger<BaseItem> logger,
IUserDataManager userDataManager,
ITVSeriesManager tvSeriesManager,
IServerConfigurationManager config)

View file

@ -11,5 +11,12 @@ namespace MediaBrowser.Controller.Net
void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues);
User? Authenticate(HttpRequest request, IAuthenticationAttributes authAttribtues);
/// <summary>
/// Authenticate request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Authorization information. Null if unauthenticated.</returns>
AuthorizationInfo Authenticate(HttpRequest request);
}
}

View file

@ -1,7 +1,11 @@
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net
{
/// <summary>
/// IAuthorization context.
/// </summary>
public interface IAuthorizationContext
{
/// <summary>
@ -17,5 +21,12 @@ namespace MediaBrowser.Controller.Net
/// <param name="requestContext">The request context.</param>
/// <returns>AuthorizationInfo.</returns>
AuthorizationInfo GetAuthorizationInfo(IRequest requestContext);
/// <summary>
/// Gets the authorization information.
/// </summary>
/// <param name="requestContext">The request context.</param>
/// <returns>AuthorizationInfo.</returns>
AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext);
}
}

View file

@ -12,7 +12,15 @@ namespace MediaBrowser.Model.Configuration
public class BaseApplicationConfiguration
{
/// <summary>
/// The number of days we should retain log files.
/// Initializes a new instance of the <see cref="BaseApplicationConfiguration" /> class.
/// </summary>
public BaseApplicationConfiguration()
{
LogFileRetentionDays = 3;
}
/// <summary>
/// Gets or sets the number of days we should retain log files.
/// </summary>
/// <value>The log file retention days.</value>
public int LogFileRetentionDays { get; set; }
@ -30,29 +38,21 @@ namespace MediaBrowser.Model.Configuration
public string CachePath { get; set; }
/// <summary>
/// Last known version that was ran using the configuration.
/// Gets or sets the last known version that was ran using the configuration.
/// </summary>
/// <value>The version from previous run.</value>
[XmlIgnore]
public Version PreviousVersion { get; set; }
/// <summary>
/// Stringified PreviousVersion to be stored/loaded,
/// because System.Version itself isn't xml-serializable
/// Gets or sets the stringified PreviousVersion to be stored/loaded,
/// because System.Version itself isn't xml-serializable.
/// </summary>
/// <value>String value of PreviousVersion</value>
/// <value>String value of PreviousVersion.</value>
public string PreviousVersionStr
{
get => PreviousVersion?.ToString();
set => PreviousVersion = Version.Parse(value);
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationConfiguration" /> class.
/// </summary>
public BaseApplicationConfiguration()
{
LogFileRetentionDays = 3;
}
}
}

View file

@ -2,7 +2,9 @@
#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Model.Configuration
{
@ -229,6 +231,8 @@ namespace MediaBrowser.Model.Configuration
public string[] CodecsUsed { get; set; }
public List<RepositoryInfo> PluginRepositories { get; set; }
public bool IgnoreVirtualInterfaces { get; set; }
public bool EnableExternalContentInSuggestions { get; set; }

View file

@ -35,6 +35,12 @@ namespace MediaBrowser.Model.Plugins
/// </summary>
/// <value>The unique id.</value>
public string Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the plugin can be uninstalled.
/// </summary>
public bool CanUninstall { get; set; }
/// <summary>
/// Gets or sets the image URL.
/// </summary>

View file

@ -0,0 +1,20 @@
namespace MediaBrowser.Model.Updates
{
/// <summary>
/// Class RepositoryInfo.
/// </summary>
public class RepositoryInfo
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string? Name { get; set; }
/// <summary>
/// Gets or sets the URL.
/// </summary>
/// <value>The URL.</value>
public string? Url { get; set; }
}
}

View file

@ -475,7 +475,8 @@ namespace MediaBrowser.Providers.Manager
catch (HttpException ex)
{
// Sometimes providers send back bad url's. Just move to the next image
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{
continue;
}
@ -589,7 +590,8 @@ namespace MediaBrowser.Providers.Manager
catch (HttpException ex)
{
// Sometimes providers send back bad urls. Just move onto the next image
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{
continue;
}

View file

@ -8,7 +8,6 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
@ -43,8 +42,7 @@ namespace Rssdp.Infrastructure
private HttpResponseParser _ResponseParser;
private readonly ILogger _logger;
private ISocketFactory _SocketFactory;
private readonly INetworkManager _networkManager;
private readonly IServerConfigurationManager _config;
private readonly INetworkManager _networkManager;
private int _LocalPort;
private int _MulticastTtl;
@ -66,11 +64,11 @@ namespace Rssdp.Infrastructure
/// Minimum constructor.
/// </summary>
/// <exception cref="ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
public SsdpCommunicationsServer(IServerConfigurationManager config, ISocketFactory socketFactory,
public SsdpCommunicationsServer(ISocketFactory socketFactory,
INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
: this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger, enableMultiSocketBinding)
{
_config = config;
}
/// <summary>
@ -355,13 +353,13 @@ namespace Rssdp.Infrastructure
if (_enableMultiSocketBinding)
{
foreach (var address in _networkManager.GetLocalIpAddresses(_config.Configuration.IgnoreVirtualInterfaces))
foreach (var address in _networkManager.GetLocalIpAddresses())
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// Not support IPv6 right now
continue;
}
}
try
{

View file

@ -353,7 +353,7 @@ namespace Rssdp.Infrastructure
{
return;
}
var location = GetFirstHeaderUriValue("Location", message);
if (location != null)
{

View file

@ -0,0 +1,15 @@
ARG DOTNET_VERSION=3.1
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
WORKDIR ${SOURCE_DIR}
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
# because of changes in docker and systemd we need to not build in parallel at the moment
# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"

View file

@ -0,0 +1,15 @@
ARG DOTNET_VERSION=3.1
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
WORKDIR ${SOURCE_DIR}
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
# because of changes in docker and systemd we need to not build in parallel at the moment
# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"

View file

@ -0,0 +1,15 @@
ARG DOTNET_VERSION=3.1
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
WORKDIR ${SOURCE_DIR}
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
# because of changes in docker and systemd we need to not build in parallel at the moment
# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting
RUN dotnet publish Jellyfin.Server --disable-parallel --configuration Release --output="${ARTIFACT_DIR}" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"

View file

@ -8,6 +8,22 @@ set -o xtrace
# Move to source directory
pushd ${SOURCE_DIR}
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd fedora
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
sed -i "s/Version:.*/Version: ${BUILD_ID}/" jellyfin.spec
sed -i "/%changelog/q" jellyfin.spec
cat <<EOF >>jellyfin.spec
* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
- Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
EOF
popd
fi
# Build RPM
make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
rpmbuild --rebuild -bb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
dpkg-buildpackage -us -uc --pre-clean --post-clean

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean

View file

@ -8,6 +8,22 @@ set -o xtrace
# Move to source directory
pushd ${SOURCE_DIR}
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd fedora
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
sed -i "s/Version:.*/Version: ${BUILD_ID}/" jellyfin.spec
sed -i "/%changelog/q" jellyfin.spec
cat <<EOF >>jellyfin.spec
* $( LANG=C date '+%a %b %d %Y' ) Jellyfin Packaging Team <packaging@jellyfin.org>
- Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
EOF
popd
fi
# Build RPM
make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
rpmbuild -rb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm

View file

@ -9,7 +9,11 @@ set -o xtrace
pushd ${SOURCE_DIR}
# Get version
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
version="${BUILD_ID}"
else
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
fi
# Build archives
dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-x64 --output dist/jellyfin-server_${version}/ "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none;UseAppHost=true"

View file

@ -9,7 +9,11 @@ set -o xtrace
pushd ${SOURCE_DIR}
# Get version
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
version="${BUILD_ID}"
else
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
fi
# Build archives
dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime osx-x64 --output dist/jellyfin-server_${version}/ "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none;UseAppHost=true"

View file

@ -9,7 +9,11 @@ set -o xtrace
pushd ${SOURCE_DIR}
# Get version
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
version="${BUILD_ID}"
else
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
fi
# Build archives
dotnet publish Jellyfin.Server --configuration Release --output dist/jellyfin-server_${version}/ "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none;UseAppHost=true"

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
dpkg-buildpackage -us -uc --pre-clean --post-clean

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean

View file

@ -14,6 +14,21 @@ if [[ ${IS_DOCKER} == YES ]]; then
sed -i '/dotnet-sdk-3.1,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
pushd debian
PR_ID=$( git log --grep 'Merge pull request' --oneline --single-worktree --first-parent | head -1 | grep --color=none -Eo '#[0-9]+' | tr -d '#' )
cat <<EOF >changelog
jellyfin-server (${BUILD_ID}-unstable) unstable; urgency=medium
* Jellyfin Server unstable build ${BUILD_ID} for merged PR #${PR_ID}
-- Jellyfin Packaging Team <packaging@jellyfin.org> $( date --rfc-2822 )
EOF
popd
fi
# Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean

View file

@ -15,7 +15,11 @@ FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win64/static/${FFMPEG_VERSION}.zip
pushd ${SOURCE_DIR}
# Get version
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
if [[ ${IS_UNSTABLE} == 'yes' ]]; then
version="${BUILD_ID}"
else
version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )"
fi
output_dir="dist/jellyfin-server_${version}"

View file

@ -1,7 +1,6 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using AutoFixture;
using AutoFixture.AutoMoq;
@ -9,7 +8,6 @@ using Jellyfin.Api.Auth;
using Jellyfin.Api.Constants;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
@ -26,12 +24,6 @@ namespace Jellyfin.Api.Tests.Auth
private readonly IFixture _fixture;
private readonly Mock<IAuthService> _jellyfinAuthServiceMock;
private readonly Mock<IOptionsMonitor<AuthenticationSchemeOptions>> _optionsMonitorMock;
private readonly Mock<ISystemClock> _clockMock;
private readonly Mock<IServiceProvider> _serviceProviderMock;
private readonly Mock<IAuthenticationService> _authenticationServiceMock;
private readonly UrlEncoder _urlEncoder;
private readonly HttpContext _context;
private readonly CustomAuthenticationHandler _sut;
private readonly AuthenticationScheme _scheme;
@ -47,26 +39,23 @@ namespace Jellyfin.Api.Tests.Auth
AllowFixtureCircularDependencies();
_jellyfinAuthServiceMock = _fixture.Freeze<Mock<IAuthService>>();
_optionsMonitorMock = _fixture.Freeze<Mock<IOptionsMonitor<AuthenticationSchemeOptions>>>();
_clockMock = _fixture.Freeze<Mock<ISystemClock>>();
_serviceProviderMock = _fixture.Freeze<Mock<IServiceProvider>>();
_authenticationServiceMock = _fixture.Freeze<Mock<IAuthenticationService>>();
var optionsMonitorMock = _fixture.Freeze<Mock<IOptionsMonitor<AuthenticationSchemeOptions>>>();
var serviceProviderMock = _fixture.Freeze<Mock<IServiceProvider>>();
var authenticationServiceMock = _fixture.Freeze<Mock<IAuthenticationService>>();
_fixture.Register<ILoggerFactory>(() => new NullLoggerFactory());
_urlEncoder = UrlEncoder.Default;
serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService)))
.Returns(authenticationServiceMock.Object);
_serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService)))
.Returns(_authenticationServiceMock.Object);
_optionsMonitorMock.Setup(o => o.Get(It.IsAny<string>()))
optionsMonitorMock.Setup(o => o.Get(It.IsAny<string>()))
.Returns(new AuthenticationSchemeOptions
{
ForwardAuthenticate = null
});
_context = new DefaultHttpContext
HttpContext context = new DefaultHttpContext
{
RequestServices = _serviceProviderMock.Object
RequestServices = serviceProviderMock.Object
};
_scheme = new AuthenticationScheme(
@ -75,22 +64,7 @@ namespace Jellyfin.Api.Tests.Auth
typeof(CustomAuthenticationHandler));
_sut = _fixture.Create<CustomAuthenticationHandler>();
_sut.InitializeAsync(_scheme, _context).Wait();
}
[Fact]
public async Task HandleAuthenticateAsyncShouldFailWithNullUser()
{
_jellyfinAuthServiceMock.Setup(
a => a.Authenticate(
It.IsAny<HttpRequest>(),
It.IsAny<AuthenticatedAttribute>()))
.Returns((User?)null);
var authenticateResult = await _sut.AuthenticateAsync();
Assert.False(authenticateResult.Succeeded);
Assert.Equal("Invalid user", authenticateResult.Failure.Message);
_sut.InitializeAsync(_scheme, context).Wait();
}
[Fact]
@ -100,8 +74,7 @@ namespace Jellyfin.Api.Tests.Auth
_jellyfinAuthServiceMock.Setup(
a => a.Authenticate(
It.IsAny<HttpRequest>(),
It.IsAny<AuthenticatedAttribute>()))
It.IsAny<HttpRequest>()))
.Throws(new SecurityException(errorMessage));
var authenticateResult = await _sut.AuthenticateAsync();
@ -123,10 +96,10 @@ namespace Jellyfin.Api.Tests.Auth
[Fact]
public async Task HandleAuthenticateAsyncShouldAssignNameClaim()
{
var user = SetupUser();
var authorizationInfo = SetupUser();
var authenticateResult = await _sut.AuthenticateAsync();
Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, user.Username));
Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username));
}
[Theory]
@ -134,10 +107,10 @@ namespace Jellyfin.Api.Tests.Auth
[InlineData(false)]
public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin)
{
var user = SetupUser(isAdmin);
var authorizationInfo = SetupUser(isAdmin);
var authenticateResult = await _sut.AuthenticateAsync();
var expectedRole = user.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User;
var expectedRole = authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User;
Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole));
}
@ -150,18 +123,18 @@ namespace Jellyfin.Api.Tests.Auth
Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme);
}
private User SetupUser(bool isAdmin = false)
private AuthorizationInfo SetupUser(bool isAdmin = false)
{
var user = _fixture.Create<User>();
user.SetPermission(PermissionKind.IsAdministrator, isAdmin);
var authorizationInfo = _fixture.Create<AuthorizationInfo>();
authorizationInfo.User = _fixture.Create<User>();
authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin);
_jellyfinAuthServiceMock.Setup(
a => a.Authenticate(
It.IsAny<HttpRequest>(),
It.IsAny<AuthenticatedAttribute>()))
.Returns(user);
It.IsAny<HttpRequest>()))
.Returns(authorizationInfo);
return user;
return authorizationInfo;
}
private void AllowFixtureCircularDependencies()

View file

@ -21,7 +21,7 @@
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="coverlet.collector" Version="1.3.0" />
<PackageReference Include="Moq" Version="4.14.1" />
<PackageReference Include="Moq" Version="4.14.3" />
</ItemGroup>
<!-- Code Analyzers -->

View file

@ -16,7 +16,7 @@
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.11.0" />
<PackageReference Include="AutoFixture.AutoMoq" Version="4.11.0" />
<PackageReference Include="Moq" Version="4.14.1" />
<PackageReference Include="Moq" Version="4.14.3" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="coverlet.collector" Version="1.3.0" />