Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/StreamFeed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ public async Task<UpdateToTargetsResponse> UpdateActivityToTargetsAsync(ForeignI
IEnumerable<string> newTargets = null,
IEnumerable<string> removed = null)
{
adds?.ForEach(FeedIdValidator.ThrowIfFeedIdIsInvalid);
newTargets?.ForEach(FeedIdValidator.ThrowIfFeedIdIsInvalid);
removed?.ForEach(FeedIdValidator.ThrowIfFeedIdIsInvalid);

var payload = new
{
foreign_id = foreignIdTime.ForeignId,
Expand Down
61 changes: 61 additions & 0 deletions src/Utils/FeedIdValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System;

namespace Stream.Utils
{
public static class FeedIdValidator
{
/// <summary>
/// Validates a fully qualified feed identifier. It should look like this: flat:myfeedname
/// We could use a Regex but that has a performance impact
/// so let's just iterate through the string and check for the correct format.
/// </summary>
public static void ThrowIfFeedIdIsInvalid(string feedId)
{
if (string.IsNullOrWhiteSpace(feedId))
{
throw new InvalidFeedIdException(feedId);
}

var foundColon = false;
var colonIndex = 0;
var index = 0;

foreach (var character in feedId)
{
if (character == ':')
{
if (foundColon)
{
throw new InvalidFeedIdException(feedId);
}

if (index == 0 || index == feedId.Length - 1)
{
throw new InvalidFeedIdException(feedId);
}

foundColon = true;
colonIndex = index;
}

index++;
}

if (!foundColon)
{
throw new InvalidFeedIdException(feedId);
}
}
}

/// <summary>
/// Exception thrown when a feed identifier is invalid.
/// The feed identifier should have a single colon. Example: flat:myfeedname
/// </summary>
public class InvalidFeedIdException : Exception
{
public InvalidFeedIdException(string feedId) : base($"Invalid feed id: {feedId}. It should look like this: flat:myfeedname")
{
}
}
}
22 changes: 22 additions & 0 deletions tests/FeedIdValidatorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using NUnit.Framework;
using Stream.Utils;

public class FeedIdValidatorTests
{
[Test]
public void TestFeedIdValidator()
{
var invalidFeedIds = new[] { "nocolon", ":beginning", "ending:", "mul:tip:le:colons" };
var valifFeedIds = new[] { "flat:myfeedname" };

foreach (var feedId in invalidFeedIds)
{
Assert.Throws<InvalidFeedIdException>(() => FeedIdValidator.ThrowIfFeedIdIsInvalid(feedId));
}

foreach (var feedId in valifFeedIds)
{
Assert.DoesNotThrow(() => FeedIdValidator.ThrowIfFeedIdIsInvalid(feedId));
}
}
}