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 NugetPackageName: Jellyfin.Common
AssemblyFileName: MediaBrowser.Common.dll AssemblyFileName: MediaBrowser.Common.dll
LinuxImage: 'ubuntu-latest' LinuxImage: 'ubuntu-latest'
- template: azure-pipelines-package.yml

3
.gitignore vendored
View File

@ -39,7 +39,6 @@ ProgramData*/
CorePlugins*/ CorePlugins*/
ProgramData-Server*/ ProgramData-Server*/
ProgramData-UI*/ ProgramData-UI*/
MediaBrowser.WebDashboard/jellyfin-web/**
################# #################
## Visual Studio ## Visual Studio
@ -276,4 +275,4 @@ BenchmarkDotNet.Artifacts
# Ignore web artifacts from native builds # Ignore web artifacts from native builds
web/ web/
web-src.* 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 "version": "0.2.0",
// Use hover for the description of the existing attributes "configurations": [
// 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)", "name": ".NET Core Launch (console)",
"type": "coreclr", "type": "coreclr",
@ -24,5 +21,8 @@
"request": "attach", "request": "attach",
"processId": "${command:pickProcess}" "processId": "${command:pickProcess}"
} }
,] ],
"env": {
"DOTNET_CLI_TELEMETRY_OPTOUT": "1"
}
} }

7
.vscode/tasks.json vendored
View File

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

View File

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

View File

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

View File

@ -585,7 +585,7 @@ namespace Emby.Server.Implementations.HttpServer
if (!string.IsNullOrWhiteSpace(rangeHeader) && totalContentLength.HasValue) 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 OnComplete = options.OnComplete
}; };
@ -622,8 +622,11 @@ namespace Emby.Server.Implementations.HttpServer
/// <summary> /// <summary>
/// Adds the caching responseHeaders. /// Adds the caching responseHeaders.
/// </summary> /// </summary>
private void AddCachingHeaders(IDictionary<string, string> responseHeaders, TimeSpan? cacheDuration, private void AddCachingHeaders(
bool noCache, DateTime? lastModifiedDate) IDictionary<string, string> responseHeaders,
TimeSpan? cacheDuration,
bool noCache,
DateTime? lastModifiedDate)
{ {
if (noCache) if (noCache)
{ {

View File

@ -1,6 +1,7 @@
#pragma warning disable CS1591 #pragma warning disable CS1591
using System; using System;
using System.Buffers;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
@ -8,52 +9,17 @@ using System.Net;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer namespace Emby.Server.Implementations.HttpServer
{ {
public class RangeRequestWriter : IAsyncStreamWriter, IHttpResult 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; private const int BufferSize = 81920;
/// <summary>
/// The _options.
/// </summary>
private readonly Dictionary<string, string> _options = new Dictionary<string, string>(); private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
/// <summary> private List<KeyValuePair<long, long?>> _requestedRanges;
/// 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;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="RangeRequestWriter" /> class. /// 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="source">The source.</param>
/// <param name="contentType">Type of the content.</param> /// <param name="contentType">Type of the content.</param>
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</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)
public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger)
{ {
if (string.IsNullOrEmpty(contentType)) if (string.IsNullOrEmpty(contentType))
{ {
@ -74,7 +39,6 @@ namespace Emby.Server.Implementations.HttpServer
RangeHeader = rangeHeader; RangeHeader = rangeHeader;
SourceStream = source; SourceStream = source;
IsHeadRequest = isHeadRequest; IsHeadRequest = isHeadRequest;
this._logger = logger;
ContentType = contentType; ContentType = contentType;
Headers[HeaderNames.ContentType] = contentType; Headers[HeaderNames.ContentType] = contentType;
@ -84,6 +48,81 @@ namespace Emby.Server.Implementations.HttpServer
SetRangeValues(contentLength); 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> /// <summary>
/// Sets the range values. /// Sets the range values.
/// </summary> /// </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) public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
{ {
try 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 the requested range is "0-", we can optimize by just doing a stream copy
if (RangeEnd >= TotalContentLength - 1) if (RangeEnd >= TotalContentLength - 1)
{ {
await source.CopyToAsync(responseStream, BufferSize).ConfigureAwait(false); await source.CopyToAsync(responseStream, BufferSize, cancellationToken).ConfigureAwait(false);
} }
else else
{ {
await CopyToInternalAsync(source, responseStream, RangeLength).ConfigureAwait(false); await CopyToInternalAsync(source, responseStream, RangeLength, cancellationToken).ConfigureAwait(false);
} }
} }
} }
finally finally
{ {
if (OnComplete != null) OnComplete?.Invoke();
{
OnComplete();
}
} }
} }
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]; var array = ArrayPool<byte>.Shared.Rent(BufferSize);
int bytesRead; try
while ((bytesRead = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
{ {
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)
{
if (copyLength <= 0) break;
{ }
break;
} }
} }
} finally
{
public string ContentType { get; set; } ArrayPool<byte>.Shared.Return(array);
}
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;
} }
} }
} }

View File

@ -51,6 +51,22 @@ namespace Emby.Server.Implementations.HttpServer.Security
return user; 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) private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
{ {
// This code is executed before the service // This code is executed before the service

View File

@ -8,6 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer.Security namespace Emby.Server.Implementations.HttpServer.Security
@ -38,6 +39,14 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(requestContext); return GetAuthorization(requestContext);
} }
public AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext)
{
var auth = GetAuthorizationDictionary(requestContext);
var (authInfo, _) =
GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query);
return authInfo;
}
/// <summary> /// <summary>
/// Gets the authorization. /// Gets the authorization.
/// </summary> /// </summary>
@ -46,7 +55,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
private AuthorizationInfo GetAuthorization(IRequest httpReq) private AuthorizationInfo GetAuthorization(IRequest httpReq)
{ {
var auth = GetAuthorizationDictionary(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 deviceId = null;
string device = null; string device = null;
string client = null; string client = null;
@ -64,20 +89,20 @@ namespace Emby.Server.Implementations.HttpServer.Security
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.Headers["X-Emby-Token"]; token = headers["X-Emby-Token"];
} }
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.Headers["X-MediaBrowser-Token"]; token = headers["X-MediaBrowser-Token"];
} }
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.QueryString["api_key"]; token = queryString["api_key"];
} }
var info = new AuthorizationInfo var authInfo = new AuthorizationInfo
{ {
Client = client, Client = client,
Device = device, Device = device,
@ -86,6 +111,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
Token = token Token = token
}; };
AuthenticationInfo originalAuthenticationInfo = null;
if (!string.IsNullOrWhiteSpace(token)) if (!string.IsNullOrWhiteSpace(token))
{ {
var result = _authRepo.Get(new AuthenticationInfoQuery var result = _authRepo.Get(new AuthenticationInfoQuery
@ -93,81 +119,77 @@ namespace Emby.Server.Implementations.HttpServer.Security
AccessToken = token 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; var updateToken = false;
// TODO: Remove these checks for IsNullOrWhiteSpace // 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 // 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) if (allowTokenInfoUpdate)
{ {
updateToken = true; 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) if (allowTokenInfoUpdate)
{ {
updateToken = true; 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; 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; updateToken = true;
} }
} }
if (updateToken) if (updateToken)
{ {
_authRepo.Update(tokenInfo); _authRepo.Update(originalAuthenticationInfo);
} }
} }
httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
} }
httpReq.Items["AuthorizationInfo"] = info; return (authInfo, originalAuthenticationInfo);
return info;
} }
/// <summary> /// <summary>
@ -187,6 +209,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(auth); 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> /// <summary>
/// Gets the authorization. /// Gets the authorization.
/// </summary> /// </summary>

View File

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

View File

@ -2897,7 +2897,8 @@ namespace Emby.Server.Implementations.Library
} }
catch (HttpException ex) 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; continue;
} }

View File

@ -1,5 +1,5 @@
{ {
"LabelRunningTimeValue": "Duración: {0}", "LabelRunningTimeValue": "Tiempo en ejecución: {0}",
"ValueSpecialEpisodeName": "Especial - {0}", "ValueSpecialEpisodeName": "Especial - {0}",
"Sync": "Sincronizar", "Sync": "Sincronizar",
"Songs": "Canciones", "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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
@ -13,6 +12,9 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Networking namespace Emby.Server.Implementations.Networking
{ {
/// <summary>
/// Class to take care of network interface management.
/// </summary>
public class NetworkManager : INetworkManager public class NetworkManager : INetworkManager
{ {
private readonly ILogger<NetworkManager> _logger; private readonly ILogger<NetworkManager> _logger;
@ -21,8 +23,14 @@ namespace Emby.Server.Implementations.Networking
private readonly object _localIpAddressSyncLock = new object(); private readonly object _localIpAddressSyncLock = new object();
private readonly object _subnetLookupLock = 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) public NetworkManager(ILogger<NetworkManager> logger)
{ {
_logger = logger; _logger = logger;
@ -31,8 +39,10 @@ namespace Emby.Server.Implementations.Networking
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
} }
/// <inheritdoc/>
public event EventHandler NetworkChanged; public event EventHandler NetworkChanged;
/// <inheritdoc/>
public Func<string[]> LocalSubnetsFn { get; set; } public Func<string[]> LocalSubnetsFn { get; set; }
private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
@ -58,13 +68,14 @@ namespace Emby.Server.Implementations.Networking
NetworkChanged?.Invoke(this, EventArgs.Empty); NetworkChanged?.Invoke(this, EventArgs.Empty);
} }
public IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface = true) /// <inheritdoc/>
public IPAddress[] GetLocalIpAddresses()
{ {
lock (_localIpAddressSyncLock) lock (_localIpAddressSyncLock)
{ {
if (_localIpAddresses == null) if (_localIpAddresses == null)
{ {
var addresses = GetLocalIpAddressesInternal(ignoreVirtualInterface).ToArray(); var addresses = GetLocalIpAddressesInternal().ToArray();
_localIpAddresses = addresses; _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) if (list.Count == 0)
{ {
list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList(); 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) .OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
.ThenBy(i => listClone.IndexOf(i)) // .ThenBy(i => listClone.IndexOf(i))
.Where(FilterIpAddress)
.GroupBy(i => i.ToString()) .GroupBy(i => i.ToString())
.Select(x => x.First()) .Select(x => x.First())
.ToList(); .ToList();
} }
private static bool FilterIpAddress(IPAddress address) /// <inheritdoc/>
{
if (address.IsIPv6LinkLocal
|| address.ToString().StartsWith("169.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
public bool IsInPrivateAddressSpace(string endpoint) public bool IsInPrivateAddressSpace(string endpoint)
{ {
return IsInPrivateAddressSpace(endpoint, true); return IsInPrivateAddressSpace(endpoint, true);
} }
// Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address
private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets) private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
{ {
if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
@ -116,12 +132,12 @@ namespace Emby.Server.Implementations.Networking
return true; return true;
} }
// ipv6 // IPV6
if (endpoint.Split('.').Length > 4) if (endpoint.Split('.').Length > 4)
{ {
// Handle ipv4 mapped to ipv6 // Handle ipv4 mapped to ipv6
var originalEndpoint = endpoint; var originalEndpoint = endpoint;
endpoint = endpoint.Replace("::ffff:", string.Empty); endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase);
if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
{ {
@ -130,23 +146,21 @@ namespace Emby.Server.Implementations.Networking
} }
// Private address space: // Private address space:
// http://en.wikipedia.org/wiki/Private_network
if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase))
{
return Is172AddressPrivate(endpoint);
}
if (endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
{ {
return true; 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)) if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
@ -157,6 +171,7 @@ namespace Emby.Server.Implementations.Networking
return false; return false;
} }
/// <inheritdoc/>
public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint) public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
{ {
if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase)) if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
@ -179,6 +194,7 @@ namespace Emby.Server.Implementations.Networking
return false; return false;
} }
// Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart
private List<string> GetSubnets(string endpointFirstPart) private List<string> GetSubnets(string endpointFirstPart)
{ {
lock (_subnetLookupLock) lock (_subnetLookupLock)
@ -224,46 +240,75 @@ namespace Emby.Server.Implementations.Networking
} }
} }
private static bool Is172AddressPrivate(string endpoint) /// <inheritdoc/>
{
for (var i = 16; i <= 31; i++)
{
if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public bool IsInLocalNetwork(string endpoint) public bool IsInLocalNetwork(string endpoint)
{ {
return IsInLocalNetworkInternal(endpoint, true); return IsInLocalNetworkInternal(endpoint, true);
} }
/// <inheritdoc/>
public bool IsAddressInSubnets(string addressString, string[] subnets) public bool IsAddressInSubnets(string addressString, string[] subnets)
{ {
return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, 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) private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
{ {
foreach (var subnet in subnets) foreach (var subnet in subnets)
{ {
var normalizedSubnet = subnet.Trim(); 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)) if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
{ {
return true; return true;
} }
// Parse CIDR subnets and see if address falls within it.
if (normalizedSubnet.Contains('/', StringComparison.Ordinal)) if (normalizedSubnet.Contains('/', StringComparison.Ordinal))
{ {
var ipNetwork = IPNetwork.Parse(normalizedSubnet); try
if (ipNetwork.Contains(address))
{ {
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(); var localSubnets = localSubnetsFn();
foreach (var subnet in localSubnets) 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)) if (!string.IsNullOrWhiteSpace(subnet))
{ {
return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false); return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
@ -345,7 +390,7 @@ namespace Emby.Server.Implementations.Networking
} }
catch (InvalidOperationException) catch (InvalidOperationException)
{ {
// Can happen with reverse proxy or IIS url rewriting // Can happen with reverse proxy or IIS url rewriting?
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -362,7 +407,7 @@ namespace Emby.Server.Implementations.Networking
return Dns.GetHostAddressesAsync(hostName); return Dns.GetHostAddressesAsync(hostName);
} }
private IEnumerable<IPAddress> GetIPsDefault(bool ignoreVirtualInterface) private IEnumerable<IPAddress> GetIPsDefault()
{ {
IEnumerable<NetworkInterface> interfaces; IEnumerable<NetworkInterface> interfaces;
@ -382,15 +427,7 @@ namespace Emby.Server.Implementations.Networking
{ {
var ipProperties = network.GetIPProperties(); var ipProperties = network.GetIPProperties();
// Try to exclude virtual adapters // Exclude any addresses if they appear in the LAN list in [ ]
// 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>();
}
return ipProperties.UnicastAddresses return ipProperties.UnicastAddresses
.Select(i => i.Address) .Select(i => i.Address)
@ -423,33 +460,29 @@ namespace Emby.Server.Implementations.Networking
return port; return port;
} }
/// <inheritdoc/>
public int GetRandomUnusedUdpPort() public int GetRandomUnusedUdpPort()
{ {
var localEndPoint = new IPEndPoint(IPAddress.Any, 0); var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
using (var udpClient = new UdpClient(localEndPoint)) using (var udpClient = new UdpClient(localEndPoint))
{ {
var port = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
return port;
} }
} }
private List<PhysicalAddress> _macAddresses; /// <inheritdoc/>
public List<PhysicalAddress> GetMacAddresses() public List<PhysicalAddress> GetMacAddresses()
{ {
if (_macAddresses == null) return _macAddresses ??= GetMacAddressesInternal().ToList();
{
_macAddresses = GetMacAddressesInternal().ToList();
}
return _macAddresses;
} }
private static IEnumerable<PhysicalAddress> GetMacAddressesInternal() private static IEnumerable<PhysicalAddress> GetMacAddressesInternal()
=> NetworkInterface.GetAllNetworkInterfaces() => NetworkInterface.GetAllNetworkInterfaces()
.Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(x => x.GetPhysicalAddress()) .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) public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask)
{ {
IPAddress network1 = GetNetworkAddress(address1, subnetMask); IPAddress network1 = GetNetworkAddress(address1, subnetMask);
@ -476,6 +509,7 @@ namespace Emby.Server.Implementations.Networking
return new IPAddress(broadcastAddress); return new IPAddress(broadcastAddress);
} }
/// <inheritdoc/>
public IPAddress GetLocalIpSubnetMask(IPAddress address) public IPAddress GetLocalIpSubnetMask(IPAddress address)
{ {
NetworkInterface[] interfaces; NetworkInterface[] interfaces;
@ -496,14 +530,11 @@ namespace Emby.Server.Implementations.Networking
foreach (NetworkInterface ni in interfaces) 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 #pragma warning disable CS1591
using System; using System;
using System.Collections;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@ -17,11 +16,10 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Updates; using MediaBrowser.Common.Updates;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO; using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates; using MediaBrowser.Model.Updates;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Updates namespace Emby.Server.Implementations.Updates
@ -31,11 +29,6 @@ namespace Emby.Server.Implementations.Updates
/// </summary> /// </summary>
public class InstallationManager : IInstallationManager 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> /// <summary>
/// The logger. /// The logger.
/// </summary> /// </summary>
@ -53,7 +46,6 @@ namespace Emby.Server.Implementations.Updates
private readonly IApplicationHost _applicationHost; private readonly IApplicationHost _applicationHost;
private readonly IZipClient _zipClient; private readonly IZipClient _zipClient;
private readonly IConfiguration _appConfig;
private readonly object _currentInstallationsLock = new object(); private readonly object _currentInstallationsLock = new object();
@ -75,8 +67,7 @@ namespace Emby.Server.Implementations.Updates
IJsonSerializer jsonSerializer, IJsonSerializer jsonSerializer,
IServerConfigurationManager config, IServerConfigurationManager config,
IFileSystem fileSystem, IFileSystem fileSystem,
IZipClient zipClient, IZipClient zipClient)
IConfiguration appConfig)
{ {
if (logger == null) if (logger == null)
{ {
@ -94,7 +85,6 @@ namespace Emby.Server.Implementations.Updates
_config = config; _config = config;
_fileSystem = fileSystem; _fileSystem = fileSystem;
_zipClient = zipClient; _zipClient = zipClient;
_appConfig = appConfig;
} }
/// <inheritdoc /> /// <inheritdoc />
@ -122,16 +112,14 @@ namespace Emby.Server.Implementations.Updates
public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal; public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
/// <inheritdoc /> /// <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 try
{ {
using (var response = await _httpClient.SendAsync( using (var response = await _httpClient.SendAsync(
new HttpRequestOptions new HttpRequestOptions
{ {
Url = manifestUrl, Url = manifest,
CancellationToken = cancellationToken, CancellationToken = cancellationToken,
CacheMode = CacheMode.Unconditional, CacheMode = CacheMode.Unconditional,
CacheLength = TimeSpan.FromMinutes(3) CacheLength = TimeSpan.FromMinutes(3)
@ -145,23 +133,33 @@ namespace Emby.Server.Implementations.Updates
} }
catch (SerializationException ex) catch (SerializationException ex)
{ {
const string LogTemplate = _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
"Failed to deserialize the plugin manifest retrieved from {PluginManifestUrl}. If you " + return Array.Empty<PackageInfo>();
"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;
} }
} }
} }
catch (UriFormatException ex) catch (UriFormatException ex)
{ {
const string LogTemplate = _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
"The URL configured for the plugin repository manifest URL is not valid: {PluginManifestUrl}. " + return Array.Empty<PackageInfo>();
"Please check the URL configured by --plugin-manifest-url or " + PluginManifestUrlKey;
_logger.LogError(ex, LogTemplate, manifestUrl);
throw;
} }
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 /> /// <inheritdoc />
@ -402,6 +400,12 @@ namespace Emby.Server.Implementations.Updates
/// <param name="plugin">The plugin.</param> /// <param name="plugin">The plugin.</param>
public void UninstallPlugin(IPlugin plugin) public void UninstallPlugin(IPlugin plugin)
{ {
if (!plugin.CanUninstall)
{
_logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
return;
}
plugin.OnUninstalling(); plugin.OnUninstalling();
// Remove it the quick way for now // Remove it the quick way for now

View File

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

View File

@ -16,7 +16,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.5" /> <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <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>
<ItemGroup> <ItemGroup>

View File

@ -43,8 +43,8 @@
<PackageReference Include="CommandLineParser" Version="2.8.0" /> <PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.5" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" 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" Version="3.6.0" />
<PackageReference Include="prometheus-net.AspNetCore" Version="3.5.0" /> <PackageReference Include="prometheus-net.AspNetCore" Version="3.6.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" 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.CreateUserLoggingConfigFile),
typeof(Routines.MigrateActivityLogDb), typeof(Routines.MigrateActivityLogDb),
typeof(Routines.RemoveDuplicateExtras), typeof(Routines.RemoveDuplicateExtras),
typeof(Routines.AddDefaultPluginRepository),
typeof(Routines.MigrateUserDb) 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.")] [Option("restartargs", Required = false, HelpText = "Arguments for restart script.")]
public string? RestartArgs { get; set; } 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 /> /// <inheritdoc />
[Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")] [Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")]
public Uri? PublishedServerUrl { get; set; } public Uri? PublishedServerUrl { get; set; }
@ -95,11 +91,6 @@ namespace Jellyfin.Server
{ {
var config = new Dictionary<string, string>(); var config = new Dictionary<string, string>();
if (PluginManifestUrl != null)
{
config.Add(InstallationManager.PluginManifestUrlKey, PluginManifestUrl);
}
if (NoWebClient) if (NoWebClient)
{ {
config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString); config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString);

View File

@ -13,6 +13,18 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api 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> /// <summary>
/// Class GetPackage. /// Class GetPackage.
/// </summary> /// </summary>
@ -94,6 +106,7 @@ namespace MediaBrowser.Api
public class PackageService : BaseApiService public class PackageService : BaseApiService
{ {
private readonly IInstallationManager _installationManager; private readonly IInstallationManager _installationManager;
private readonly IServerConfigurationManager _serverConfigurationManager;
public PackageService( public PackageService(
ILogger<PackageService> logger, ILogger<PackageService> logger,
@ -103,6 +116,19 @@ namespace MediaBrowser.Api
: base(logger, serverConfigurationManager, httpResultFactory) : base(logger, serverConfigurationManager, httpResultFactory)
{ {
_installationManager = installationManager; _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> /// <summary>

View File

@ -11,14 +11,21 @@ namespace MediaBrowser.Common.Net
{ {
event EventHandler NetworkChanged; event EventHandler NetworkChanged;
/// <summary>
/// Gets or sets a function to return the list of user defined LAN addresses.
/// </summary>
Func<string[]> LocalSubnetsFn { get; set; } Func<string[]> LocalSubnetsFn { get; set; }
/// <summary> /// <summary>
/// Gets a random port number that is currently available. /// Gets a random port TCP number that is currently available.
/// </summary> /// </summary>
/// <returns>System.Int32.</returns> /// <returns>System.Int32.</returns>
int GetRandomUnusedTcpPort(); int GetRandomUnusedTcpPort();
/// <summary>
/// Gets a random port UDP number that is currently available.
/// </summary>
/// <returns>System.Int32.</returns>
int GetRandomUnusedUdpPort(); int GetRandomUnusedUdpPort();
/// <summary> /// <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> /// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInPrivateAddressSpace(string endpoint); 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> /// <summary>
/// Determines whether [is in local network] [the specified endpoint]. /// Determines whether [is in local network] [the specified endpoint].
/// </summary> /// </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> /// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInLocalNetwork(string endpoint); 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); 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); 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); IPAddress GetLocalIpSubnetMask(IPAddress address);
} }
} }

View File

@ -2,6 +2,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Reflection;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
@ -49,6 +50,12 @@ namespace MediaBrowser.Common.Plugins
/// <value>The data folder path.</value> /// <value>The data folder path.</value>
public string DataFolderPath { get; private set; } 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> /// <summary>
/// Gets the plugin info. /// Gets the plugin info.
/// </summary> /// </summary>
@ -60,7 +67,8 @@ namespace MediaBrowser.Common.Plugins
Name = Name, Name = Name,
Version = Version.ToString(), Version = Version.ToString(),
Description = Description, Description = Description,
Id = Id.ToString() Id = Id.ToString(),
CanUninstall = CanUninstall
}; };
return info; return info;

View File

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

View File

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Updates; using MediaBrowser.Model.Updates;
namespace MediaBrowser.Common.Updates namespace MediaBrowser.Common.Updates
@ -40,6 +39,14 @@ namespace MediaBrowser.Common.Updates
/// </summary> /// </summary>
IEnumerable<InstallationInfo> CompletedInstallations { get; } 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> /// <summary>
/// Gets all available packages. /// Gets all available packages.
/// </summary> /// </summary>

View File

@ -560,8 +560,6 @@ namespace MediaBrowser.Controller.Entities
/// <summary> /// <summary>
/// The logger. /// The logger.
/// </summary> /// </summary>
public static ILoggerFactory LoggerFactory { get; set; }
public static ILogger<BaseItem> Logger { get; set; } public static ILogger<BaseItem> Logger { get; set; }
public static ILibraryManager LibraryManager { 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; 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); .GetUserItems(parent, this, CollectionType, query);
} }

View File

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

View File

@ -11,5 +11,12 @@ namespace MediaBrowser.Controller.Net
void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues); void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues);
User? Authenticate(HttpRequest 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 MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net namespace MediaBrowser.Controller.Net
{ {
/// <summary>
/// IAuthorization context.
/// </summary>
public interface IAuthorizationContext public interface IAuthorizationContext
{ {
/// <summary> /// <summary>
@ -17,5 +21,12 @@ namespace MediaBrowser.Controller.Net
/// <param name="requestContext">The request context.</param> /// <param name="requestContext">The request context.</param>
/// <returns>AuthorizationInfo.</returns> /// <returns>AuthorizationInfo.</returns>
AuthorizationInfo GetAuthorizationInfo(IRequest requestContext); 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 public class BaseApplicationConfiguration
{ {
/// <summary> /// <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> /// </summary>
/// <value>The log file retention days.</value> /// <value>The log file retention days.</value>
public int LogFileRetentionDays { get; set; } public int LogFileRetentionDays { get; set; }
@ -30,29 +38,21 @@ namespace MediaBrowser.Model.Configuration
public string CachePath { get; set; } public string CachePath { get; set; }
/// <summary> /// <summary>
/// Last known version that was ran using the configuration. /// Gets or sets the last known version that was ran using the configuration.
/// </summary> /// </summary>
/// <value>The version from previous run.</value> /// <value>The version from previous run.</value>
[XmlIgnore] [XmlIgnore]
public Version PreviousVersion { get; set; } public Version PreviousVersion { get; set; }
/// <summary> /// <summary>
/// Stringified PreviousVersion to be stored/loaded, /// Gets or sets the stringified PreviousVersion to be stored/loaded,
/// because System.Version itself isn't xml-serializable /// because System.Version itself isn't xml-serializable.
/// </summary> /// </summary>
/// <value>String value of PreviousVersion</value> /// <value>String value of PreviousVersion.</value>
public string PreviousVersionStr public string PreviousVersionStr
{ {
get => PreviousVersion?.ToString(); get => PreviousVersion?.ToString();
set => PreviousVersion = Version.Parse(value); 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 #pragma warning disable CS1591
using System; using System;
using System.Collections.Generic;
using MediaBrowser.Model.Dto; using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Updates;
namespace MediaBrowser.Model.Configuration namespace MediaBrowser.Model.Configuration
{ {
@ -229,6 +231,8 @@ namespace MediaBrowser.Model.Configuration
public string[] CodecsUsed { get; set; } public string[] CodecsUsed { get; set; }
public List<RepositoryInfo> PluginRepositories { get; set; }
public bool IgnoreVirtualInterfaces { get; set; } public bool IgnoreVirtualInterfaces { get; set; }
public bool EnableExternalContentInSuggestions { get; set; } public bool EnableExternalContentInSuggestions { get; set; }

View File

@ -35,6 +35,12 @@ namespace MediaBrowser.Model.Plugins
/// </summary> /// </summary>
/// <value>The unique id.</value> /// <value>The unique id.</value>
public string Id { get; set; } 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> /// <summary>
/// Gets or sets the image URL. /// Gets or sets the image URL.
/// </summary> /// </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) catch (HttpException ex)
{ {
// Sometimes providers send back bad url's. Just move to the next image // 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; continue;
} }
@ -589,7 +590,8 @@ namespace MediaBrowser.Providers.Manager
catch (HttpException ex) catch (HttpException ex)
{ {
// Sometimes providers send back bad urls. 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) if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{ {
continue; continue;
} }

View File

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

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 # Move to source directory
pushd ${SOURCE_DIR} 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 # Build RPM
make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
rpmbuild --rebuild -bb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
dpkg-buildpackage -us -uc --pre-clean --post-clean 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH} export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH} export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean

View File

@ -8,6 +8,22 @@ set -o xtrace
# Move to source directory # Move to source directory
pushd ${SOURCE_DIR} 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 # Build RPM
make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS make -f fedora/Makefile srpm outdir=/root/rpmbuild/SRPMS
rpmbuild -rb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm rpmbuild -rb /root/rpmbuild/SRPMS/jellyfin-*.src.rpm

View File

@ -9,7 +9,11 @@ set -o xtrace
pushd ${SOURCE_DIR} pushd ${SOURCE_DIR}
# Get version # 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 # 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" 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} pushd ${SOURCE_DIR}
# Get version # 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 # 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" 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} pushd ${SOURCE_DIR}
# Get version # 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 # Build archives
dotnet publish Jellyfin.Server --configuration Release --output dist/jellyfin-server_${version}/ "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none;UseAppHost=true" 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
dpkg-buildpackage -us -uc --pre-clean --post-clean 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH} export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a arm64 --pre-clean --post-clean 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 sed -i '/dotnet-sdk-3.1,/d' debian/control
fi 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 # Build DEB
export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH} export CONFIG_SITE=/etc/dpkg-cross/cross-config.${ARCH}
dpkg-buildpackage -us -uc -a armhf --pre-clean --post-clean 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} pushd ${SOURCE_DIR}
# Get version # 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}" output_dir="dist/jellyfin-server_${version}"

View File

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

View File

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

View File

@ -16,7 +16,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoFixture" Version="4.11.0" /> <PackageReference Include="AutoFixture" Version="4.11.0" />
<PackageReference Include="AutoFixture.AutoMoq" 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" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
<PackageReference Include="coverlet.collector" Version="1.3.0" /> <PackageReference Include="coverlet.collector" Version="1.3.0" />