Files
ArchiSteamFarm/ArchiSteamFarm/Program.cs

477 lines
16 KiB
C#
Raw Normal View History

2017-11-18 17:27:06 +01:00
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
//
2018-07-27 04:52:14 +02:00
// Copyright 2015-2018 Łukasz "JustArchi" Domeradzki
// 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
using System;
using System.Collections;
2016-03-09 03:10:33 +01:00
using System.Collections.Generic;
using System.Diagnostics;
2017-01-08 05:32:59 +01:00
using System.Globalization;
2015-10-25 06:16:50 +01:00
using System.IO;
2016-03-09 03:52:04 +01:00
using System.Linq;
2017-01-20 22:48:44 +01:00
using System.Resources;
2015-10-29 17:36:16 +01:00
using System.Threading.Tasks;
using ArchiSteamFarm.IPC;
2017-01-06 13:20:36 +01:00
using ArchiSteamFarm.Localization;
2018-09-08 01:03:55 +02:00
using ArchiSteamFarm.NLog;
2018-02-25 18:57:06 +01:00
using Newtonsoft.Json;
2017-06-26 01:37:14 +02:00
using NLog;
using NLog.Targets;
using SteamKit2;
2015-10-25 06:16:50 +01:00
namespace ArchiSteamFarm {
internal static class Program {
2018-08-06 01:21:36 +02:00
internal static byte LoadBalancingDelay => Math.Max(GlobalConfig?.LoginLimiterDelay ?? 0, (byte) 10);
2017-06-26 02:17:02 +02:00
internal static GlobalConfig GlobalConfig { get; private set; }
internal static GlobalDatabase GlobalDatabase { get; private set; }
2018-04-18 01:04:28 +02:00
internal static bool ProcessRequired { get; private set; }
internal static bool RestartAllowed { get; private set; } = true;
internal static WebBrowser WebBrowser { get; private set; }
2016-01-03 20:36:13 +01:00
private static readonly object ConsoleLock = new object();
2017-08-02 19:36:43 +02:00
// We need to keep this one assigned and not calculated on-demand
private static readonly string ProcessFileName = Process.GetCurrentProcess().MainModule.FileName;
2018-04-18 01:04:28 +02:00
private static readonly TaskCompletionSource<byte> ShutdownResetEvent = new TaskCompletionSource<byte>();
2015-10-29 17:36:16 +01:00
private static bool ShutdownSequenceInitialized;
2018-04-18 01:11:46 +02:00
private static bool SystemRequired;
internal static async Task Exit(byte exitCode = 0) {
2017-01-06 13:20:36 +01:00
if (exitCode != 0) {
ASF.ArchiLogger.LogGenericError(Strings.ErrorExitingWithNonZeroErrorCode);
2017-01-06 13:20:36 +01:00
}
2018-04-18 01:04:28 +02:00
await Shutdown(exitCode).ConfigureAwait(false);
2016-04-02 13:08:43 +02:00
Environment.Exit(exitCode);
}
2017-01-06 16:29:34 +01:00
internal static string GetUserInput(ASF.EUserInputType userInputType, string botName = SharedInfo.ASF) {
2016-11-09 09:26:07 +01:00
if (userInputType == ASF.EUserInputType.Unknown) {
2016-03-12 06:01:55 +01:00
return null;
}
2017-06-26 03:36:51 +02:00
if (GlobalConfig.Headless) {
ASF.ArchiLogger.LogGenericWarning(Strings.ErrorUserInputRunningInHeadlessMode);
2016-04-06 16:37:45 +02:00
return null;
}
2017-02-25 18:13:54 +01:00
string result;
2017-12-29 16:19:16 +01:00
2015-10-25 06:16:50 +01:00
lock (ConsoleLock) {
Logging.OnUserInputStart();
2016-05-13 06:32:42 +02:00
2017-12-29 16:19:16 +01:00
try {
switch (userInputType) {
case ASF.EUserInputType.DeviceID:
Console.Write(Bot.FormatBotResponse(Strings.UserInputDeviceID, botName));
result = Console.ReadLine();
break;
case ASF.EUserInputType.Login:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamLogin, botName));
result = Console.ReadLine();
break;
case ASF.EUserInputType.Password:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamPassword, botName));
result = Utilities.ReadLineMasked();
break;
case ASF.EUserInputType.SteamGuard:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamGuard, botName));
result = Console.ReadLine();
break;
case ASF.EUserInputType.SteamParentalPIN:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteamParentalPIN, botName));
result = Utilities.ReadLineMasked();
break;
case ASF.EUserInputType.TwoFactorAuthentication:
Console.Write(Bot.FormatBotResponse(Strings.UserInputSteam2FA, botName));
result = Console.ReadLine();
break;
default:
ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(userInputType), userInputType));
Console.Write(Bot.FormatBotResponse(string.Format(Strings.UserInputUnknown, userInputType), botName));
result = Console.ReadLine();
break;
}
if (!Console.IsOutputRedirected) {
Console.Clear(); // For security purposes
}
} catch (Exception e) {
Logging.OnUserInputEnd();
2017-12-29 16:19:16 +01:00
ASF.ArchiLogger.LogGenericException(e);
return null;
2016-04-13 16:48:11 +02:00
}
Logging.OnUserInputEnd();
2015-10-25 06:16:50 +01:00
}
2015-12-16 01:17:54 +01:00
2016-05-30 01:57:06 +02:00
return !string.IsNullOrEmpty(result) ? result.Trim() : null;
2015-10-25 06:16:50 +01:00
}
internal static async Task Restart() {
if (!await InitShutdownSequence().ConfigureAwait(false)) {
return;
}
2017-08-02 19:36:43 +02:00
string executableName = Path.GetFileNameWithoutExtension(ProcessFileName);
2018-06-11 01:24:54 +02:00
if (string.IsNullOrEmpty(executableName)) {
ASF.ArchiLogger.LogNullError(nameof(executableName));
return;
}
IEnumerable<string> arguments = Environment.GetCommandLineArgs().Skip(executableName.Equals(SharedInfo.AssemblyName) ? 1 : 0);
try {
2017-08-02 19:36:43 +02:00
Process.Start(ProcessFileName, string.Join(" ", arguments));
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
2017-07-05 07:07:03 +02:00
// Give new process some time to take over the window (if needed)
2017-07-05 07:49:40 +02:00
await Task.Delay(2000).ConfigureAwait(false);
2017-07-05 07:07:03 +02:00
2018-04-18 01:04:28 +02:00
ShutdownResetEvent.TrySetResult(0);
Environment.Exit(0);
}
private static void HandleCryptKeyArgument(string cryptKey) {
if (string.IsNullOrEmpty(cryptKey)) {
ASF.ArchiLogger.LogNullError(nameof(cryptKey));
return;
}
2018-08-19 14:37:23 +02:00
ArchiCryptoHelper.SetEncryptionKey(cryptKey);
}
private static void HandlePathArgument(string path) {
if (string.IsNullOrEmpty(path)) {
ASF.ArchiLogger.LogNullError(nameof(path));
return;
}
try {
Directory.SetCurrentDirectory(path);
} catch (Exception e) {
ASF.ArchiLogger.LogGenericException(e);
}
}
private static async Task Init(IReadOnlyCollection<string> args) {
2017-07-10 17:07:48 +02:00
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
2018-01-31 02:42:23 +01:00
// We must register our logging targets as soon as possible
Target.Register<HistoryTarget>(HistoryTarget.TargetName);
2017-07-02 10:10:30 +02:00
Target.Register<SteamTarget>(SteamTarget.TargetName);
2016-07-19 22:18:00 +02:00
2017-02-05 14:32:38 +01:00
InitCore(args);
await InitASF(args).ConfigureAwait(false);
}
private static async Task InitASF(IReadOnlyCollection<string> args) {
2018-06-16 08:04:02 +02:00
ASF.ArchiLogger.LogGenericInfo(SharedInfo.PublicIdentifier + " V" + SharedInfo.Version + " (" + SharedInfo.BuildInfo.Variant + "/" + SharedInfo.ModuleVersion + " | " + OS.Variant + ")");
2017-02-05 09:02:27 +01:00
await InitGlobalConfigAndLanguage().ConfigureAwait(false);
// Parse post-init args
if (args != null) {
ParsePostInitArgs(args);
}
OS.Init(SystemRequired, GlobalConfig.OptimizationMode);
2018-04-18 01:11:46 +02:00
2018-04-18 01:16:04 +02:00
await InitGlobalDatabaseAndServices().ConfigureAwait(false);
2017-07-01 04:06:33 +02:00
2018-09-17 00:42:24 +02:00
await ASF.UpdateAndRestart().ConfigureAwait(false);
2016-12-24 19:27:36 +01:00
await ASF.InitBots().ConfigureAwait(false);
2018-04-18 01:16:04 +02:00
ASF.InitEvents();
}
private static void InitCore(IReadOnlyCollection<string> args) {
2018-05-23 15:28:02 +02:00
Directory.SetCurrentDirectory(SharedInfo.HomeDirectory);
// Allow loading configs from source tree if it's a debug build
if (Debugging.IsDebugBuild) {
// Common structure is bin/(x64/)Debug/ArchiSteamFarm.exe, so we allow up to 4 directories up
for (byte i = 0; i < 4; i++) {
Directory.SetCurrentDirectory("..");
if (Directory.Exists(SharedInfo.ConfigDirectory)) {
break;
2017-02-05 14:32:38 +01:00
}
2018-05-23 15:28:02 +02:00
}
2017-02-05 14:32:38 +01:00
2018-05-23 15:28:02 +02:00
// If config directory doesn't exist after our adjustment, abort all of that
if (!Directory.Exists(SharedInfo.ConfigDirectory)) {
Directory.SetCurrentDirectory(SharedInfo.HomeDirectory);
2017-02-05 14:32:38 +01:00
}
}
// Parse pre-init args
if (args != null) {
ParsePreInitArgs(args);
}
2018-01-31 02:42:23 +01:00
Logging.InitCoreLoggers();
2017-02-05 14:32:38 +01:00
}
2017-02-05 09:02:27 +01:00
private static async Task InitGlobalConfigAndLanguage() {
2016-08-02 06:04:44 +02:00
string globalConfigFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalConfigFileName);
2016-07-31 17:38:14 +02:00
GlobalConfig = await GlobalConfig.Load(globalConfigFile).ConfigureAwait(false);
2016-03-06 23:28:56 +01:00
if (GlobalConfig == null) {
ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorGlobalConfigNotLoaded, globalConfigFile));
2017-01-06 22:18:41 +01:00
await Task.Delay(5 * 1000).ConfigureAwait(false);
await Exit(1).ConfigureAwait(false);
2017-01-08 05:32:59 +01:00
return;
}
2018-02-25 18:57:06 +01:00
if (Debugging.IsUserDebugging) {
2018-05-18 21:12:33 +02:00
ASF.ArchiLogger.LogGenericDebug(SharedInfo.GlobalConfigFileName + ": " + JsonConvert.SerializeObject(GlobalConfig, Formatting.Indented));
2018-02-25 18:57:06 +01:00
}
2017-01-08 05:32:59 +01:00
if (!string.IsNullOrEmpty(GlobalConfig.CurrentCulture)) {
try {
// GetCultureInfo() would be better but we can't use it for specifying neutral cultures such as "en"
CultureInfo culture = CultureInfo.CreateSpecificCulture(GlobalConfig.CurrentCulture);
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = culture;
2017-11-03 23:17:45 +01:00
} catch (Exception) {
ASF.ArchiLogger.LogGenericError(Strings.ErrorInvalidCurrentCulture);
2017-01-08 05:32:59 +01:00
}
2016-03-06 23:28:56 +01:00
}
2017-11-03 23:17:45 +01:00
if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.Equals("en")) {
return;
}
2017-02-07 17:35:52 +01:00
ResourceSet defaultResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.GetCultureInfo("en-US"), true, true);
if (defaultResourceSet == null) {
ASF.ArchiLogger.LogNullError(nameof(defaultResourceSet));
return;
2017-01-20 22:48:44 +01:00
}
2018-06-09 00:45:15 +02:00
HashSet<DictionaryEntry> defaultStringObjects = defaultResourceSet.Cast<DictionaryEntry>().ToHashSet();
if (defaultStringObjects.Count == 0) {
ASF.ArchiLogger.LogNullError(nameof(defaultStringObjects));
2017-02-07 17:25:32 +01:00
return;
}
2017-11-03 23:17:45 +01:00
ResourceSet currentResourceSet = Strings.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
if (currentResourceSet == null) {
ASF.ArchiLogger.LogNullError(nameof(currentResourceSet));
return;
2017-01-20 22:48:44 +01:00
}
2018-06-09 00:45:15 +02:00
HashSet<DictionaryEntry> currentStringObjects = currentResourceSet.Cast<DictionaryEntry>().ToHashSet();
if (currentStringObjects.Count >= defaultStringObjects.Count) {
// Either we have 100% finished translation, or we're missing it entirely and using en-US
2018-06-09 00:45:15 +02:00
HashSet<DictionaryEntry> testStringObjects = currentStringObjects.ToHashSet();
testStringObjects.ExceptWith(defaultStringObjects);
// If we got 0 as final result, this is the missing language
// Otherwise it's just a small amount of strings that happen to be the same
if (testStringObjects.Count == 0) {
currentStringObjects = testStringObjects;
}
2017-01-20 22:48:44 +01:00
}
if (currentStringObjects.Count < defaultStringObjects.Count) {
float translationCompleteness = currentStringObjects.Count / (float) defaultStringObjects.Count;
2017-11-03 23:17:45 +01:00
ASF.ArchiLogger.LogGenericInfo(string.Format(Strings.TranslationIncomplete, CultureInfo.CurrentUICulture.Name, translationCompleteness.ToString("P1")));
}
2017-02-05 09:02:27 +01:00
}
2017-01-20 22:48:44 +01:00
2017-02-05 09:02:27 +01:00
private static async Task InitGlobalDatabaseAndServices() {
2016-08-02 06:04:44 +02:00
string globalDatabaseFile = Path.Combine(SharedInfo.ConfigDirectory, SharedInfo.GlobalDatabaseFileName);
2016-07-31 17:38:14 +02:00
2017-01-06 22:18:41 +01:00
if (!File.Exists(globalDatabaseFile)) {
ASF.ArchiLogger.LogGenericInfo(Strings.Welcome);
2017-08-22 15:48:00 +02:00
await Task.Delay(10 * 1000).ConfigureAwait(false);
2017-11-29 02:07:57 +01:00
ASF.ArchiLogger.LogGenericWarning(Strings.WarningPrivacyPolicy);
await Task.Delay(5 * 1000).ConfigureAwait(false);
2017-01-06 22:18:41 +01:00
}
GlobalDatabase = await GlobalDatabase.Load(globalDatabaseFile).ConfigureAwait(false);
2016-03-07 02:39:55 +01:00
if (GlobalDatabase == null) {
ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorDatabaseInvalid, globalDatabaseFile));
2017-01-06 22:18:41 +01:00
await Task.Delay(5 * 1000).ConfigureAwait(false);
await Exit(1).ConfigureAwait(false);
2017-01-08 05:32:59 +01:00
return;
2016-03-07 02:39:55 +01:00
}
// If debugging is on, we prepare debug directory prior to running
2018-05-18 21:12:33 +02:00
if (Debugging.IsUserDebugging) {
ASF.ArchiLogger.LogGenericDebug(SharedInfo.GlobalDatabaseFileName + ": " + JsonConvert.SerializeObject(GlobalDatabase, Formatting.Indented));
2018-04-18 01:04:28 +02:00
Logging.EnableTraceLogging();
if (Directory.Exists(SharedInfo.DebugDirectory)) {
try {
Directory.Delete(SharedInfo.DebugDirectory, true);
await Task.Delay(1000).ConfigureAwait(false); // Dirty workaround giving Windows some time to sync
} catch (IOException e) {
ASF.ArchiLogger.LogGenericException(e);
}
}
2018-04-18 01:04:28 +02:00
Directory.CreateDirectory(SharedInfo.DebugDirectory);
DebugLog.AddListener(new Debugging.DebugListener());
DebugLog.Enabled = true;
}
WebBrowser.Init();
WebBrowser = new WebBrowser(ASF.ArchiLogger, GlobalConfig.WebProxy, true);
2018-04-18 01:04:28 +02:00
if (GlobalConfig.IPC) {
await ArchiKestrel.Start().ConfigureAwait(false);
2018-04-18 01:04:28 +02:00
}
2015-11-25 16:31:39 +01:00
}
private static async Task<bool> InitShutdownSequence() {
if (ShutdownSequenceInitialized) {
return false;
}
ShutdownSequenceInitialized = true;
// Sockets created by IPC might still be running for a short while after complete app shutdown
2017-11-30 23:39:35 +01:00
// Ensure that IPC is stopped before we finalize shutdown sequence
await ArchiKestrel.Stop().ConfigureAwait(false);
2017-11-30 23:39:35 +01:00
2017-08-09 00:18:38 +02:00
if (Bot.Bots.Count > 0) {
// Stop() function can block due to SK2 sockets, don't forget a maximum delay
await Task.WhenAny(Utilities.InParallel(Bot.Bots.Values.Select(bot => Task.Run(() => bot.Stop(true)))), Task.Delay(Bot.Bots.Count * WebBrowser.MaxTries * 1000)).ConfigureAwait(false);
2017-04-27 01:57:04 +02:00
2017-08-09 00:18:38 +02:00
// Extra second for Steam requests to go through
await Task.Delay(1000).ConfigureAwait(false);
2017-04-27 01:57:04 +02:00
}
2017-06-26 01:37:14 +02:00
LogManager.Flush();
return true;
}
2018-04-18 01:04:28 +02:00
private static async Task<int> Main(string[] args) {
2017-08-04 18:27:30 +02:00
// Initialize
await Init(args).ConfigureAwait(false);
2017-06-26 03:36:51 +02:00
2017-08-04 18:27:30 +02:00
// Wait for shutdown event
2018-04-18 01:04:28 +02:00
return await ShutdownResetEvent.Task.ConfigureAwait(false);
}
2017-11-30 23:39:35 +01:00
private static async void OnProcessExit(object sender, EventArgs e) => await Shutdown().ConfigureAwait(false);
2017-07-10 17:07:48 +02:00
private static async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) {
if (e?.ExceptionObject == null) {
ASF.ArchiLogger.LogNullError(nameof(e) + " || " + nameof(e.ExceptionObject));
return;
}
2018-04-08 05:24:21 +02:00
await ASF.ArchiLogger.LogFatalException((Exception) e.ExceptionObject).ConfigureAwait(false);
2017-07-10 17:07:48 +02:00
await Exit(1).ConfigureAwait(false);
}
2018-04-08 05:24:21 +02:00
private static async void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) {
2017-07-10 17:07:48 +02:00
if (e?.Exception == null) {
ASF.ArchiLogger.LogNullError(nameof(e) + " || " + nameof(e.Exception));
return;
}
2018-04-08 05:24:21 +02:00
await ASF.ArchiLogger.LogFatalException(e.Exception).ConfigureAwait(false);
// Normally we should abort the application here, but many tasks are in fact failing in SK2 code which we can't easily fix
// Thanks Valve.
e.SetObserved();
2017-07-10 17:07:48 +02:00
}
private static void ParsePostInitArgs(IReadOnlyCollection<string> args) {
2016-07-24 00:36:15 +02:00
if (args == null) {
ASF.ArchiLogger.LogNullError(nameof(args));
2016-07-24 00:36:15 +02:00
return;
}
bool cryptKeyNext = false;
2016-07-24 00:36:15 +02:00
foreach (string arg in args) {
switch (arg) {
2018-04-18 01:04:28 +02:00
case "--cryptkey" when !cryptKeyNext:
cryptKeyNext = true;
2017-10-21 23:03:45 +02:00
break;
2018-04-18 01:04:28 +02:00
case "--no-restart" when !cryptKeyNext:
RestartAllowed = false;
break;
2018-04-18 01:04:28 +02:00
case "--process-required" when !cryptKeyNext:
ProcessRequired = true;
2016-07-24 00:36:15 +02:00
break;
2018-04-18 01:04:28 +02:00
case "--system-required" when !cryptKeyNext:
2018-04-18 01:11:46 +02:00
SystemRequired = true;
2017-10-07 17:26:08 +02:00
break;
2016-07-24 00:36:15 +02:00
default:
if (cryptKeyNext) {
cryptKeyNext = false;
HandleCryptKeyArgument(arg);
2018-04-18 01:04:28 +02:00
} else if ((arg.Length > 11) && arg.StartsWith("--cryptkey=", StringComparison.Ordinal)) {
HandleCryptKeyArgument(arg.Substring(11));
}
2016-07-24 00:36:15 +02:00
break;
}
}
}
private static void ParsePreInitArgs(IReadOnlyCollection<string> args) {
2016-05-13 06:32:42 +02:00
if (args == null) {
ASF.ArchiLogger.LogNullError(nameof(args));
2016-05-13 06:32:42 +02:00
return;
}
bool pathNext = false;
2016-01-03 20:36:13 +01:00
foreach (string arg in args) {
switch (arg) {
2018-04-18 01:04:28 +02:00
case "--path" when !pathNext:
pathNext = true;
2016-05-30 01:57:06 +02:00
break;
2016-01-03 20:36:13 +01:00
default:
if (pathNext) {
pathNext = false;
HandlePathArgument(arg);
2018-04-18 01:04:28 +02:00
} else if ((arg.Length > 7) && arg.StartsWith("--path=", StringComparison.Ordinal)) {
HandlePathArgument(arg.Substring(7));
2016-01-03 20:36:13 +01:00
}
break;
}
}
}
2018-04-18 01:04:28 +02:00
private static async Task Shutdown(byte exitCode = 0) {
if (!await InitShutdownSequence().ConfigureAwait(false)) {
2017-01-06 16:29:34 +01:00
return;
}
2018-04-18 01:04:28 +02:00
ShutdownResetEvent.TrySetResult(exitCode);
2017-01-06 16:29:34 +01:00
}
2016-06-28 06:58:59 +02:00
}
2018-07-31 16:17:24 +02:00
}