Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable nullable reference types for MediaBrowser.Common #5982

Merged
merged 2 commits into from May 6, 2021
Merged
Changes from all commits
Commits
File filter
Filter file types
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.

Always

Just for now

@@ -77,8 +77,9 @@ public abstract class BaseAuthorizationHandler<T> : AuthorizationHandler<T>
return false;
}

var ip = _httpContextAccessor.HttpContext.GetNormalizedRemoteIp();
var isInLocalNetwork = _networkManager.IsInLocalNetwork(ip);
var isInLocalNetwork = _httpContextAccessor.HttpContext != null
&& _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp());

// User cannot access remotely and user is remote
if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !isInLocalNetwork)
{
@@ -1,3 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Net.Mime;
using System.Text.Json;
@@ -94,6 +95,11 @@ public async Task<ActionResult> UpdateNamedConfiguration([FromRoute, Required] s
{
var configurationType = _configurationManager.GetConfigurationType(key);
var configuration = await JsonSerializer.DeserializeAsync(Request.Body, configurationType, _serializerOptions).ConfigureAwait(false);
if (configuration == null)
{
throw new ArgumentException("Body doesn't contain a valid configuration");
}

_configurationManager.SaveConfiguration(key, configuration);
return NoContent();
}
@@ -1,3 +1,5 @@
#nullable disable

using System;

namespace MediaBrowser.Common.Configuration
@@ -1,3 +1,4 @@
#nullable disable
#pragma warning disable CS1591

using System;
@@ -1,3 +1,5 @@
#nullable disable

namespace MediaBrowser.Common.Configuration
{
/// <summary>
@@ -1,5 +1,4 @@
#pragma warning disable CS1591
#nullable enable

using System;
using System.Collections.Generic;
@@ -17,7 +17,7 @@ public static class EventHelper
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param>
/// <param name="logger">The logger.</param>
public static void QueueEventIfNotNull(EventHandler handler, object sender, EventArgs args, ILogger logger)
public static void QueueEventIfNotNull(EventHandler? handler, object sender, EventArgs args, ILogger logger)
{
if (handler != null)
{
@@ -43,7 +43,7 @@ public static void QueueEventIfNotNull(EventHandler handler, object sender, Even
/// <param name="sender">The sender.</param>
/// <param name="args">The args.</param>
/// <param name="logger">The logger.</param>
public static void QueueEventIfNotNull<T>(EventHandler<T> handler, object sender, T args, ILogger logger)
public static void QueueEventIfNotNull<T>(EventHandler<T>? handler, object sender, T args, ILogger logger)
{
if (handler != null)
{
@@ -1,5 +1,3 @@
#nullable enable

using System;
using System.Security.Cryptography;
using System.Text;
@@ -1,5 +1,3 @@
#nullable enable

using System.Collections.Generic;

namespace MediaBrowser.Common.Extensions
@@ -17,7 +17,7 @@ public static bool IsLocal(this HttpContext context)
{
return (context.Connection.LocalIpAddress == null
&& context.Connection.RemoteIpAddress == null)
|| context.Connection.LocalIpAddress.Equals(context.Connection.RemoteIpAddress);
|| Equals(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress);
}

/// <summary>
@@ -1,5 +1,3 @@
#nullable enable

using System;

namespace MediaBrowser.Common.Extensions
@@ -1,5 +1,3 @@
#nullable enable

using System;
using System.Diagnostics;
using System.Threading;
@@ -1,4 +1,3 @@
#nullable enable
#pragma warning disable CS1591

using System;
@@ -1,5 +1,3 @@
#nullable enable

using System;

namespace MediaBrowser.Common.Extensions
@@ -1,5 +1,3 @@
#nullable enable

using System;
using System.Collections.Generic;

@@ -21,7 +21,7 @@ MIT License
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#nullable enable

#pragma warning disable CS1591
#pragma warning disable CA1034
using System;
@@ -1,5 +1,3 @@
#nullable enable

using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -1,3 +1,5 @@
#nullable disable

using System;
using System.Collections.Generic;
using System.Reflection;
@@ -9,67 +9,16 @@ namespace MediaBrowser.Common.Json.Converters
/// Convert comma delimited string to array of type.
/// </summary>
/// <typeparam name="T">Type to convert to.</typeparam>
public class JsonCommaDelimitedArrayConverter<T> : JsonConverter<T[]>
public sealed class JsonCommaDelimitedArrayConverter<T> : JsonDelimitedArrayConverter<T>
{
private readonly TypeConverter _typeConverter;

/// <summary>
/// Initializes a new instance of the <see cref="JsonCommaDelimitedArrayConverter{T}"/> class.
/// </summary>
public JsonCommaDelimitedArrayConverter()
public JsonCommaDelimitedArrayConverter() : base()
{
_typeConverter = TypeDescriptor.GetConverter(typeof(T));
}

/// <inheritdoc />
public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
var stringEntries = reader.GetString().Split(',', StringSplitOptions.RemoveEmptyEntries);
if (stringEntries.Length == 0)
{
return Array.Empty<T>();
}

var parsedValues = new object[stringEntries.Length];
var convertedCount = 0;
for (var i = 0; i < stringEntries.Length; i++)
{
try
{
parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim());
convertedCount++;
}
catch (FormatException)
{
// TODO log when upgraded to .Net6
// https://github.com/dotnet/runtime/issues/42975
// _logger.LogDebug(e, "Error converting value.");
}
}

var typedValues = new T[convertedCount];
var typedValueIndex = 0;
for (var i = 0; i < stringEntries.Length; i++)
{
if (parsedValues[i] != null)
{
typedValues.SetValue(parsedValues[i], typedValueIndex);
typedValueIndex++;
}
}

return typedValues;
}

return JsonSerializer.Deserialize<T[]>(ref reader, options);
}

/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
protected override char Delimiter => ',';
}
}
@@ -19,10 +19,10 @@ public override bool CanConvert(Type typeToConvert)
}

/// <inheritdoc />
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0];
return (JsonConverter)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType));
return (JsonConverter?)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType));
}
}
}
@@ -0,0 +1,81 @@
using System;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// Convert delimited string to array of type.
/// </summary>
/// <typeparam name="T">Type to convert to.</typeparam>
public abstract class JsonDelimitedArrayConverter<T> : JsonConverter<T[]?>
{
private readonly TypeConverter _typeConverter;

/// <summary>
/// Initializes a new instance of the <see cref="JsonDelimitedArrayConverter{T}"/> class.
/// </summary>
protected JsonDelimitedArrayConverter()
{
_typeConverter = TypeDescriptor.GetConverter(typeof(T));
}

/// <summary>
/// Gets the array delimiter.
/// </summary>
protected virtual char Delimiter { get; }

/// <inheritdoc />
public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
// GetString can't return null here because we already handled it above
var stringEntries = reader.GetString()?.Split(Delimiter, StringSplitOptions.RemoveEmptyEntries);
if (stringEntries == null || stringEntries.Length == 0)
{
return Array.Empty<T>();
}

var parsedValues = new object[stringEntries.Length];
var convertedCount = 0;
for (var i = 0; i < stringEntries.Length; i++)
{
try
{
parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim());
convertedCount++;
}
catch (FormatException)
{
// TODO log when upgraded to .Net6
// https://github.com/dotnet/runtime/issues/42975
// _logger.LogDebug(e, "Error converting value.");
}
}

