The move!

This commit is contained in:
Jamie.Rees 2017-05-16 08:31:44 +01:00
commit 25526cc4d9
1147 changed files with 85 additions and 8524 deletions

View file

@ -0,0 +1,28 @@
using System;
using System.Text;
using Newtonsoft.Json;
namespace Ombi.Helpers
{
public class ByteConverterHelper
{
public static byte[] ReturnBytes(object obj)
{
var json = JsonConvert.SerializeObject(obj);
var bytes = Encoding.UTF8.GetBytes(json);
return bytes;
}
public static T ReturnObject<T>(byte[] bytes)
{
var json = Encoding.UTF8.GetString(bytes);
var model = JsonConvert.DeserializeObject<T>(json);
return model;
}
public static string ReturnFromBytes(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
}
}

View file

@ -0,0 +1,46 @@
using System;
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Ombi.Helpers
{
public class ClaimConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(System.Security.Claims.Claim));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var claim = (System.Security.Claims.Claim)value;
JObject jo = new JObject();
jo.Add("Type", claim.Type);
jo.Add("Value", IsJson(claim.Value) ? new JRaw(claim.Value) : new JValue(claim.Value));
jo.Add("ValueType", claim.ValueType);
jo.Add("Issuer", claim.Issuer);
jo.Add("OriginalIssuer", claim.OriginalIssuer);
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
string type = (string)jo["Type"];
JToken token = jo["Value"];
string value = token.Type == JTokenType.String ? (string)token : token.ToString(Formatting.None);
string valueType = (string)jo["ValueType"];
string issuer = (string)jo["Issuer"];
string originalIssuer = (string)jo["OriginalIssuer"];
return new Claim(type, value, valueType, issuer, originalIssuer);
}
private bool IsJson(string val)
{
return (val != null &&
(val.StartsWith("[") && val.EndsWith("]")) ||
(val.StartsWith("{") && val.EndsWith("}")));
}
}
}

View file

@ -0,0 +1,19 @@
using System.Text.RegularExpressions;
namespace Ombi.Helpers
{
public static class HtmlHelper
{
public static string RemoveHtml(this string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
var step2 = Regex.Replace(step1, @"\s{2,}", " ");
return step2;
}
}
}

View file

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
namespace Ombi.Helpers
{
public static class LinqHelpers
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> knownKeys = new HashSet<TKey>();
foreach (TSource source1 in source)
{
if (knownKeys.Add(keySelector(source1)))
yield return source1;
}
}
}
}

View file

@ -0,0 +1,10 @@
using Microsoft.Extensions.Logging;
namespace Ombi.Helpers
{
public class LoggingEvents
{
public static EventId ApiException => new EventId(1000);
public static EventId CacherException => new EventId(2000);
}
}

View file

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard1.6</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EasyCrypto" Version="3.3.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="1.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="System.Security.Claims" Version="4.3.0" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,114 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2017 Jamie Rees
// File: PlexHelper.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
namespace Ombi.Helpers
{
public class PlexHelper
{
public static string GetProviderIdFromPlexGuid(string guid)
{
if (string.IsNullOrEmpty(guid))
return guid;
var guidSplit = guid.Split(new[] { '/', '?' }, StringSplitOptions.RemoveEmptyEntries);
if (guidSplit.Length > 1)
{
return guidSplit[1];
}
return string.Empty;
}
public static EpisodeModelHelper GetSeasonsAndEpisodesFromPlexGuid(string guid)
{
var ep = new EpisodeModelHelper();
//guid="com.plexapp.agents.thetvdb://269586/2/8?lang=en"
if (string.IsNullOrEmpty(guid))
return null;
try
{
var guidSplit = guid.Split(new[] { '/', '?' }, StringSplitOptions.RemoveEmptyEntries);
if (guidSplit.Length > 2)
{
ep.ProviderId = guidSplit[1];
ep.SeasonNumber = int.Parse(guidSplit[2]);
ep.EpisodeNumber = int.Parse(guidSplit[3]);
}
return ep;
}
catch (Exception e)
{
return ep;
}
}
public static int GetSeasonNumberFromTitle(string title)
{
if (string.IsNullOrEmpty(title))
{
return 0;
}
var split = title.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 2)
{
// Cannot get the season number, it's not in the usual format
return 0;
}
int season;
if (int.TryParse(split[1], out season))
{
return season;
}
return 0;
}
public static string GetPlexMediaUrl(string machineId, string mediaId)
{
var url =
$"https://app.plex.tv/web/app#!/server/{machineId}/details?key=library%2Fmetadata%2F{mediaId}";
return url;
}
public static string FormatGenres(string tags)
{
var split = tags.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
return string.Join(", ", split);
}
}
public class EpisodeModelHelper
{
public string ProviderId { get; set; }
public int SeasonNumber { get; set; }
public int EpisodeNumber { get; set; }
}
}

View file

@ -0,0 +1,15 @@
using Newtonsoft.Json;
namespace Ombi.Helpers
{
public static class SerializerSettings
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
//TypeNameHandling = TypeNameHandling.Objects,
//TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
NullValueHandling = NullValueHandling.Ignore
};
}
}

