Files
ArchiSteamFarm/ArchiSteamFarm/Utilities.cs

275 lines
7.5 KiB
C#
Raw Normal View History

2017-11-18 17:27:06 +01:00
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
//
2019-01-02 16:32:53 +01:00
// Copyright 2015-2019 Łukasz "JustArchi" Domeradzki
2018-07-27 04:52:14 +02:00
// Contact: JustArchi@JustArchi.net
2017-11-18 17:27:06 +01:00
//
2018-07-27 04:52:14 +02:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2017-11-18 17:27:06 +01:00
//
2018-07-27 04:52:14 +02:00
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2015-10-28 19:21:27 +01:00
2016-04-01 20:18:21 +02:00
using System;
2017-01-28 15:29:38 +01:00
using System.Collections.Generic;
using System.Globalization;
2016-04-01 20:18:21 +02:00
using System.Linq;
using System.Net;
2017-08-05 22:35:03 +02:00
using System.Text;
using System.Text.RegularExpressions;
2018-02-26 19:48:29 +01:00
using System.Threading;
using System.Threading.Tasks;
using Humanizer;
2017-09-23 06:44:37 +02:00
using Humanizer.Localisation;
2015-10-25 06:16:50 +01:00
namespace ArchiSteamFarm {
internal static class Utilities {
2018-04-23 05:53:58 +02:00
// Normally we wouldn't need to use this singleton, but we want to ensure decent randomness across entire program's lifetime
2017-07-02 10:00:02 +02:00
private static readonly Random Random = new Random();
2016-12-23 03:37:29 +01:00
internal static string GetArgsAsText(string[] args, byte argsToSkip, string delimiter) {
if ((args == null) || (args.Length <= argsToSkip) || string.IsNullOrEmpty(delimiter)) {
ASF.ArchiLogger.LogNullError(nameof(args) + " || " + nameof(argsToSkip) + " || " + nameof(delimiter));
2018-12-15 00:27:15 +01:00
return null;
}
return string.Join(delimiter, args.Skip(argsToSkip));
}
internal static string GetArgsAsText(string text, byte argsToSkip) {
if (string.IsNullOrEmpty(text)) {
ASF.ArchiLogger.LogNullError(nameof(text));
2018-12-15 00:27:15 +01:00
return null;
}
string[] args = text.Split((char[]) null, argsToSkip + 1, StringSplitOptions.RemoveEmptyEntries);
2018-12-15 00:27:15 +01:00
return args[args.Length - 1];
}
2016-05-13 06:32:42 +02:00
internal static string GetCookieValue(this CookieContainer cookieContainer, string url, string name) {
if ((cookieContainer == null) || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(name)) {
ASF.ArchiLogger.LogNullError(nameof(cookieContainer) + " || " + nameof(url) + " || " + nameof(name));
2018-12-15 00:27:15 +01:00
2016-05-30 01:57:06 +02:00
return null;
}
Uri uri;
try {
uri = new Uri(url);
} catch (UriFormatException e) {
ASF.ArchiLogger.LogGenericException(e);
2018-12-15 00:27:15 +01:00
return null;
}
2016-05-30 01:57:06 +02:00
CookieCollection cookies = cookieContainer.GetCookies(uri);
2018-12-15 00:27:15 +01:00
2018-03-09 15:43:25 +01:00
return cookies.Count > 0 ? (from Cookie cookie in cookies where cookie.Name.Equals(name) select cookie.Value).FirstOrDefault() : null;
}
internal static uint GetUnixTime() => (uint) DateTimeOffset.UtcNow.ToUnixTimeSeconds();
2016-12-23 03:37:29 +01:00
internal static void InBackground(Action action, bool longRunning = false) {
if (action == null) {
ASF.ArchiLogger.LogNullError(nameof(action));
2018-12-15 00:27:15 +01:00
return;
}
TaskCreationOptions options = TaskCreationOptions.DenyChildAttach;
if (longRunning) {
2018-02-26 19:48:29 +01:00
options |= TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
}
2018-02-26 19:48:29 +01:00
Task.Factory.StartNew(action, CancellationToken.None, options, TaskScheduler.Default);
}
internal static void InBackground<T>(Func<T> function, bool longRunning = false) {
if (function == null) {
ASF.ArchiLogger.LogNullError(nameof(function));
2018-12-15 00:27:15 +01:00
return;
}
TaskCreationOptions options = TaskCreationOptions.DenyChildAttach;
if (longRunning) {
2018-02-26 19:48:29 +01:00
options |= TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness;
}
2018-02-26 19:48:29 +01:00
Task.Factory.StartNew(function, CancellationToken.None, options, TaskScheduler.Default);
}
internal static async Task<IList<T>> InParallel<T>(IEnumerable<Task<T>> tasks) {
if (tasks == null) {
ASF.ArchiLogger.LogNullError(nameof(tasks));
2018-12-15 00:27:15 +01:00
return null;
}
IList<T> results;
switch (Program.GlobalConfig.OptimizationMode) {
case GlobalConfig.EOptimizationMode.MinMemoryUsage:
results = new List<T>();
foreach (Task<T> task in tasks) {
results.Add(await task.ConfigureAwait(false));
}
break;
default:
results = await Task.WhenAll(tasks).ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
break;
}
return results;
}
internal static async Task InParallel(IEnumerable<Task> tasks) {
if (tasks == null) {
ASF.ArchiLogger.LogNullError(nameof(tasks));
2018-12-15 00:27:15 +01:00
return;
}
switch (Program.GlobalConfig.OptimizationMode) {
case GlobalConfig.EOptimizationMode.MinMemoryUsage:
2018-12-15 00:27:15 +01:00
foreach (Task task in tasks) {
await task.ConfigureAwait(false);
}
break;
default:
await Task.WhenAll(tasks).ConfigureAwait(false);
2018-12-15 00:27:15 +01:00
break;
}
}
internal static bool IsValidCdKey(string key) {
if (string.IsNullOrEmpty(key)) {
ASF.ArchiLogger.LogNullError(nameof(key));
2018-12-15 00:27:15 +01:00
return false;
}
return Regex.IsMatch(key, @"^[0-9A-Z]{4,7}-[0-9A-Z]{4,7}-[0-9A-Z]{4,7}(?:(?:-[0-9A-Z]{4,7})?(?:-[0-9A-Z]{4,7}))?$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
internal static bool IsValidHexadecimalString(string text) {
if (string.IsNullOrEmpty(text)) {
ASF.ArchiLogger.LogNullError(nameof(text));
2018-12-15 00:27:15 +01:00
return false;
}
2018-12-26 16:56:28 +01:00
if (text.Length % 2 != 0) {
return false;
}
// ulong is 64-bits wide, each hexadecimal character is 4-bits wide, so we split each 16
const byte split = 16;
2018-12-15 00:27:15 +01:00
2018-12-26 16:56:28 +01:00
string lastHex;
2018-12-26 16:56:28 +01:00
if (text.Length >= split) {
StringBuilder hex = new StringBuilder(split);
foreach (char character in text) {
hex.Append(character);
if (hex.Length < split) {
continue;
}
if (!ulong.TryParse(hex.ToString(), NumberStyles.HexNumber, null, out _)) {
return false;
}
hex.Clear();
}
2018-12-26 16:56:28 +01:00
if (hex.Length == 0) {
return true;
}
lastHex = hex.ToString();
} else {
lastHex = text;
}
2018-12-26 16:56:28 +01:00
switch (lastHex.Length) {
case 2:
return byte.TryParse(lastHex, NumberStyles.HexNumber, null, out _);
case 4:
return ushort.TryParse(lastHex, NumberStyles.HexNumber, null, out _);
case 8:
return uint.TryParse(lastHex, NumberStyles.HexNumber, null, out _);
default:
return false;
}
}
2017-07-02 10:00:02 +02:00
internal static int RandomNext() {
lock (Random) {
return Random.Next();
}
}
2017-08-05 22:35:03 +02:00
internal static string ReadLineMasked(char mask = '*') {
StringBuilder result = new StringBuilder();
ConsoleKeyInfo keyInfo;
2018-12-15 00:27:15 +01:00
2017-08-05 22:35:03 +02:00
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter) {
if (!char.IsControl(keyInfo.KeyChar)) {
result.Append(keyInfo.KeyChar);
Console.Write(mask);
} else if ((keyInfo.Key == ConsoleKey.Backspace) && (result.Length > 0)) {
result.Remove(result.Length - 1, 1);
if (Console.CursorLeft == 0) {
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
} else {
2017-11-28 21:31:45 +01:00
// There are two \b characters here
Console.Write(@" ");
2017-08-05 22:35:03 +02:00
}
}
}
Console.WriteLine();
2018-12-15 00:27:15 +01:00
2017-08-05 22:35:03 +02:00
return result.ToString();
}
2017-11-16 22:13:34 +01:00
internal static IEnumerable<T> ToEnumerable<T>(this T item) {
yield return item;
}
2018-02-13 15:28:28 +01:00
internal static string ToHumanReadable(this TimeSpan timeSpan) => timeSpan.Humanize(3, maxUnit: TimeUnit.Year, minUnit: TimeUnit.Second);
2015-10-25 06:16:50 +01:00
}
}