Skip to content

Commit

Permalink
ref - Consolidated type-agnostic tools
Browse files Browse the repository at this point in the history
---

Type: ref
Breaking: False
Doc Required: False
Backport Required: False
Part: 1/1
  • Loading branch information
AptiviCEO committed Sep 2, 2024
1 parent d259830 commit 4ac004f
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 133 deletions.
5 changes: 3 additions & 2 deletions VisualCard.Calendar/Parsers/VCalendarParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
using VisualCard.Calendar.Parts.Implementations;
using VisualCard.Calendar.Exceptions;
using VisualCard.Parts.Enums;
using VisualCard.Parsers;

namespace VisualCard.Calendar.Parsers
{
Expand Down Expand Up @@ -159,7 +160,7 @@ public Parts.Calendar Parse()
}

// Check the type for allowed types
string[] elementTypes = VCalendarParserTools.GetTypes(splitArgs, defaultType, specifierRequired);
string[] elementTypes = VcardParserTools.GetTypes(splitArgs, defaultType, specifierRequired);
foreach (string elementType in elementTypes)
{
string elementTypeUpper = elementType.ToUpper();
Expand All @@ -168,7 +169,7 @@ public Parts.Calendar Parse()
}

// Handle the part type
string values = VCalendarParserTools.GetValuesString(splitArgs, defaultValue, VCalendarConstants._valueArgumentSpecifier);
string values = VcardParserTools.GetValuesString(splitArgs, defaultValue, VCalendarConstants._valueArgumentSpecifier);
switch (type)
{
case PartType.Strings:
Expand Down
129 changes: 0 additions & 129 deletions VisualCard.Calendar/Parsers/VCalendarParserTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,56 +33,6 @@ namespace VisualCard.Calendar.Parsers
internal class VCalendarParserTools
{
#pragma warning disable IDE0060
internal static string GetTypesString(string[] args, string @default, bool isSpecifierRequired = true)
{
// We're given an array of split arguments of an element delimited by the colon, such as: "...TYPE=home..."
// Filter list of arguments with the arguments that start with the type argument specifier, or, if specifier is not required,
// that doesn't have an equals sign
var ArgType = args.Where((arg) => arg.StartsWith(VCalendarConstants._typeArgumentSpecifier) || !arg.Contains("=")).ToArray();

// Trying to specify type without TYPE= is illegal according to RFC2426 in vCard 3.0 and 4.0
if (ArgType.Count() > 0 && !ArgType[0].StartsWith(VCalendarConstants._typeArgumentSpecifier) && isSpecifierRequired)
throw new InvalidDataException("Type must be prepended with TYPE=");

// Get the type from the split argument
string Type = "";
if (isSpecifierRequired)
// Attempt to get the value from the key strictly
Type =
ArgType.Count() > 0 ?
string.Join(VCalendarConstants._valueDelimiter.ToString(), ArgType.Select((arg) => arg.Substring(VCalendarConstants._typeArgumentSpecifier.Length))) :
@default;
else
// Attempt to get the value from the key
Type =
ArgType.Count() > 0 ?
string.Join(VCalendarConstants._valueDelimiter.ToString(), ArgType.Select((arg) => arg.StartsWith(VCalendarConstants._typeArgumentSpecifier) ? arg.Substring(VCalendarConstants._typeArgumentSpecifier.Length) : arg)) :
@default;

// Return the type
return Type;
}

internal static string[] GetTypes(string[] args, string @default, bool isSpecifierRequired = true) =>
GetTypesString(args, @default, isSpecifierRequired).Split([VCalendarConstants._valueDelimiter], StringSplitOptions.RemoveEmptyEntries);

internal static string GetValuesString(string[] args, string @default, string argSpecifier)
{
// We're given an array of split arguments of an element delimited by the colon, such as: "...TYPE=home..."
// Filter list of arguments with the arguments that start with the specified specifier (key)
var argFromSpecifier = args.Where((arg) => arg.StartsWith(argSpecifier));

// Attempt to get the value from the key
string argString =
argFromSpecifier.Count() > 0 ?
string.Join(VCalendarConstants._valueDelimiter.ToString(), argFromSpecifier.Select((arg) => arg.Substring(argSpecifier.Length))) :
@default;
return argString;
}

internal static string[] GetValues(string[] args, string @default, string argSpecifier) =>
GetValuesString(args, @default, argSpecifier).Split([VCalendarConstants._valueDelimiter], StringSplitOptions.RemoveEmptyEntries);

internal static bool StringSupported(CalendarStringsEnum stringsEnum, Version calendarVersion) =>
stringsEnum switch
{
Expand Down Expand Up @@ -166,85 +116,6 @@ internal static (PartType type, object enumeration, Type enumType, Func<string,
_ =>
throw new InvalidOperationException($"Unknown prefix {prefix}"),
};

internal static string MakeStringBlock(string target, int firstLength)
{
const int maxChars = 74;
int maxCharsFirst = maxChars - firstLength + 1;

// Construct the block
StringBuilder block = new();
int selectedMax = maxCharsFirst;
int processed = 0;
for (int currCharNum = 0; currCharNum < target.Length; currCharNum++)
{
if (target[currCharNum] != '\n' && target[currCharNum] != '\r')
{
block.Append(target[currCharNum]);
processed++;
}
if (processed >= selectedMax || target[currCharNum] == '\n')
{
// Append a new line because we reached the maximum limit
selectedMax = maxChars;
processed = 0;
block.Append("\n ");
}
}
return block.ToString();
}

internal static IEnumerable<int> GetDigits(int num)
{
int individualFactor = 0;
int tennerFactor = Convert.ToInt32(Math.Pow(10, num.ToString().Length));
while (tennerFactor > 1)
{
num -= tennerFactor * individualFactor;
tennerFactor /= 10;
individualFactor = num / tennerFactor;
yield return individualFactor;
}
}

internal static bool IsEncodingBlob(string[] args, string keyEncoded)
{
string encoding = GetValuesString(args, "b", VCalendarConstants._encodingArgumentSpecifier);
bool isValidUri = Uri.TryCreate(keyEncoded, UriKind.Absolute, out Uri uri);
if (isValidUri)
{
if (uri.Scheme == "data")
return true;
return false;
}
return
encoding.Equals("b", StringComparison.OrdinalIgnoreCase) ||
encoding.Equals("BASE64", StringComparison.OrdinalIgnoreCase) ||
encoding.Equals("BLOB", StringComparison.OrdinalIgnoreCase);
}

internal static Stream GetBlobData(string[] args, string keyEncoded)
{
if (IsEncodingBlob(args, keyEncoded))
{
bool isValidUri = Uri.TryCreate(keyEncoded, UriKind.Absolute, out Uri uri);
string dataStr;
if (isValidUri)
{
if (uri.Scheme == "data")
dataStr = uri.AbsolutePath.Substring(uri.AbsolutePath.IndexOf(",") + 1);
else
throw new InvalidDataException("Contains a valid URL; you should fetch that URL manually and convert the response to the stream.");
}
else
dataStr = keyEncoded;
byte[] dataBytes = Convert.FromBase64String(dataStr);
Stream blobStream = new MemoryStream(dataBytes);
return blobStream;
}
else
throw new InvalidOperationException("Not a blob. You should somehow handle it.");
}
#pragma warning restore IDE0060
}
}
5 changes: 3 additions & 2 deletions VisualCard.Calendar/Parts/Calendar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using VisualCard.Calendar.Parsers;
using VisualCard.Calendar.Parts.Comparers;
using VisualCard.Calendar.Parts.Enums;
using VisualCard.Parsers;
using VisualCard.Parts.Enums;

namespace VisualCard.Calendar.Parts
Expand Down Expand Up @@ -171,7 +172,7 @@ internal string SaveToString(Version version, Dictionary<CalendarPartsArrayEnum,
// Now, locate the prefix and assemble the line
string prefix = VCalendarParserTools.GetPrefixFromStringsEnum(stringEnum);
cardBuilder.Append($"{prefix}{VCalendarConstants._argumentDelimiter}");
cardBuilder.AppendLine($"{VCalendarParserTools.MakeStringBlock(stringValue, prefix.Length)}");
cardBuilder.AppendLine($"{VcardParserTools.MakeStringBlock(stringValue, prefix.Length)}");
}

// Then, enumerate all the arrays
Expand All @@ -198,7 +199,7 @@ internal string SaveToString(Version version, Dictionary<CalendarPartsArrayEnum,
string[] partArgumentsLines = partArguments.SplitNewLines();
partBuilder.Append($"{prefix}");
partBuilder.Append($"{partArguments}");
partBuilder.Append($"{VCalendarParserTools.MakeStringBlock(partRepresentation, partArgumentsLines[partArgumentsLines.Length - 1].Length + prefix.Length)}");
partBuilder.Append($"{VcardParserTools.MakeStringBlock(partRepresentation, partArgumentsLines[partArgumentsLines.Length - 1].Length + prefix.Length)}");
cardBuilder.AppendLine($"{partBuilder}");
}
}
Expand Down

0 comments on commit 4ac004f

Please sign in to comment.