View file

@ -0,0 +1,101 @@
using EasyCrypto;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Ombi.Helpers
{
public static class StringCipher
{
/// <summary>
/// Decrypts the specified cipher text.
/// </summary>
/// <param name="cipherText">The cipher text.</param>
/// <param name="passPhrase">The pass phrase.</param>
/// <returns></returns>
public static string Decrypt(string cipherText, string passPhrase)
{
var fullCipher = Convert.FromBase64String(cipherText);
var iv = new byte[16];
var cipher = new byte[16];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
var key = Encoding.UTF8.GetBytes(passPhrase);
using (var aesAlg = Aes.Create())
{
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
string result;
using (var msDecrypt = new MemoryStream(cipher))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}
return result;
}
}
}
/// <summary>
/// Encrypts the specified plain text.
/// </summary>
/// <param name="plainText">The plain text.</param>
/// <param name="passPhrase">The pass phrase.</param>
/// <returns></returns>
public static string Encrypt(string plainText, string passPhrase)
{
var key = Encoding.UTF8.GetBytes(passPhrase);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
return Convert.ToBase64String(result);
}
}
}
}
public static string EncryptString(string text, string keyString)
{
var t = Encoding.UTF8.GetBytes(text);
var result = Convert.ToBase64String(t);
return result;
}
public static string DecryptString(string cipherText, string keyString)
{
var textAsBytes = Convert.FromBase64String(cipherText);
var result = Encoding.UTF8.GetString(textAsBytes);
return result;
}
}
}

View file

@ -0,0 +1,44 @@
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Ombi.Helpers
{
public static class StringHelper
{
public static bool Contains(this string paragraph, string word, CompareOptions opts)
{
return CultureInfo.CurrentUICulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
}
public static string CalcuateMd5Hash(this string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
}
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.UTF8.GetBytes(input);
var hash = md5.ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var t in hash)
{
sb.Append(t.ToString("x2"));
}
return sb.ToString();
}
}
public static string GetSha1Hash(this string input)
{
var sha1 = SHA1.Create();
return string.Join("", (sha1.ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("x2")).ToArray());
}
}
}

View file

@ -0,0 +1,123 @@
using System;
namespace Ombi.Helpers
{
public static class UriHelper
{
private const string Https = "Https";
private const string Http = "Http";
public static Uri ReturnUri(this string val)
{
if (val == null)
{
throw new ApplicationSettingsException("The URI is null, please check your settings to make sure you have configured the applications correctly.");
}
try
{
var uri = new UriBuilder();
if (val.StartsWith("http://", StringComparison.Ordinal))
{
uri = new UriBuilder(val);
}
else if (val.StartsWith("https://", StringComparison.Ordinal))
{
uri = new UriBuilder(val);
}
else if (val.Contains(":"))
{
var split = val.Split(':', '/');
int port;
int.TryParse(split[1], out port);
uri = split.Length == 3
? new UriBuilder(Http, split[0], port, "/" + split[2])
: new UriBuilder(Http, split[0], port);
}
else
{
uri = new UriBuilder(Http, val);
}
return uri.Uri;
}
catch (Exception exception)
{
throw new Exception(exception.Message, exception);
}
}
/// <summary>
/// Returns the URI.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="port">The port.</param>
/// <param name="ssl">if set to <c>true</c> [SSL].</param>
/// <param name="subdir">The subdir.</param>
/// <returns></returns>
/// <exception cref="ApplicationSettingsException">The URI is null, please check your settings to make sure you have configured the applications correctly.</exception>
/// <exception cref="System.Exception"></exception>
public static Uri ReturnUri(this string val, int port, bool ssl = default(bool))
{
if (val == null)
{
throw new ApplicationSettingsException("The URI is null, please check your settings to make sure you have configured the applications correctly.");
}
try
{
var uri = new UriBuilder();
if (val.StartsWith("http://", StringComparison.Ordinal))
{
var split = val.Split('/');
uri = split.Length >= 4 ? new UriBuilder(Http, split[2], port, "/" + split[3]) : new UriBuilder(new Uri($"{val}:{port}"));
}
else if (val.StartsWith("https://", StringComparison.Ordinal))
{
var split = val.Split('/');
uri = split.Length >= 4
? new UriBuilder(Https, split[2], port, "/" + split[3])
: new UriBuilder(Https, split[2], port);
}
else if (ssl)
{
uri = new UriBuilder(Https, val, port);
}
else
{
uri = new UriBuilder(Http, val, port);
}
return uri.Uri;
}
catch (Exception exception)
{
throw new Exception(exception.Message, exception);
}
}
public static Uri ReturnUriWithSubDir(this string val, int port, bool ssl, string subDir)
{
var uriBuilder = new UriBuilder(val);
if (ssl)
{
uriBuilder.Scheme = Https;
}
if (!string.IsNullOrEmpty(subDir))
{
uriBuilder.Path = subDir;
}
uriBuilder.Port = port;
return uriBuilder.Uri;
}
}
public class ApplicationSettingsException : Exception
{
public ApplicationSettingsException(string s) : base(s)
{
}
}
}