var typedValues = new T[convertedCount];
var typedValueIndex = 0;
for (var i = 0; i < stringEntries.Length; i++)
{
if (parsedValues[i] != null)
{
typedValues.SetValue(parsedValues[i], typedValueIndex);
typedValueIndex++;
}
}

return typedValues;
}

return JsonSerializer.Deserialize<T[]>(ref reader, options);
}

/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T[]? value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
}
@@ -18,10 +18,10 @@ public override bool CanConvert(Type typeToConvert)
}

/// <inheritdoc />
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var structType = typeToConvert.GenericTypeArguments[0];
return (JsonConverter)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType));
return (JsonConverter?)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType));
}
}
}
}
@@ -7,27 +7,33 @@ namespace MediaBrowser.Common.Json.Converters
/// <summary>
/// Converts a string <c>N/A</c> to <c>string.Empty</c>.
/// </summary>
public class JsonOmdbNotAvailableStringConverter : JsonConverter<string>
public class JsonOmdbNotAvailableStringConverter : JsonConverter<string?>
{
/// <inheritdoc />
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}

if (reader.TokenType == JsonTokenType.String)
{
var str = reader.GetString();
if (str != null && str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
// GetString can't return null here because we already handled it above
var str = reader.GetString()!;
if (str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
{
return null;
}

return str;
}

return JsonSerializer.Deserialize<string>(ref reader, options);
return JsonSerializer.Deserialize<string?>(ref reader, options);
}

/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
ProTip! Use n and p to navigate between commits in a pull request.